11、接收蓝牙返回消息(onBLECharacteristicValueChange)

雨点打透心脏的1/2处 2022-04-24 01:34 546阅读 0赞

wx.onBLECharacteristicValueChange(function callback)

基础库 1.1.0 开始支持,低版本需做兼容处理。

监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification。

参数

function callback

低功耗蓝牙设备的特征值变化事件的回调函数

参数

Object res































属性 类型 说明
deviceId string 蓝牙设备 id
serviceId string 蓝牙特征值对应服务的 uuid
characteristicId string 蓝牙特征值的 uuid
value ArrayBuffer 特征值最新的值

lanyatest.wxml代码:

  1. <!--pages/lanyatest/lanyatest.wxml-->
  2. <view class="contentview">
  3. <view class='myview' >
  4. {
  5. {info}}
  6. </view>
  7. <button type="primary" class="button" bindtap="lanyatest1">1初始化蓝牙</button>
  8. <button type="primary" class="button" bindtap="lanyatest2">2获取蓝牙状态</button>
  9. <button type="primary" class="button" bindtap="lanyatest3">3搜索周边设备</button>
  10. <button type="primary" class="button" bindtap="lanyatest4">4获取所有设备</button>
  11. <block wx:for="{
  12. {devices}}" wx:key="{
  13. {test}}">
  14. <button type="primary" class="button" id="{
  15. {item.deviceId}}" style='background-color:red' bindtap="lanyaconnect">5连接{
  16. {item.name}} </button>
  17. </block>
  18. <button type="primary" class="button" bindtap="lanyatest6">6停止搜索周边蓝牙设备</button>
  19. <button type="primary" class="button" bindtap="lanyatest7">7获取所有service</button>
  20. <button type="primary" class="button" bindtap="lanyatest8">8获取所有特征值</button>
  21. <button type="primary" class="button" bindtap="lanyatest9">9启用特征值变化notify</button>
  22. <button type="primary" class="button" bindtap="lanyatest10">10接收蓝牙返回消息</button>
  23. </view>

