热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

微信小程序--Ble蓝牙

本文主要介绍了微信小程序--Ble蓝牙的实现方法。文中附上源码下载,具有很好的参考价值。下面跟着小编一起来看下吧

有一段时间没有。没有写关于小程序的文章了。3月28日,微信的api又一次新的更新。期待已久的蓝牙api更新。就开始撸一番。

源码地址

1.简述

蓝牙适配器接口是基础库版本 1.1.0 开始支持。

iOS 微信客户端 6.5.6 版本开始支持,Android 客户端暂不支持

蓝牙总共增加了18个api接口。

2.Api分类

搜索类

连接类

通信类

3.API的具体使用

详细见官网:

https://mp.weixin.qq.com/debug/wxadoc/dev/api/bluetooth.html#wxgetconnectedbluethoothdevicesobject

4. 案例实现

4.1 搜索蓝牙设备

/**
 * 搜索设备界面
 */
Page({
 data: {
 logs: [],
 list:[],
 },
 onLoad: function () {
 console.log('onLoad')
var that = this;
// const SDKVersion = wx.getSystemInfoSync().SDKVersion || '1.0.0'
// const [MAJOR, MINOR, PATCH] = SDKVersion.split('.').map(Number)
// console.log(SDKVersion);
// console.log(MAJOR);
// console.log(MINOR);
// console.log(PATCH);

// const canIUse = apiName => {
// if (apiName === 'showModal.cancel') {
//  return MAJOR >= 1 && MINOR >= 1
// }
// return true
// }

// wx.showModal({
// success: function(res) {
//  if (canIUse('showModal.cancel')) {
//  console.log(res.cancel)
//  }
// }
// })
  //获取适配器
  wx.openBluetoothAdapter({
  success: function(res){
  // success
  console.log("-----success----------");
   console.log(res);
   //开始搜索
  wx.startBluetoothDevicesDiscovery({
 services: [],
 success: function(res){
 // success
  console.log("-----startBluetoothDevicesDiscovery--success----------");
  console.log(res);
 },
 fail: function(res) {
 // fail
  console.log(res);
 },
 complete: function(res) {
 // complete
  console.log(res);
 }
})

  },
  fail: function(res) {
   console.log("-----fail----------");
  // fail
   console.log(res);
  },
  complete: function(res) {
  // complete
   console.log("-----complete----------");
   console.log(res);
  }
 })

  wx.getBluetoothDevices({
  success: function(res){
   // success
   //{devices: Array[11], errMsg: "getBluetoothDevices:ok"}
   console.log("getBluetoothDevices");
   console.log(res);
   that.setData({
   list:res.devices
   });
   console.log(that.data.list);
  },
  fail: function(res) {
   // fail
  },
  complete: function(res) {
   // complete
  }
  })

 },
 onShow:function(){

 },
 //点击事件处理
 bindViewTap: function(e) {
  console.log(e.currentTarget.dataset.title);
  console.log(e.currentTarget.dataset.name);
  console.log(e.currentTarget.dataset.advertisData);

 var title = e.currentTarget.dataset.title;
 var name = e.currentTarget.dataset.name;
  wx.redirectTo({
  url: '../conn/conn?deviceId='+title+'&name='+name,
  success: function(res){
   // success
  },
  fail: function(res) {
   // fail
  },
  complete: function(res) {
   // complete
  }
  })
 },
})

4.2连接 获取数据

/**
 * 连接设备。获取数据
 */
