瀏覽代碼

feature: 蓝牙数据发送监听和接收数据监听处理

Damon 7 月之前
父節點
當前提交
49003a7b19
共有 4 個文件被更改,包括 252 次插入37 次删除
  1. 1 1
      devices/ble_manager.js
  2. 197 36
      utils/blue_ble/manager.js
  3. 5 0
      utils/blue_ble/util.js
  4. 49 0
      utils/hex_util.js

+ 1 - 1
devices/ble_manager.js

@@ -163,7 +163,7 @@ class bleManager {
       }
     });
 
-    ///监听已连接或没有连接
+    ///监听已连接或没有连接 连接和断开的时候会回调
     // {"deviceId":"E4:9F:80:09:40:EC","connected":false}
     wx.onBLEConnectionStateChange((result) => {
       if (result.connected) {

+ 197 - 36
utils/blue_ble/manager.js

@@ -17,6 +17,20 @@ class Manager {
     that.compareList = [];
     ///离线的所有设备,也可以用来比较
     that.dissmissDevice = [];
+
+    ///当前蓝牙ble连接设备的相关属性
+    that.services = {};
+    that.serviceIndex = 0;
+    that.notify = false;
+    that.write = false;
+    that.read = false;
+
+    that.writeCharaterId = "";
+    that.writeServiceId = "";
+    that.notifyCharaterId = "";
+    that.notifyServiceId = "";
+    that.readCharaterId = "";
+    that.readServiceId = "";
   }
 
   ///获取比较的数据
@@ -261,7 +275,7 @@ class Manager {
     wx.startBluetoothDevicesDiscovery({
       allowDuplicatesKey: true,
       success: function (res) {
-        that.getConnectedDevices();
+        // that.getConnectedDevices();
         that.doStartScaning = false;
         that.requestBlueTime = time_util.getCurrentMills();
         if (boolean != null) {
@@ -298,47 +312,194 @@ class Manager {
     });
   }
 
-  ///获取 所有搜索过的蓝牙设备
-  getConnectedDevices() {
+  ///开始连接设备
+  startConnect(device) {
+    return new Promise((resolve, reject) => {
+      var deviceId = device.deviceId;
+      wx.createBLEConnection({
+        deviceId: deviceId,
+        success: function (res) {
+          resolve(true);
+        },
+        fail: function (res) {
+          resolve(false);
+        }
+      });
+    });
+  }
+
+  ///初始化 接收数据 获取特征值
+  getNotifyCharaterId(device) {
     var that = this;
-    const hex_util = require('./../../utils/hex_util');
-    wx.getBluetoothDevices({
-      success: (res) => {
-        if (that.callBackConnect != null) {
-          for (var i = 0; i < res.devices.length; i++) {
-            var temp = res.devices[i];
-            if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
-              temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
-              if (that.callBackConnect != null) {
-                that.callBackConnect(temp);
-              }
-              break;
+    return new Promise((resolve, reject) => {
+      var deviceId = device.deviceId;
+      wx.getBLEDeviceServices({
+        deviceId: deviceId,
+        success: function (res) {
+          that.services = res.services;
+          that.getCharacteristics(device);
+        }
+      })
+    });
+  }
+
+  ///获取设备真正的属性特征值
+  getCharacteristics(device) {
+    var that = this;
+    var deviceId = device.deviceId;
+    var index = that.serviceIndex;
+    var notify = that.notify;
+    var write = that.write;
+    var read = that.read;
+    var services = that.services;
+    wx.getBLEDeviceCharacteristics({
+      deviceId: deviceId,
+      serviceId: services[index].uuid,
+      success: function (res) {
+        console.log(res.characteristics)
+        for (var i = 0; i < res.characteristics.length; i++) {
+          var properties = res.characteristics[i].properties;
+          var charaterId = res.characteristics[i].uuid;
+
+          if (!that.notify) {
+            if (properties.notify) {
+              that.notifyCharaterId = charaterId;
+              that.notifyServiceId = services[index].uuid;
+              that.notify = true;
             }
           }
-        } else {
-          for (var i = 0; i < res.devices.length; i++) {
-            if (that.compareList.length > 0) {
-              var has = false;
-              for (var j = 0; j < that.compareList.length; j++) {
-                if (res.devices[i].name != "") {
-                  if (res.devices[i].deviceId == that.compareList[j].deviceId) {
-                    has = true;
-                    break;
-                  }
-                }
-              }
-              if (!has) {
-                that.compareList.push(res.devices[i]);
-              }
-            } else {
-              that.compareList.push(res.devices[i]);
+          if (!that.write) {
+            if (properties.write) {
+              that.writeCharaterId = charaterId;
+              that.writeServiceId = services[index].uuid;
+              that.write = true;
+            }
+          }
+          if (!that.read) {
+            if (properties.read) {
+              that.readCharaterId = charaterId;
+              that.readServiceId = services[index].uuid;
+              that.read = true;
             }
           }
         }
-      },
-      fail: (err) => {
-        console.error('获取蓝牙设备列表失败', err);
+        if (!that.notify) {
+          index++
+          that.serviceIndex = index;
+          that.notify = notify;
+          that.write = write;
+          that.read = read;
+
+          if (index == services.length) {
+            that.serviceIndex = 0;
+            that.notify = false;
+            that.write = false;
+            that.read = false;
+          } else {
+            that.getCharacteristics(device);
+          }
+        } else {
+          that.monitorCharacteristicValueChange(device);
+        }
       }
+    })
+  }
+
+  // 监听发送的数据
+  monitorCharacteristicValueChange(device) {
+    var that = this;
+    var deviceId = device.deviceId;
+    const hex_util = require('./../../utils/hex_util');
+    wx.notifyBLECharacteristicValueChange({
+      state: true,
+      deviceId: deviceId,
+      serviceId: that.notifyServiceId,
+      characteristicId: that.notifyCharaterId,
+      success: function (res) {
+        wx.onBLECharacteristicValueChange(function (r) {
+          var receiveText = hex_util.buf2string(r.value);
+          console.log('接收到数据文字:' + receiveText)
+        });
+      }
+    })
+  }
+
+  // 断开设备的连接
+  disconnect(device) {
+    return new Promise((resolve, reject) => {
+      var deviceId = device.deviceId;
+      wx.closeBLEConnection({
+        deviceId: deviceId,
+        success: (res) => {
+          resolve(true);
+        },
+        fail: (err) => {
+          resolve(false);
+        }
+      });
     });
   }
-}
+
+  ///发送数据
+  sendData(text, device) {
+    var that = this;
+    var deviceId = device.deviceId;
+    var buffer = new ArrayBuffer(text.length)
+    var dataView = new Uint8Array(buffer)
+    for (var i = 0; i < text.length; i++) {
+      dataView[i] = text.charCodeAt(i)
+    }
+    wx.writeBLECharacteristicValue({
+      deviceId: deviceId,
+      serviceId: that.writeServiceId,
+      characteristicId: that.writeCharaterId,
+      value: buffer,
+      success: function (res) {},
+      fail(err) {}
+    });
+  }
+}
+
+///获取 所有搜索过的蓝牙设备
+// getConnectedDevices() {
+//   var that = this;
+//   const hex_util = require('./../../utils/hex_util');
+//   wx.getBluetoothDevices({
+//     success: (res) => {
+//       if (that.callBackConnect != null) {
+//         for (var i = 0; i < res.devices.length; i++) {
+//           var temp = res.devices[i];
+//           if (that.connectWillDevice != null && temp.name == that.connectWillDevice.clientType) {
+//             temp.mac = temp.advertisData ? hex_util.buf2hex(temp.advertisData) : '';
+//             if (that.callBackConnect != null) {
+//               that.callBackConnect(temp);
+//             }
+//             break;
+//           }
+//         }
+//       } else {
+//         for (var i = 0; i < res.devices.length; i++) {
+//           if (that.compareList.length > 0) {
+//             var has = false;
+//             for (var j = 0; j < that.compareList.length; j++) {
+//               if (res.devices[i].name != "") {
+//                 if (res.devices[i].deviceId == that.compareList[j].deviceId) {
+//                   has = true;
+//                   break;
+//                 }
+//               }
+//             }
+//             if (!has) {
+//               that.compareList.push(res.devices[i]);
+//             }
+//           } else {
+//             that.compareList.push(res.devices[i]);
+//           }
+//         }
+//       }
+//     },
+//     fail: (err) => {
+//       console.error('获取蓝牙设备列表失败', err);
+//     }
+//   });
+// }

+ 5 - 0
utils/blue_ble/util.js

@@ -57,4 +57,9 @@ class BleUtil {
     var that = this;
     await that.manager.stopScan();
   }
+
+  ///开始连接设备
+  async startConnect(device) {
+    
+  }
 }

+ 49 - 0
utils/hex_util.js

@@ -1,8 +1,57 @@
 module.exports = {
   buf2hex: buf2hex,
+  buf2string: buf2string,
+  changeArrayByValue: changeArrayByValue,
+  removeWrongArray: removeWrongArray,
 }
 
 ///获取数据
 function buf2hex(buffer) {
   return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
+}
+
+///数据转文字
+function buf2string(buffer) {
+  var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
+  var str = ''
+  for (var i = 0; i < arr.length; i++) {
+    str += String.fromCharCode(arr[i])
+  }
+  return str
+}
+
+/// value 数组转换的根据值  array 需要转换的数组 
+/// 根据数组中的一个值分隔数组, 分割后组成的新数组
+function changeArrayByValue(value, array) {
+  // var value = "IMU data";
+  var newArray = new Array();
+  var dataStr = '';
+  for (var i = 0; i < array.length; i++) {
+    if (array[i] == value) {
+      if (dataStr) {
+        //把分隔的数据添加新到数组中
+        newArray.push(dataStr.substring(0, dataStr.length - 2).split("  "));
+      }
+      dataStr = '';
+      continue;
+    } else {
+      dataStr += (array[i] + "  ");
+      //把最后分隔的数据添加新到数组中
+      if (i == array.length - 1) {
+        newArray.push(dataStr.substring(0, dataStr.length - 2).split("  "));
+      }
+    }
+  }
+  return newArray;
+}
+
+///数组 去除数组中长度不等于三的属性
+function removeWrongArray(array) {
+  for (var i = 0; i < array.length; i++) {
+    if (array[i].length != 9) {
+      array.splice(i, 1);
+      removeWrongArray(array);
+    }
+  }
+  return array;
 }