Browse Source

feature: 处理君正方案音响的特征值

332777428@qq.com 5 months atrás
parent
commit
8242e04c50
3 changed files with 229 additions and 91 deletions
  1. 5 3
      pages/deviceConnect4/deviceConnect4.js
  2. 187 46
      utils/blue_ble/manager.js
  3. 37 42
      utils/blue_ble/util.js

+ 5 - 3
pages/deviceConnect4/deviceConnect4.js

@@ -47,10 +47,12 @@ Page({
       "mac": name,
       "deviceId": deviceId
     };
+
+    console.log("gadsfasdfadfaf===00==");
     BleUtil.getInstance().startConnect(device, function (changed) {
-      console.log("gadsfasdfadfaf===111==" + changed);
-      BleUtil.getInstance().sendData(device, app.globalData.ssid,app.globalData.pwdData);
+      if (changed) {
+        BleUtil.getInstance().sendData(device, app.globalData.ssid, app.globalData.pwdData);
+      }
     });
-
   },
 })

+ 187 - 46
utils/blue_ble/manager.js

@@ -312,9 +312,11 @@ class Manager {
       wx.createBLEConnection({
         deviceId: deviceId,
         success: function (res) {
+          console.log("gadsfasdfadfaf===mmm==" + JSON.stringify(res));
           resolve(true);
         },
         fail: function (res) {
+          console.log("gadsfasdfadfaf===nnn==" + JSON.stringify(res));
           var errCode = res.errCode;
           var errMsg = res.errMsg;
           if (errCode == -1 && errMsg == "createBLEConnection:fail:already connect") {
@@ -327,6 +329,35 @@ class Manager {
     });
   }
 
+  // 发现服务
+  discoverServices(device) {
+    var deviceId = device.deviceId;
+    return new Promise((resolve, reject) => {
+      wx.getBLEDeviceServices({
+        deviceId: deviceId,
+        success: (res) => {
+          let service_id = "";
+          for (let i = 0; i < res.services.length; i++) {
+            if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
+              res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
+            ) {
+              service_id = res.services[i].uuid;
+              break;
+            }
+            service_id = res.services[i].uuid;
+          }
+          // if (that.publicDevice) {
+          //   that.publicDevice.serviceId = service_id;
+          // }
+          resolve(service_id);
+        },
+        fail: (err) => {
+          reject("");
+        }
+      });
+    });
+  }
+
   ///初始化 接收数据 获取特征值
   getNotifyServices(device) {
     var deviceId = device.deviceId;
@@ -334,67 +365,97 @@ class Manager {
       wx.getBLEDeviceServices({
         deviceId: deviceId,
         success: function (res) {
-          console.log("gadsfasdfadfaf===xxxx==" + JSON.stringify(res));
+          console.log("gadsfasdfadfaf===2222==" + JSON.stringify(res));
           resolve(res.services);
         },
         fail: function (res) {
-          console.log("gadsfasdfadfaf===yyy==" + JSON.stringify(res));
+          console.log("gadsfasdfadfaf===333==" + JSON.stringify(res));
           resolve(null);
         }
       });
     });
   }
 
+  // 发现服务
+  discoverServices(device) {
+    var deviceId = device.deviceId;
+    return new Promise((resolve, reject) => {
+      wx.getBLEDeviceServices({
+        deviceId: deviceId,
+        success: (res) => {
+          let service_id = "";
+          for (let i = 0; i < res.services.length; i++) {
+            if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1 ||
+              res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
+            ) {
+              service_id = res.services[i].uuid;
+              break;
+            }
+            service_id = res.services[i].uuid;
+          }
+          resolve(service_id);
+        },
+        fail: (err) => {
+          console.error('发现服务失败:', err);
+          reject("");
+        }
+      });
+    });
+  }
+
+
+  // 发现特征值 read / write
+  discoverCharacteristics(device, serviceId) {
+    var deviceId = device.deviceId;
+    return new Promise((resolve, reject) => {
+      wx.getBLEDeviceCharacteristics({
+        deviceId: deviceId,
+        serviceId: serviceId,
+        success: (res) => {
+          resolve(res.characteristics);
+        },
+        fail: (err) => {
+          reject("");
+        }
+      });
+    });
+  }
+
   ///获取设备真正的属性特征值