Page({
 data: {
  motto: 'Hello World',
  userInfo: {},
  deviceId: '',
  name: '',
  serviceId: '',
  services: [],
  cd20: '',
  cd01: '',
  cd02: '',
  cd03: '',
  cd04: '',
  characteristics20: null,
  characteristics01: null,
  characteristics02: null,
  characteristics03: null,
  characteristics04: null,
  result,

 },
 onLoad: function (opt) {
  var that = this;
  console.log("onLoad");
  console.log('deviceId=' + opt.deviceId);
  console.log('name=' + opt.name);
  that.setData({ deviceId: opt.deviceId });
  /**
   * 监听设备的连接状态
   */
  wx.onBLEConnectionStateChanged(function (res) {
   console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  })
  /**
   * 连接设备
   */
  wx.createBLEConnection({
   deviceId: that.data.deviceId,
   success: function (res) {
    // success
    console.log(res);
    /**
     * 连接成功,后开始获取设备的服务列表
     */
    wx.getBLEDeviceServices({
     // 这里的 deviceId 需要在上面的 getBluetoothDevices中获取
     deviceId: that.data.deviceId,
     success: function (res) {
      console.log('device services:', res.services)
      that.setData({ services: res.services });
      console.log('device services:', that.data.services[1].uuid);
      that.setData({ serviceId: that.data.services[1].uuid });
      console.log('--------------------------------------');
      console.log('device设备的id:', that.data.deviceId);
      console.log('device设备的服务id:', that.data.serviceId);
      /**
       * 延迟3秒,根据服务获取特征 
       */
      setTimeout(function () {
       wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要在上面的 getBluetoothDevices
        deviceId: that.data.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: that.data.serviceId,
        success: function (res) {
         console.log('000000000000' + that.data.serviceId);
         console.log('device getBLEDeviceCharacteristics:', res.characteristics)
         for (var i = 0; i <5; i++) {
          if (res.characteristics[i].uuid.indexOf("cd20") != -1) {
           that.setData({
            cd20: res.characteristics[i].uuid,
            characteristics20: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd01") != -1) {
           that.setData({
            cd01: res.characteristics[i].uuid,
            characteristics01: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd02") != -1) {
           that.setData({
            cd02: res.characteristics[i].uuid,
            characteristics02: res.characteristics[i]
           });
          } if (res.characteristics[i].uuid.indexOf("cd03") != -1) {
           that.setData({
            cd03: res.characteristics[i].uuid,
            characteristics03: res.characteristics[i]
           });
          }
          if (res.characteristics[i].uuid.indexOf("cd04") != -1) {
           that.setData({
            cd04: res.characteristics[i].uuid,
            characteristics04: res.characteristics[i]
           });
          }
         }
         console.log('cd01= ' + that.data.cd01 + 'cd02= ' + that.data.cd02 + 'cd03= ' + that.data.cd03 + 'cd04= ' + that.data.cd04 + 'cd20= ' + that.data.cd20);
         /**
          * 回调获取 设备发过来的数据
          */
         wx.onBLECharacteristicValueChange(function (characteristic) {
          console.log('characteristic value comed:', characteristic.value)
          //{value: ArrayBuffer, deviceId: "D8:00:D2:4F:24:17", serviceId: "ba11f08c-5f14-0b0d-1080-007cbe238851-0x600000460240", characteristicId: "0000cd04-0000-1000-8000-00805f9b34fb-0x60800069fb80"}
          /**
           * 监听cd04cd04中的结果
           */
          if (characteristic.characteristicId.indexOf("cd01") != -1) {
           const result = characteristic.value;
           const hex = that.buf2hex(result);
           console.log(hex);
          }
          if (characteristic.characteristicId.indexOf("cd04") != -1) {
           const result = characteristic.value;
           const hex = that.buf2hex(result);
           console.log(hex);
           that.setData({ result: hex });
          }

         })
         /**
          * 顺序开发设备特征notifiy
          */
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd01,
          state: true,
          success: function (res) {
           // success
           console.log('notifyBLECharacteristicValueChanged success', res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd02,
          state: true,
          success: function (res) {
           // success
           console.log('notifyBLECharacteristicValueChanged success', res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })
         wx.notifyBLECharacteristicValueChanged({
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd03,
          state: true,
          success: function (res) {
           // success
           console.log('notifyBLECharacteristicValueChanged success', res);
          },
          fail: function (res) {
           // fail
          },
          complete: function (res) {
           // complete
          }
         })

         wx.notifyBLECharacteristicValueChanged({
          // 启用 notify 功能
          // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          characteristicId: that.data.cd04,
          state: true,
          success: function (res) {
           console.log('notifyBLECharacteristicValueChanged success', res)
          }
         })

        }, fail: function (res) {
         console.log(res);
        }
       })
      }
       , 1500);
     }
    })
   },
   fail: function (res) {
    // fail
   },
   complete: function (res) {
    // complete
   }
  })
 },

 /**
  * 发送 数据到设备中
  */
 bindViewTap: function () {
  var that = this;
  var hex = 'AA5504B10000B5'
  var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
   return parseInt(h, 16)
  }))
  console.log(typedArray)
  console.log([0xAA, 0x55, 0x04, 0xB1, 0x00, 0x00, 0xB5])
  var buffer1 = typedArray.buffer
  console.log(buffer1)
  wx.writeBLECharacteristicValue({
   deviceId: that.data.deviceId,
   serviceId: that.data.serviceId,
   characteristicId: that.data.cd20,
   value: buffer1,
   success: function (res) {
    // success
    console.log("success 指令发送成功");
    console.log(res);
   },
   fail: function (res) {
    // fail
    console.log(res);
   },
   complete: function (res) {
    // complete
   }
  })

 },
 /**
  * ArrayBuffer 转换为 Hex
  */
 buf2hex: function (buffer) { // buffer is an ArrayBuffer
  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
 }
})

5.效果展示

这里写图片描述

发送校验指令。获取结果

这里写图片描述

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!


推荐阅读
  • Java验证码——kaptcha的使用配置及样式
    本文介绍了如何使用kaptcha库来实现Java验证码的配置和样式设置,包括pom.xml的依赖配置和web.xml中servlet的配置。 ... [详细]
  • 本文内容为asp.net微信公众平台开发的目录汇总,包括数据库设计、多层架构框架搭建和入口实现、微信消息封装及反射赋值、关注事件、用户记录、回复文本消息、图文消息、服务搭建(接入)、自定义菜单等。同时提供了示例代码和相关的后台管理功能。内容涵盖了多个方面,适合综合运用。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文介绍了九度OnlineJudge中的1002题目“Grading”的解决方法。该题目要求设计一个公平的评分过程,将每个考题分配给3个独立的专家,如果他们的评分不一致,则需要请一位裁判做出最终决定。文章详细描述了评分规则,并给出了解决该问题的程序。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 本文介绍了P1651题目的描述和要求,以及计算能搭建的塔的最大高度的方法。通过动态规划和状压技术,将问题转化为求解差值的问题,并定义了相应的状态。最终得出了计算最大高度的解法。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 动态规划算法的基本步骤及最长递增子序列问题详解
    本文详细介绍了动态规划算法的基本步骤,包括划分阶段、选择状态、决策和状态转移方程,并以最长递增子序列问题为例进行了详细解析。动态规划算法的有效性依赖于问题本身所具有的最优子结构性质和子问题重叠性质。通过将子问题的解保存在一个表中,在以后尽可能多地利用这些子问题的解,从而提高算法的效率。 ... [详细]
author-avatar
不点包子
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有