lanyatest.js代码:

  1. // pages/lanyatest/lanyatest.js
  2. Page({
  3. /**
  4. * 页面的初始数据
  5. */
  6. data: {
  7. info:"未初始化蓝牙适配器",
  8. connectedDeviceId:"",
  9. deviceId:"",
  10. services:"",
  11. servicesUUID:"0000ff00-0000-1000-8000-00805f9b34fb",
  12. serviceId:"",
  13. notifyCharacteristicsId:"",
  14. writeCharacteristicsId: "",
  15. },
  16. lanyatest1(event){
  17. var that = this;
  18. wx.openBluetoothAdapter({
  19. success: function (res) {
  20. console.log('初始化蓝牙适配器成功')
  21. //页面日志显示
  22. that.setData({
  23. info: '初始化蓝牙适配器成功'
  24. })
  25. },
  26. fail: function (res) {
  27. console.log('请打开蓝牙和定位功能')
  28. that.setData({
  29. info: '请打开蓝牙和定位功能'
  30. })
  31. }
  32. })
  33. },
  34. lanyatest2(event){
  35. var that = this;
  36. wx.getBluetoothAdapterState({
  37. success: function (res) {
  38. //打印相关信息
  39. console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);
  40. that.setData({
  41. info: JSON.stringify(res.errMsg) +"\n蓝牙是否可用:" + res.available
  42. })
  43. },
  44. fail: function (res) {
  45. //打印相关信息
  46. console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available);
  47. that.setData({
  48. info: JSON.stringify(res.errMsg) + "\n蓝牙是否可用:" + res.available
  49. })
  50. }
  51. })
  52. },
  53. lanyatest3(event){
  54. var that = this;
  55. wx.startBluetoothDevicesDiscovery({
  56. services: ['FEE7'], //如果填写了此UUID,那么只会搜索出含有这个UUID的设备,建议一开始先不填写或者注释掉这一句
  57. success: function (res) {
  58. that.setData({
  59. info: "搜索设备" + JSON.stringify(res),
  60. })
  61. console.log('搜索设备返回' + JSON.stringify(res))
  62. }
  63. })
  64. },
  65. lanyatest4(event){
  66. var that = this;
  67. wx.getBluetoothDevices({
  68. success: function (res) {
  69. that.setData({
  70. info: "设备列表\n" + JSON.stringify(res.devices),
  71. devices: res.devices
  72. })
  73. console.log('搜设备数目:' + res.devices.length)
  74. console.log('设备信息:\n' + JSON.stringify(res.devices)+"\n")
  75. }
  76. })
  77. },
  78. lanyaconnect(event){
  79. var that = this;
  80. wx.createBLEConnection({
  81. deviceId: event.currentTarget.id,
  82. success: function (res) {
  83. console.log('调试信息:' + res.errMsg);
  84. that.setData({
  85. connectedDeviceId: event.currentTarget.id,
  86. info: "MAC地址:" + event.currentTarget.id + ' 调试信息:' + res.errMsg,
  87. })
  88. },
  89. fail: function () {
  90. console.log("连接失败");
  91. },
  92. })
  93. },
  94. lanyatest6(event){
  95. var that = this;
  96. wx.stopBluetoothDevicesDiscovery({
  97. success: function (res) {
  98. console.log("停止搜索" + JSON.stringify(res.errMsg));
  99. that.setData({
  100. info: "停止搜索" + JSON.stringify(res.errMsg),
  101. })
  102. }
  103. })
  104. },
  105. lanyatest7(event){
  106. var that = this;
  107. wx.getBLEDeviceServices({
  108. // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
  109. deviceId: that.data.connectedDeviceId,
  110. success: function (res) {
  111. console.log('services UUID:\n', JSON.stringify(res.services));
  112. for (var i = 0; i < res.services.length; i++) {
  113. console.log("第"+(i+1) + "个UUID:" + res.services[i].uuid+"\n")
  114. }
  115. that.setData({
  116. services: res.services,
  117. info: JSON.stringify(res.services),
  118. })
  119. }
  120. })
  121. },
  122. lanyatest8(event){
  123. var that = this;
  124. var myUUID = that.data.servicesUUID;//具有写、通知属性的服务uuid
  125. console.log('UUID' + myUUID)
  126. wx.getBLEDeviceCharacteristics({
  127. // 这里的 deviceId 需要在上面的接口中获取
  128. deviceId: that.data.connectedDeviceId,
  129. // 这里的 serviceId 需要在上面的 接口中获取
  130. serviceId: myUUID,
  131. success: function (res) {
  132. console.log("%c getBLEDeviceCharacteristics", "color:red;");
  133. for (var i = 0; i < res.characteristics.length; i++) {
  134. console.log('特征值:' + res.characteristics[i].uuid)
  135. if (res.characteristics[i].properties.notify) {
  136. console.log("notifyServicweId:", myUUID);
  137. console.log("notifyCharacteristicsId:", res.characteristics[i].uuid);
  138. that.setData({
  139. notifyServicweId: myUUID,
  140. notifyCharacteristicsId: "0000ff01-0000-1000-8000-00805f9b34fb",//手动设置notifyCharacteristicsId为这个UUID,为了方便写死在这里
  141. })
  142. }
  143. if (res.characteristics[i].properties.write) {
  144. console.log("writeServicweId:", myUUID);
  145. console.log("writeCharacteristicsId:", res.characteristics[i].uuid);
  146. that.setData({
  147. writeServicweId: myUUID,
  148. //writeCharacteristicsId: res.characteristics[i].uuid,
  149. writeCharacteristicsId: "0000ff02-0000-1000-8000-00805f9b34fb",//手动设置writeCharacteristicsId为这个UUID,为了方便写死在这里
  150. })
  151. }
  152. }
  153. console.log('device getBLEDeviceCharacteristics:', res.characteristics);
  154. that.setData({
  155. msg: JSON.stringify(res.characteristics),
  156. })
  157. },
  158. fail: function () {
  159. console.log("fail");
  160. },
  161. })
  162. },
  163. lanyatest9(event){
  164. var that = this;
  165. var notifyServicweId = that.data.servicesUUID; //具有写、通知属性的服务uuid
  166. var notifyCharacteristicsId = that.data.notifyCharacteristicsId;
  167. console.log("启用notify的serviceId", notifyServicweId);
  168. console.log("启用notify的notifyCharacteristicsId", notifyCharacteristicsId);
  169. wx.notifyBLECharacteristicValueChange({
  170. state: true, // 启用 notify 功能
  171. deviceId: that.data.connectedDeviceId,
  172. // 这里的 serviceId 就是that.data.servicesUUID
  173. serviceId: notifyServicweId,
  174. characteristicId: that.data.notifyCharacteristicsId,
  175. success: function (res) {
  176. console.log('notifyBLECharacteristicValueChange success', res.errMsg)
  177. var msg = '启动notify:' + res.errMsg
  178. that.setData({
  179. info: msg
  180. })
  181. },
  182. fail: function () {
  183. console.log('启动notify:' + res.errMsg);
  184. },
  185. })
  186. },
  187. lanyatest10(event){
  188. var that = this;
  189. console.log("开始接收数据");
  190. wx.onBLECharacteristicValueChange(function (res) {
  191. console.log("characteristicId:" + res.characteristicId)
  192. console.log("serviceId:" + res.serviceId)
  193. console.log("deviceId" + res.deviceId)
  194. console.log("Length:" + res.value.byteLength)
  195. console.log("hexvalue:" + ab2hex(res.value))
  196. that.setData({
  197. info: that.data.info + ab2hex(res.value)
  198. })
  199. })
  200. },
  201. //我删除了自动生成的生命周期函数
  202. })
  203. // ArrayBuffer转16进度字符串示例
  204. function ab2hex(buffer) {
  205. var hexArr = Array.prototype.map.call(
  206. new Uint8Array(buffer),
  207. function (bit) {
  208. return ('00' + bit.toString(16)).slice(-2)
  209. }
  210. )
  211. return hexArr.join(',');
  212. }

lanyatest.wxss代码:

  1. /* pages/lanyatest/lanyatest.wxss */
  2. .vertical{
  3. display: flex;
  4. flex-direction: column;
  5. }
  6. /**index.wxss**/
  7. .horizontal{
  8. display: flex;
  9. flex-direction: row;
  10. }
  11. .btinfo{
  12. height:100px;
  13. }
  14. .contentview {
  15. margin: 0 10px;
  16. }
  17. .button {
  18. margin: 5px;
  19. }
  20. .myview{
  21. height:200px;
  22. word-break:break-all;/* 自动换行 */
  23. }

真机调试结果:

打开串口调试助手愉快地发消息了

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MjM0MDg3_size_16_color_FFFFFF_t_70

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MjM0MDg3_size_16_color_FFFFFF_t_70 1

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM0MjM0MDg3_size_16_color_FFFFFF_t_70 2

发表评论

表情:
评论列表 (有 0 条评论,546人围观)

还没有评论,来说两句吧...

相关阅读

    相关 设计

    1.问:什么是蓝牙通信? 答:蓝牙通讯最初设计初衷是方便移动电话(手机)与配件之间进行低成本、低功耗无线通信连接,现在已经成为IEEE802.15标准,得到全球上万家厂商支持