-  getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
+  getCharacteristics(device, serviceId, failed, getMessageCall, successed) {
     var that = this;
     var deviceId = device.deviceId;
     wx.getBLEDeviceCharacteristics({
       deviceId: deviceId,
-      serviceId: services[index].uuid,
+      serviceId: serviceId,
       success: function (res) {
-        var notifyCharaterId = "";
-        var notifyServiceId = "";
-        for (var i = 0; i < res.characteristics.length; i++) {
-          var properties = res.characteristics[i].properties;
-          var charaterId = res.characteristics[i].uuid;
-
-          if (!notify) {
-            if (properties.notify) {
-              notifyCharaterId = charaterId;
-              notifyServiceId = services[index].uuid;
-              notify = true;
-            }
-          }
-          if (!write) {
-            if (properties.write) {
-              that.writeCharaterId = charaterId;
-              that.writeServiceId = services[index].uuid;
-              write = true;
-            }
-          }
+        var characteristics = res.characteristics;
+        if (characteristics.length <= 0) {
+          failed();
+          return;
+        }
 
-          if (!read) {
-            if (properties.read) {
-              that.readCharaterId = charaterId;
-              that.readServiceId = services[index].uuid;
-              read = true;
-            }
+        for (let i = 0; i < characteristics.length; i++) {
+          var charc = characteristics[i];
+          var properties = charc.properties;
+          var charaterId = charc.uuid;
+          ///可以开始读取数据
+          if (properties.notify) {
+            var notifyCharaterId = charaterId;
+            getMessageCall(notifyCharaterId);
           }
-        }
 
-        if (!notify) {
-          index++
-          if (index == services.length) {
-            fail();
-          } else {
-            that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
+          ///可以开始写入数据
+          if (properties.write || properties.writeWithoutResponse) {
+            that.writeServiceId = serviceId;
+            that.writeCharaterId = charaterId;
+            setTimeout(() => {
+              successed();
+            }, 100);
           }
-        } else {
-          succeed(notifyServiceId, notifyCharaterId);
         }
       }
-    })
+    });
   }
 
   // 监听发送的数据
@@ -419,7 +480,16 @@ class Manager {
   ///收取到的数据转换为文字
   onBLECharacteristicValueChange(callback) {
     wx.onBLECharacteristicValueChange(function (r) {
-      callback(r.value);
+      console.log("gadsfasdfadfaf===666==" + JSON.stringify(r));
+      var receiveText = hex_util.buf2string(r);
+      console.log("gadsfasdfadfaf===777==" + receiveText);
+      let buffer = characteristic.value
+      let dataView = new DataView(buffer)
+      let dataResult = []
+      for (let i = 0; i < dataView.byteLength; i++) {
+        dataResult.push(dataView.getUint8(i))
+      }
+      callback(dataResult);
     });
   }
 
@@ -440,16 +510,28 @@ class Manager {
   }
 
   ///发送数据
-  sendData(device, text) {
+  sendData(device, data) {
     return new Promise((resolve, reject) => {
       var that = this;
       var deviceId = device.deviceId;
-      var buffer = new ArrayBuffer(text.length)
-      var dataView = new Uint8Array(buffer);
+      var buffer = new ArrayBuffer(data.length);
+      // 下面是赋值,不能删
+      const dataView = new DataView(buffer);
 
-      for (var i = 1; i < text.length; i++) {
-        dataView[i] = text.charCodeAt(i)
+      for (var i = 0; i < data.length; i++) {
+        dataView.setUint8(i, data[i]);
       }
+      // data.forEach((value, index) => {
+      //   dataView.setUint8(index, value); // 将每个16进制数值写入到 buffer 中
+      // });
+
+      console.log("gadsfasdfadfaf===bbb==" + deviceId);
+      console.log("gadsfasdfadfaf===ccc==" + that.writeServiceId);
+      console.log("gadsfasdfadfaf===ddd==" + that.writeCharaterId);
+      console.log("gadsfasdfadfaf===eee==" + JSON.stringify(buffer));
+
+      // serviceId: that.publicDevice.serviceId, //服务通道,这里主要是notify
+      // characteristicId: characteristicId, //notify uuid
       wx.writeBLECharacteristicValue({
         deviceId: deviceId,
         serviceId: that.writeServiceId,
@@ -468,6 +550,65 @@ class Manager {
 
 module.exports = Manager;
 
+///获取设备真正的属性特征值
+// getCharacteristics(device, services, index, notify, write, read, succeed, fail) {
+//   var that = this;
+//   var deviceId = device.deviceId;
+//   var serviceId = services[index].uuid;
+//   wx.getBLEDeviceCharacteristics({
+//     deviceId: deviceId,
+//     serviceId: serviceId,
+//     success: function (res) {
+//       var notifyCharaterId = "";
+//       var notifyServiceId = "";
+
+//       console.log("gadsfasdfadfaf===xxxx==" + JSON.stringify(res.characteristics));
+//       for (var i = 0; i < res.characteristics.length; i++) {
+//         var properties = res.characteristics[i].properties;
+//         var charaterId = res.characteristics[i].uuid;
+
+//         if (!notify) {
+//           if (properties.notify) {
+//             notifyCharaterId = charaterId;
+//             notifyServiceId = services[index].uuid;
+//             console.log("gadsfasdfadfaf===xxxx==" + properties.write);
+//             console.log("gadsfasdfadfaf===yyy==" + properties.writeWithoutResponse);
+//             console.log("gadsfasdfadfaf===zzz==" + JSON.stringify(res.characteristics[i]));
+//             notify = true;
+//           }
+//         }
+//         if (!write) {
+//           if (properties.write) {
+//             that.writeCharaterId = charaterId;
+//             that.writeServiceId = services[index].uuid;
+//             write = true;
+//           }
+//         }
+
+//         if (!read) {
+//           if (properties.read) {
+//             that.readCharaterId = charaterId;
+//             that.readServiceId = services[index].uuid;
+//             read = true;
+//           }
+//         }
+//       }
+
+//       if (!notify) {
+//         index++
+//         if (index == services.length) {
+//           fail();
+//         } else {
+//           console.log("gadsfasdfadfaf===yyy==");
+//           that.getCharacteristics(device, services, index, notify, write, read, succeed, fail);
+//         }
+//       } else {
+//         succeed(notifyServiceId, notifyCharaterId);
+//       }
+//     }
+//   })
+// }
+
 ///获取 所有搜索过的蓝牙设备
 // getConnectedDevices() {
 //   var that = this;

+ 37 - 42
utils/blue_ble/util.js

@@ -1,4 +1,5 @@
 const Manager = require('./manager');
+const BtParse = require('../../devices/bluetooth/bt_parse');
 
 class BleUtil {
   static _instance = new BleUtil();
@@ -63,57 +64,52 @@ class BleUtil {
     // await that.disconnect(device);
 
     var res = await that.manager.startConnect(device);
+    console.log("gadsfasdfadfaf===222==" + JSON.stringify(res));
     if (!res) {
-      onChanged(false, device);
+      that.disconnect(device);
+      onChanged(false);
       return;
     }
 
     const strings = require('./../../utils/strings');
     var services = await that.manager.getNotifyServices(device);
+    console.log("gadsfasdfadfaf===333==" + JSON.stringify(services));
     if (strings.isEmpty(services)) {
-      console.log("gadsfasdfadfaf===bbb==");
+      that.disconnect(device);
       onChanged(false);
       return;
     }
 
-    that.manager.getCharacteristics(device, services, 0, false, false, false,
-      async function (notifyServiceId, notifyCharaterId) {
-          var isTrue = that.manager.monitorCharacteristicValueChange(device, notifyServiceId, notifyCharaterId);
-          if (!isTrue) {
-            onChanged(false);
-            return;
-          }
-
-          console.log("gadsfasdfadfaf===ddd==" + JSON.stringify(isTrue));
-          ///解决连接之后会有一段时间显示离线,先添加进去就不会了
-          // var has = false;
-          // var compareList = that.manager.getCompareList();
-          // for (var j = 0; j < compareList.length; j++) {
-          //   if (compareList[j].deviceId == device.deviceId) {
-          //     has = true;
-          //     break;
-          //   }
-          // }
-          // if (!has) {
-          //   compareList.unshift(device);
-          //   that.manager.setCompareList(compareList);
-          // }
-          onChanged(true);
+    var index = 0;
+    for (let i = 0; i < services.length; i++) {
+      if (services[i].uuid.toUpperCase().indexOf("FFE5") != -1 ||
+        services[i].uuid.toUpperCase().indexOf("1111") != -1
+      ) {
+        index = i;
+        break;
+      }
+    }
+
+    var notifyServiceId = services[index].uuid;
+    console.log("gadsfasdfadfaf===ppp==" + index + "==" + notifyServiceId);
+    that.manager.getCharacteristics(device, notifyServiceId, function () {
+        that.disconnect(device);
+        onChanged(false);
+      }, function (notifyCharaterId) {
+        var isTrue = that.manager.monitorCharacteristicValueChange(device, notifyServiceId, notifyCharaterId);
+        if (!isTrue) {
+          onChanged(false);
+          return;
+        }
 
-          const hex_util = require('./../../utils/hex_util');
-          const bt_parse = require('./../../devices/bluetooth/bt_parse');
-          that.manager.onBLECharacteristicValueChange(function (value) {
-            var receiveText = hex_util.buf2string(value);
-            console.log("gadsfasdfadfaf===eeee==" + receiveText);
-            console.log('接收到数据文字:' + receiveText);
-
-            var buffer = new DataView(value);
-            var result = []
-            for (let i = 0; i < buffer.byteLength; i++) {
-              result.push(buffer.getUint8(i))
-            }
-            bt_parse.parseTLV(result);
-          });
+        ///数据接收
+        that.manager.onBLECharacteristicValueChange(function (value) {
+          BtParse.parseTLV(value);
+        });
+      },
+      async function () {
+          console.log("gadsfasdfadfaf===ttt==");
+          onChanged(true);
         },
         function () {
           onChanged(false);
@@ -124,11 +120,10 @@ class BleUtil {
   ///发送数据
   async sendData(device, wifiName, pwd) {
     var that = this;
-    console.log("gadsfasdfadfaf===222==" + wifiName + "===" + pwd);
     var text = that.sendWiFiInfo(wifiName, pwd);
-    console.log("gadsfasdfadfaf===444==" + text);
+    console.log("gadsfasdfadfaf===888==" + text);
     var isTrue = await that.manager.sendData(device, text);
-    console.log("gadsfasdfadfaf===333==" + isTrue);
+    console.log("gadsfasdfadfaf===999==" + isTrue);
     ///发送数据成功
     if (isTrue) {