ソースを参照

feature:优化选蓝牙插件的代码

zeng.chen 8 ヶ月 前
コミット
2dd713fde9
4 ファイル変更379 行追加341 行削除
  1. 118 102
      devices/ble_manager.js
  2. 28 5
      devices/bluetooth/bt_cmd.js
  3. 113 93
      devices/bluetooth/bt_parse.js
  4. 120 141
      devices/bt_helper.js

+ 118 - 102
devices/ble_manager.js

@@ -11,95 +11,98 @@ class bleManager {
 
     // 检查蓝牙权限
     async checkBluetoothPermission() {
-        return new Promise((resolve, reject) => {
-            // 获取蓝牙权限
-            const _this = getApp();
-            wx.getSetting({
-                success(res) {
-                    if (res.authSetting["scope.bluetooth"]) {
-                        _this.globalData.scopeBluetooth = true;
-                        this.hasPermission = true;
-                        // console.log('checkBluetoothPermission success, now is', res)
-
-                        resolve(true);
-
-                    } else if (res.authSetting["scope.bluetooth"] === undefined) {
-                        _this.globalData.scopeBluetooth = false;
-                        this.hasPermission = false;
-                        wx.authorize({
-                            scope: "scope.bluetooth",
-                            complete() {
-
-                                resolve(_this.checkBluetoothPermission());
-
-                            }
-                        });
-
-                    } else {
-                        _this.globalData.scopeBluetooth = false;
-                        this.hasPermission = false;
+        // return new Promise((resolve, reject) => {
+        // 获取蓝牙权限
+        const _app = getApp();
+        wx.getSetting({
+            success(res) {
+                if (res.authSetting["scope.bluetooth"]) {
+                    _app.globalData.scopeBluetooth = true;
+                    this.hasPermission = true;
+                    // console.log('checkBluetoothPermission success, now is', res)
+
+                    // resolve(true);
+
+                } else if (res.authSetting["scope.bluetooth"] === undefined) {
+                    _app.globalData.scopeBluetooth = false;
+                    this.hasPermission = false;
+                    wx.authorize({
+                        scope: "scope.bluetooth",
+                        complete() {
+                            this.checkBluetoothPermission()
+                            // resolve(_this.checkBluetoothPermission());
 
-                        wx.showModal({
-                            title: '请打开系统蓝牙进行配网',
-                            content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
-                            success(res) {
-                                if (res.confirm) {
-                                    console.log('用户点击确定')
-                                    wx.openSetting({
-                                        complete() {
-                                            // _this.getBluetoothStatus();
-                                        }
-                                    })
-                                } else if (res.cancel) {
-                                    console.log('用户点击取消')
-                                }
+                        }
+                    });
+
+                } else {
+                    _this.globalData.scopeBluetooth = false;
+                    this.hasPermission = false;
+
+                    wx.showModal({
+                        title: '请打开系统蓝牙进行配网',
+                        content: '如已打开蓝牙仍然弹框,请尝试重启小程序',
+                        success(res) {
+                            if (res.confirm) {
+                                console.log('用户点击确定')
+                                wx.openSetting({
+                                    complete() {
+                                        // _this.getBluetoothStatus();
+                                    }
+                                })
+                            } else if (res.cancel) {
+                                console.log('用户点击取消')
                             }
-                        })
-                        resolve(false);
-                    };
-                }
-            })
+                        }
+                    })
+                    // resolve(false);
+                };
+            }
         })
-
-
+        // })
 
     }
 
     // 初始化蓝牙适配器
-    initBluetoothAdapter() {
-        let _this = this;
+    async initBluetoothAdapter() {
+        let _this = this
+        // return new Promise((resolve, reject) => {
+        wx.openBluetoothAdapter({
+            success: (res) => {
+                _this.isAvailable = true;
+                // console.log('adapterState success, now is', res)
+
+                // resolve(true);
+            },
+            fail: (err) => {
+                _this.isAvailable = false;
+                console.log('adapterState fail, now is', err)
+
+                // reject(false);
+            }
+        });
         wx.onBluetoothAdapterStateChange(function (res) {
             console.log('adapterState changed, now is', res)
             _this.isAvailable = res.available ?? false
 
         })
-        return new Promise((resolve, reject) => {
-            wx.openBluetoothAdapter({
-                success: (res) => {
-                    _this.isAvailable = true;
-                    // console.log('adapterState success, now is', res)
-
-                    resolve(true);
-                },
-                fail: (err) => {
-                    _this.isAvailable = false;
-                    // console.log('adapterState fail, now is', err)
+        // });
+    }
 
-                    reject(false);
-                }
-            });
-        });
+    closeBle() {
+        wx.closeBluetoothAdapter()
     }
 
     // 获取已连接的蓝牙设备
     getConnectedDevices() {
         if (!this.isAvailable && !this.hasPermission) {
-            return false;
+            return [];
         }
         return new Promise((resolve, reject) => {
             wx.getConnectedBluetoothDevices({
                 // services: ["FFC0", "ffc0", "FFC1", "FFC2", "ffc1", "ffc2", "AB00", "ab00", "AB01", "AB02", "FFF1", "fff1", "FFE2", "FFE5",],
-                services: ["ab00", "0000AB00-0000-1000-8000-00805F9B34FB", "ffe5", "1111"],
+                // services: ["ab00", "0000AB00-0000-1000-8000-00805F9B34FB", "ffe5", "1111"],
+                services: [],
                 // services: [
                 //     "0000ab00-0000-1000-8000-00805f9b34fb",
                 //     "0000ffc0-0000-1000-8000-00805f9b34fb",
@@ -154,7 +157,7 @@ class bleManager {
             wx.closeBLEConnection({
                 deviceId: deviceId,
                 success: (res) => {
-                    this.connectedDeviceId = null;
+                    this.device = null;
                     console.log('断开连接成功:', res);
                     resolve(res);
                 },
@@ -172,16 +175,16 @@ class bleManager {
             const buffer = new ArrayBuffer(data.length);
             const view = new Uint8Array(buffer);
             for (let i = 0; i < data.length; i++) {
-                view[i] = data.charCodeAt(i);
+                view[i] = data[i];
             }
-
+            console.log('开始发送数据:', data, view);
             wx.writeBLECharacteristicValue({
                 deviceId: this.device.deviceId,
                 serviceId: this.device.serviceId,
                 characteristicId: this.device.characteristicId,
                 value: buffer,
                 success: (res) => {
-                    console.log('数据发送成功:', res);
+                    console.log('数据发送成功:');
                     resolve(res);
                 },
                 fail: (err) => {
@@ -328,7 +331,8 @@ class bleManager {
                 name: device.name,
                 localName: device.localName,
                 uuid: uuid,
-                mac: device.mac
+                mac: device.mac,
+                connectable: device.connectable
             }
         });
         return newDevices
@@ -348,15 +352,15 @@ class bleManager {
     }
     // 连接到指定设备
     connectToDevice(device) {
-        this.device = device
 
         return new Promise((resolve, reject) => {
             console.log("开始连接蓝牙:", device.deviceId)
             wx.createBLEConnection({
                 deviceId: device.deviceId,
                 success: (res) => {
+                    this.device = device
                     console.log('连接成功:', res);
-                    resolve(res);
+                    resolve(true);
                 },
                 fail: (err) => {
                     this.device = null
@@ -402,24 +406,26 @@ class bleManager {
                 deviceId: deviceId,
                 success: (res) => {
                     this.device.services = res.services;
-                    console.log('发现服务:', res.services);
                     let service_id = "";
                     for (let i = 0; i < res.services.length; i++) {
-                        if (services[i].uuid.toUpperCase().indexOf("AB00") != -1
-                            || services[i].uuid.toUpperCase().indexOf("FFC0") != -1
+                        if (res.services[i].uuid.toUpperCase().indexOf("AB00") != -1
+                            || res.services[i].uuid.toUpperCase().indexOf("FFC0") != -1
                         ) {
-                            service_id = services[i].uuid;
+                            service_id = res.services[i].uuid;
                             break;
                         }
                     }
                     this.device.serviceId = service_id;
+                    console.log('发现服务:', service_id);
+
                     resolve(service_id);
+                    // resolve(res.services);
                 },
                 fail: (err) => {
                     this.device.serviceId = null;
 
                     console.error('发现服务失败:', err);
-                    reject(new Error('发现服务失败'));
+                    reject([]);
                 }
             });
         });
@@ -427,19 +433,19 @@ class bleManager {
 
     // 发现特征值 read / write
     discoverCharacteristics(deviceId, serviceId) {
-        console.log('发现特征值:', deviceId, serviceId);
+        console.log('发现特征值:' + deviceId + " ,  " + serviceId);
 
-        if (deviceId !== this.device.deviceId) {
-            console.log('设备id不匹配')
-            return false
-        }
+        // if (deviceId !== this.device.deviceId) {
+        //     console.log('设备id不匹配')
+        //     return false
+        // }
         return new Promise((resolve, reject) => {
             wx.getBLEDeviceCharacteristics({
                 deviceId: deviceId,
                 serviceId: serviceId,
                 success: (res) => {
                     // this.characteristics[serviceId] = res.characteristics;
-                    console.log('发现特征值:', res.characteristics);
+                    console.log('发现特征值2:', res);
                     this.device.characteristics = res.characteristics;
 
                     resolve(res.characteristics);
@@ -454,19 +460,18 @@ class bleManager {
     }
 
     // 读取特征值
-    readCharacteristicValue(deviceId, serviceId, characteristicId) {
-        if (deviceId !== this.device.deviceId) {
-            console.log('设备id不匹配2')
-            return ""
-        }
-        console.log('开始读取特征值', deviceId, serviceId, characteristicId)
+    readCharacteristicValue(characteristicId) {
+
+        console.log('开始读取特征值', characteristicId)
         return new Promise((resolve, reject) => {
             wx.readBLECharacteristicValue({
-                deviceId: deviceId,
-                serviceId: serviceId,
+                deviceId: this.device.deviceId,
+                serviceId: this.device.serviceId,
                 characteristicId: characteristicId,
                 success: (res) => {
-                    console.log('读取特征值成功:', res);
+                    const name = this.parseBLEValue(res.value); // 解析读取到的值
+
+                    console.log('读取特征值成功:', name, res);
                     resolve(res);
                 },
                 fail: (err) => {
@@ -476,25 +481,27 @@ class bleManager {
             });
         });
     }
-
+    // 解析读取到的设备名称
+    parseBLEValue(buffer) {
+        return String.fromCharCode.apply(null, new Uint8Array(buffer));
+    }
     // 监听特征值变化
-    notifyCharacteristicValueChange(deviceId, serviceId, characteristicId, callback) {
+    notifyCharacteristicValueChange(characteristicId, callback) {
+        console.log('监听特征值变化:', characteristicId);
         wx.notifyBLECharacteristicValueChange({
-            deviceId: deviceId,  //设备mac   IOS和安卓系统不一样
-            serviceId: serviceId,     //服务通道,这里主要是notify
+            deviceId: this.device.deviceId,  //设备mac   IOS和安卓系统不一样
+            serviceId: this.device.serviceId,     //服务通道,这里主要是notify
             characteristicId: characteristicId,     //notify uuid
             state: true,
             success: function (res) {
                 console.log("开启notify 成功")
                 //TODO  onBLECharacteristicValueChange  监听特征值 设备的数据在这里获取到
                 wx.onBLECharacteristicValueChange(function (characteristic) {
-                    console.log('characteristic value comed:')
                     let buffer = characteristic.value
                     let dataView = new DataView(buffer)
                     let dataResult = []
-                    console.log("dataView.byteLength", dataView.byteLength)
                     for (let i = 0; i < dataView.byteLength; i++) {
-                        console.log("0x" + dataView.getUint8(i).toString(16))
+                        // console.log("0x" + dataView.getUint8(i).toString(16))
                         dataResult.push(dataView.getUint8(i).toString(16))
                     }
                     const result = dataResult
@@ -505,10 +512,19 @@ class bleManager {
                     }
                 })
             },
-            fail: function (res) { }
+            fail: function (res) {
+                console.log("订阅特征失败:", res)
+
+            }
         })
     }
 
+    setWrite(wirte, characteristicId) {
+        console.log('写入特征值:', characteristicId)
+        this.device.wirte = wirte
+        this.device.characteristicId = characteristicId;
+    }
+
 }
 
 const ble = new bleManager();

+ 28 - 5
devices/bluetooth/bt_cmd.js

@@ -19,7 +19,7 @@ const EnumConnectType = {
 
 class BtCmd {
     // BtCmd._();
-    // constructor() { }
+    constructor() { }
 
     // 获取版本号
     static get queryVersion() {
@@ -160,9 +160,19 @@ class BtCmd {
         return this._build(CmdRgb.query, [0x0]);
     }
 
+    static stringToUint8Array(str) {
+        // 54 44 44 48 01 11 28 09 73 6d6172745f413246
+        // const encoder = new TextEncoder();
+        // const uint8Array = encoder.encode(str);
+        // return uint8Array;
+        return [0x73, 0x6d, 0x61, 0x72, 0x74, 0x5f, 0x41, 0x32, 0x46]
+    }
+
     // 校验设备
-    static get checkDevice() {
-        return this._build(CmdBase.checkDevice, StringUtil.string2ListInt(CmdBase.secretKey));
+    static checkDevice() {
+        let secretKey = this.stringToUint8Array(CmdBase.secretKey)
+        console.log(`checkDevice========${secretKey}`);
+        return this._build(CmdBase.checkDevice, secretKey);
     }
 
     // 杰理语音开始回应
@@ -255,7 +265,7 @@ class BtCmd {
         if (isSend) {
             mqttAddDebugCmd(`发送蓝牙指令:${cmd} \n ${result}`);
         }
-        console.log(`${key}解析-[${result}]`);
+        console.log(`${key}解析- [${result}]`);
     }
 
     static _int2Hex(value) {
@@ -281,6 +291,7 @@ const CmdBase = {
     setVolume: 0x33,
     newFlag: "MW-Mate X\\(4G_WIFI\\)|MW-2AX\\(WIFI-N\\)|MW-SR1\\(4G_WIFI\\)|MW-SR1\\(4G_WIFI_MEIZU01\\)",
     // volumeMax: (new RegExp(`^(${CmdBase.newFlag})$`, 'i').test(DeviceManager.instance.clientType || "")) ? 0x20 : 0xF,
+    volumeMax: 15,
 
     parseVersion(version) {
         let ver;
@@ -403,4 +414,16 @@ const CmdWeek = {
         }
         return w;
     }
-};
+};
+
+module.exports = {
+    BtCmd,
+    CmdBase,
+    CmdEarPhone,
+    CmdRtc,
+    CmdRgb,
+    CmdKwh,
+    CmdKey,
+    CmdVoice,
+    CmdWeek
+};

+ 113 - 93
devices/bluetooth/bt_parse.js

@@ -1,4 +1,14 @@
-import { BtCmd } from './bt_cmd.js';
+import {
+    BtCmd,
+    CmdBase,
+    CmdEarPhone,
+    CmdRtc,
+    // CmdRgb,
+    CmdKwh,
+    CmdKey,
+    CmdVoice,
+    CmdWeek
+} from './bt_cmd';
 
 class BtParse {
     // 型号名称
@@ -12,17 +22,21 @@ class BtParse {
     // 如果10ms内获取两个一模一样的就删除一个
     static lastCmd = null;
     static lastTime = null;
+    constructor() { }
 
     // 解析命令
-    static async parseTLV(cmd) {
+    static parseTLV(cmd) {
         BtCmd.printTLV(cmd, false);
         // todo 在线
         // if (!PlayDevice.isOnline) {
         //     return;
         // }
-        if (!BtParse.isReceiveCmd) {
-            return;
-        }
+
+        // if (!BtParse.isReceiveCmd) {
+        //     return;
+        // }
+
+
 
         if (cmd.length > 5) {
             // 指令类别
@@ -44,13 +58,14 @@ class BtParse {
                 // 查询版本号后校验设备
                 else if (type === CmdBase.queryVersion) {
                     const version = CmdBase.parseVersion(value);
-                    EventManager.fire(CmdEvent.version(version));
-                    EventManager.fire(CmdEvent.getDeviceInfo());
+                    //EventManager.fire(CmdEvent.version(version));
+                    //EventManager.fire(CmdEvent.getDeviceInfo());
                 } else if (BtParse._getDataHeader(cmd)) {
                     // 控制指令
                     BtParse._controlCmd(cmd);
                 } else {
-                    const manufacturer = DeviceManager.instance.device?.manufacturer ?? "";
+                    const manufacturer = "";
+                    // DeviceManager.instance.device?.manufacturer ?? "";
 
                     // 山景的语音判断
                     if (manufacturer === EnumSupplier.shanJing) {
@@ -86,41 +101,41 @@ class BtParse {
     }
 
     // todo 暂时不要
-    // static _voiceCmd(cmd) {
-    //     const type = cmd[6];
-
-    //     switch (type) {
-    //         // 杰理语音开始
-    //         case CmdVoice.jlStartVoice:
-    //             BtParse._startRecord(EnumSupplier.jieLi);
-    //             break;
-
-    //         // 杰理结束
-    //         case CmdVoice.jlStopVoice:
-    //             BtParse._stopRecord(EnumSupplier.jieLi);
-    //             break;
-
-    //         // 发给插件
-    //         case CmdVoice.jlReceiveVoiceData:
-    //             console.log("发送杰里的p1语音:没有进来过,不走这里的,直接判断0x70 && jieLi");
-    //             BtParse._receiveRecordData(cmd);
-    //             break;
-
-    //         // 领心语音开始
-    //         case CmdVoice.lxStartVoice:
-    //             BtParse._startRecord(EnumSupplier.lingXin);
-    //             break;
-
-    //         // 领心语音结束
-    //         case CmdVoice.lxStopVoice:
-    //             BtParse._stopRecord(EnumSupplier.lingXin);
-    //             break;
-
-    //         default:
-    //             console.log("发送语音:默认发送,不走这里", cmd);
-    //             break;
-    //     }
-    // }
+    static _voiceCmd(cmd) {
+        const type = cmd[6];
+        console.log("收到语音指令:", cmd);
+        // switch (type) {
+        //     // 杰理语音开始
+        //     case CmdVoice.jlStartVoice:
+        //         BtParse._startRecord(EnumSupplier.jieLi);
+        //         break;
+
+        //     // 杰理结束
+        //     case CmdVoice.jlStopVoice:
+        //         BtParse._stopRecord(EnumSupplier.jieLi);
+        //         break;
+
+        //     // 发给插件
+        //     case CmdVoice.jlReceiveVoiceData:
+        //         console.log("发送杰里的p1语音:没有进来过,不走这里的,直接判断0x70 && jieLi");
+        //         BtParse._receiveRecordData(cmd);
+        //         break;
+
+        //     // 领心语音开始
+        //     case CmdVoice.lxStartVoice:
+        //         BtParse._startRecord(EnumSupplier.lingXin);
+        //         break;
+
+        //     // 领心语音结束
+        //     case CmdVoice.lxStopVoice:
+        //         BtParse._stopRecord(EnumSupplier.lingXin);
+        //         break;
+
+        //     default:
+        //         console.log("发送语音:默认发送,不走这里", cmd);
+        //         break;
+        // }
+    }
 
     static async _startRecord(supplier) {
         console.log("StartVoice======语音开始", supplier);
@@ -140,7 +155,7 @@ class BtParse {
         const type = cmd[6];
         const value = cmd[8];
         // mqttAddDebugCmd("收到蓝牙指令:" + cmd);
-
+        console.log("收到控制指令:", cmd, type)
         switch (type) {
             // 校验设备
             case CmdBase.checkDeviceSuccess:
@@ -154,18 +169,19 @@ class BtParse {
 
             // 按键   短按、长按等
             case CmdKey.type:
-                if (DeviceUtil.isIOS) {
-                    if (BtParse.lastCmd && JSON.stringify(BtParse.lastCmd) === JSON.stringify(cmd)) {
-                        if (BtParse.lastTime) {
-                            const curTime = TimeUtil.getCurrentMillis();
-                            if (curTime - BtParse.lastTime < 5) {
-                                return;
-                            }
-                        }
-                    }
-                    BtParse.lastCmd = cmd;
-                    BtParse.lastTime = TimeUtil.getCurrentMillis();
-                }
+                // IOS的不要了
+                // if (DeviceUtil.isIOS) {
+                //     if (BtParse.lastCmd && JSON.stringify(BtParse.lastCmd) === JSON.stringify(cmd)) {
+                //         if (BtParse.lastTime) {
+                //             const curTime = TimeUtil.getCurrentMillis();
+                //             if (curTime - BtParse.lastTime < 5) {
+                //                 return;
+                //             }
+                //         }
+                //     }
+                //     BtParse.lastCmd = cmd;
+                //     BtParse.lastTime = TimeUtil.getCurrentMillis();
+                // }
                 let t = 0;
                 if (cmd.length > 9) {
                     t = cmd[9];
@@ -268,7 +284,9 @@ class BtParse {
             // 音量 54 44 44 48 1 a 32 2 b 0
             case CmdBase.queryVolume:
                 // 手机最大音量 需要获取
-                const phoneMax = await VolumeUtil.getMaxVolume();
+                const phoneMax = 15;
+                // todo 音量
+                //await VolumeUtil.getMaxVolume();
                 const max = CmdBase.volumeMax;
                 const d = phoneMax / max;
 
@@ -281,33 +299,34 @@ class BtParse {
                 }
 
                 // 仅用于记录设备音量,播控页面显示用
-                EventManager.fire(CmdEvent.volume({ volume: trueVolume }));
-                if (DeviceUtil.isAndroid) {
-                    const name = DeviceManager.instance.name;
-                    if (name === "猫王·霹雳唱机") {
-                        VolumeUtil.setVolume(trueVolume);
-                    }
-                }
+                //EventManager.fire(CmdEvent.volume({ volume: trueVolume }));
+                // if (DeviceUtil.isAndroid) {
+                //     const name = "";
+                //     // DeviceManager.instance.name;
+                //     if (name === "猫王·霹雳唱机") {
+                //         // VolumeUtil.setVolume(trueVolume);
+                //     }
+                // }
                 break;
 
             // 查询电量
             case CmdKwh.queryKwh:
-                EventManager.fire(CmdEvent.battery({ kwh: value }));
+                //EventManager.fire(CmdEvent.battery({ kwh: value }));
                 break;
 
             // 自动播放 54, 44, 44, 48, 1, 9, 24, 1, 1
             case CmdBase.getAutoPlay:
             case CmdBase.setAutoPlay:
-                setTimeout(() => {
-                    EventManager.fire(CmdEvent.playStatus({
-                        playStatus: value === EnumOpen.open ? EnumPlayStatus.play : EnumPlayStatus.pause,
-                    }));
-                }, 300);
+                // setTimeout(() => {
+                //     EventManager.fire(CmdEvent.playStatus({
+                //         playStatus: value === EnumOpen.open ? EnumPlayStatus.play : EnumPlayStatus.pause,
+                //     }));
+                // }, 300);
                 break;
 
             // 查询低电量设置
             case CmdKwh.queryLowKwhWarningTone:
-                EventManager.fire(CmdEvent.queryLowKwn({ kwh: value }));
+                //EventManager.fire(CmdEvent.queryLowKwn({ kwh: value }));
                 break;
 
             // 耳机电量 index0 :左耳机, index1:左耳机 ,index2: 充电盒。value: 0-9代表10-100% 获取不到用-1
@@ -323,12 +342,12 @@ class BtParse {
                     kwh = Math.max(value, rightKwh);
                 }
 
-                EventManager.fire(CmdEvent.batteryEarphone({
-                    kwhLeft: value,
-                    kwhBox: boxKwh,
-                    kwhRight: rightKwh,
-                    kwh: kwh,
-                }));
+                // EventManager.fire(CmdEvent.batteryEarphone({
+                //     kwhLeft: value,
+                //     kwhBox: boxKwh,
+                //     kwhRight: rightKwh,
+                //     kwh: kwh,
+                // }));
                 break;
 
             // EQ  [84, 68, 68, 72, 1, 18, 180, 10, 0, 0, 240, 237, 236, 0, 236, 0, 0, 0]
@@ -338,14 +357,14 @@ class BtParse {
                     const result = cmd.slice(8, cmd.length);
                     const list = result.map(element => parseInt(element, 16));
                     console.log("eq==============", list);
-                    EventManager.fire(CmdEvent.eqs({ eqs: list }));
+                    // EventManager.fire(CmdEvent.eqs({ eqs: list }));
                 }
                 break;
 
             // 低延迟  [54, 44, 44, 48, 1, a, b2, 2, 0, 2]
             case CmdEarPhone.queryLowDelayMode:
                 const lowDelayMode = cmd[9];
-                EventManager.fire(CmdEvent.lowDelayMode({ lowDelayMode, lowDelayModeOpen: value }));
+                // EventManager.fire(CmdEvent.lowDelayMode({ lowDelayMode, lowDelayModeOpen: value }));
                 break;
 
             // 耳机低电量
@@ -363,19 +382,19 @@ class BtParse {
                     const minutes = cmd[11];
                     const wakeCycle = CmdWeek.cmd2Week(week);
                     console.log("queryAlarm=====", wakeSwitch, "=", wakeCycle);
-                    EventManager.fire(CmdEvent.wake({
-                        wakeSwitch,
-                        wakeCycle,
-                        wakeHour: hour,
-                        wakeMinutes: minutes,
-                    }));
+                    // EventManager.fire(CmdEvent.wake({
+                    //     wakeSwitch,
+                    //     wakeCycle,
+                    //     wakeHour: hour,
+                    //     wakeMinutes: minutes,
+                    // }));
                 }
                 break;
 
             // 查询自动休眠状态
             case CmdRtc.querySleepAfterPlayPause:
             case CmdRtc.setSleepAfterPlayPause:
-                EventManager.fire(CmdEvent.pauseSleep({ pauseSleep: value }));
+                //EventManager.fire(CmdEvent.pauseSleep({ pauseSleep: value }));
                 break;
 
             // 查询休眠
@@ -385,11 +404,11 @@ class BtParse {
                 const minutes = cmd[10];
                 const leftHour = cmd[11];
                 const leftMinutes = cmd[12];
-                EventManager.fire(CmdEvent.sleep({
-                    sleepSwitch,
-                    sleepHour: hour,
-                    sleepMinutes: minutes,
-                }));
+                // EventManager.fire(CmdEvent.sleep({
+                //     sleepSwitch,
+                //     sleepHour: hour,
+                //     sleepMinutes: minutes,
+                // }));
                 break;
 
             // 开始录音
@@ -403,7 +422,7 @@ class BtParse {
                 const singleC = cmd[8];
                 const doubleC = cmd[9];
                 const longC = cmd[10];
-                EventManager.fire(CmdEvent.ctrlStatus({ ctrlStatus: [singleC, doubleC, longC] }));
+                //EventManager.fire(CmdEvent.ctrlStatus({ ctrlStatus: [singleC, doubleC, longC] }));
                 break;
 
             default:
@@ -414,4 +433,5 @@ class BtParse {
     }
 }
 
-export { BtParse };
+// 导出类
+module.exports = BtParse;

+ 120 - 141
devices/bt_helper.js

@@ -4,10 +4,12 @@
 // const BtIOSHelper = require('./BtIOSHelper');
 // const QueueManager = require('./QueueManager');
 // const DeviceManager = require('./DeviceManager');
-const BtCmd = require('./../devices/bluetooth/bt_cmd');
+const { CmdBase, BtCmd, } = require('./../devices/bluetooth/bt_cmd');
+const BtParse = require('./../devices/bluetooth/bt_parse');
+const ble = require('./ble_manager');
 // const VolumeUtil = require('./VolumeUtil');
 // const EventManager = require('./EventManager');
-const CmdBase = require('./../devices/bluetooth/bt_cmd');
+// const CmdBase = require('./../devices/bluetooth/bt_cmd');
 const bleManager = require('./ble_manager');
 // const EnumConnectStatus = require('./EnumConnectStatus');
 // const EnumOpen = require('./EnumOpen');
@@ -47,6 +49,7 @@ class BtHelper {
     // _helper;
 
     constructor() {
+        this.timer = null;
         // if (DeviceUtil.isAndroid) {
         //     this._helper = BtAndroidHelper.instance;
         // } else {
@@ -67,7 +70,8 @@ class BtHelper {
 
     async search(mqttFilterList) {
         let res = await bleManager.startScan()
-        setTimeout(() => {
+        this.timer = null;
+        this.timer = setTimeout(() => {
             bleManager.stopScan();
         }, 10000);
         // console.log(res);
@@ -83,58 +87,68 @@ class BtHelper {
         bleManager.stopScan();
     }
 
+    async _connectSuccess() {
+        await btHelper.checkDevice()
+        await btHelper.getDeviceInfo()
+    }
+
     async connect(data, onChanged) {
         // await this._helper.connect({ data, onChanged, isClick });
         try {
+            clearTimeout(this.timer);
+            this.timer = null;
+            bleManager.stopScan()
             var res = await bleManager.connectToDevice(data);
             console.log('连接成功');
             // this.setData({ connectedDeviceId: deviceId });
             if (res === false) {
                 console.log("连接失败")
+                this.disconnect(data)
                 return
             }
             const serviceId = await bleManager.discoverServices(data.deviceId);
-
+            if (serviceId == "") {
+                console.log("连接失败")
+                this.disconnect(data)
+                return
+            }
             // this.setData({ services });
-            console.log("服务ID", serviceId)
-
-            var characteristics = await bleManager.discoverCharacteristics({
-                deviceId: data.deviceId,
-                serviceId: serviceId,
-            })
+            console.log("服务ID:" + serviceId)
 
-            console.log('device特征值:', res.characteristics)
-            for (let i = 0; i < res.characteristics.length; i++) {
-                let charc = res.characteristics[i];
+            var characteristics = await bleManager.discoverCharacteristics(data.deviceId, serviceId)
+            if (characteristics == "") {
+                console.log("连接失败")
+                this.disconnect(data)
+                return
+            }
+            console.log('device特征值:', characteristics)
+            for (let i = 0; i < characteristics.length; i++) {
+                let charc = characteristics[i];
                 if (charc.properties.notify) {
                     // 订阅的
-                    bleManager.notifyCharacteristicValueChange(data.deviceId, service.serviceId, characteristics, true, (res) => {
-                        // console.log(res)
+                    bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
+                        // console.log('收到数据:', BtParse.parseTLV);
+                        BtParse.parseTLV(res);
                     })
                 }
-                if (charc.properties.write || element.properties.writeWithoutResponse) {
+                if (charc.properties.write || charc.properties.writeWithoutResponse) {
                     // 写入的
+                    bleManager.setWrite(charc, charc.uuid)
+
+                    setTimeout(() => {
+                        this._connectSuccess()
+                    }, 1000);
+
+                    if (onChanged) {
+                        onChanged(true)
+                    }
                 }
                 if (charc.properties.read) {
-                    console.log('读read_id:', that.data.read_id);
-                    var chara = await bleManager.readCharacteristicValue({
-                        deviceId: data.deviceId,
-                        serviceId: uuid,
-                        characteristicId: characteristics,
-                    })
+                    var chara = await bleManager.readCharacteristicValue(charc.uuid,)
                 }
             }
 
 
-
-
-            console.log("查询特征值:", chara)
-
-
-
-            if (onChanged) {
-                onChanged(true)
-            }
             // this.setData({ characteristics: { ...this.data.characteristics, [service.uuid]: characteristics } });
 
         } catch (error) {
@@ -143,7 +157,6 @@ class BtHelper {
     }
 
     async disconnect(data) {
-        // await this._helper.disconnect();
         bleManager.disconnect(data.deviceId)
     }
 
@@ -152,7 +165,11 @@ class BtHelper {
     }
 
     async send(cmd, type) {
-        // bleManager.sendData()
+        // console.log('开始发送数据:', cmd)
+        if (cmd) {
+            bleManager.sendData(cmd)
+        }
+
         // QueueManager.instance.addTask({ task: cmd });
     }
     // onLoad: function () {
@@ -162,85 +179,47 @@ class BtHelper {
 
     async initBluetooth() {
         try {
-            let res = await bleManager.initBluetoothAdapter();
-            console.log(res)
+            bleManager.initBluetoothAdapter();
+            // console.log(res)
 
-            let per = await bleManager.checkBluetoothPermission();
-            console.log(per)
+            bleManager.checkBluetoothPermission();
+            // console.log(per)
         } catch (error) {
             console.error(error);
         }
     }
 
+    closeBle() {
+        bleManager.closeBle()
+    }
+
     async getConnectedDevices() {
         try {
-            // const connectedDevices = await bleManager.getConnectedDevices();
-            const allDevices = await bleManager.getAllConnectedDevices()
-            console.log("全部设备:", allDevices.length)
-            return allDevices
+            const connectedDevices = await bleManager.getConnectedDevices();
+            console.log("全部设备1:", connectedDevices)
+            if (connectedDevices.devices.length) {
+                // todo 已经连接上的设备
+            }
+            // const allDevices = await bleManager.getAllConnectedDevices()
+            // console.log("全部设备2:", allDevices.length)
+            return connectedDevices
         } catch (error) {
             console.error(error);
         }
     }
 
-
-    // disconnectFromDevice: async function(deviceId) {
-    //     try {
-    //         await bleManager.disconnectFromDevice(deviceId);
-    //         console.log('断开连接成功');
-    //         this.setData({ connectedDeviceId: null });
-    //     } catch (error) {
-    //         console.error(error);
-    //     }
-    // },
-
-    // sendData: async function(deviceId, serviceId, characteristicId, data) {
-    //     try {
-    //         await bleManager.sendData(deviceId, serviceId, characteristicId, data);
-    //         console.log('数据发送成功');
-    //     } catch (error) {
-    //         console.error(error);
-    //     }
-    // },
-
-    // stopDiscovery: async function() {
-    //     try {
-    //         await bleManager.stopBluetoothDevicesDiscovery();
-    //         console.log('停止搜索成功');
-    //     } catch (error) {
-    //         console.error(error);
-    //     }
-    // },
-
-    // readCharacteristicValue: async function(deviceId, serviceId, characteristicId) {
-    //     try {
-    //         const value = await bleManager.readCharacteristicValue(deviceId, serviceId, characteristicId);
-    //         console.log('读取特征值:', value);
-    //     } catch (error) {
-    //         console.error(error);
-    //     }
-    // },
-
-    // notifyCharacteristicValueChange: async function(deviceId, serviceId, characteristicId, state) {
-    //     try {
-    //         const result = await bleManager.notifyCharacteristicValueChange(deviceId, serviceId, characteristicId, state);
-    //         console.log('通知特征值变化:', result);
-    //     } catch (error) {
-    //         console.error(error);
-    //     }
-    // }
-
-    checkDevice() {
-        this.send(BtCmd.checkDevice);
+    async checkDevice() {
+        // console.log("校验设备:", BtCmd); // 输出: EarPhone Info
+        await this.send(BtCmd.checkDevice());
         //2.0有发这个,不知道是啥
-        this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]));
+        await this.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
     }
 
-    getVersion() {
-        this.send(BtCmd.queryVersion);
+    async getVersion() {
+        await this.send(BtCmd.queryVersion());
     }
 
-    static get _time() {
+    _time() {
         return 400;
     }
 
@@ -252,58 +231,58 @@ class BtHelper {
         //     this.send(BtCmd.queryLowPower);
         //     this.send(BtCmd.queryCtrlStatus);
         // } else {
-        await this.send(BtCmd.setTime);
-        await this.send(BtCmd.queryKwh);
+        await this.send(BtCmd.setTime());
+        await this.send(BtCmd.queryKwh());
         await this.getSleep();
         await this.getAlert();
-        await this.send(BtCmd.queryRGB);
+        await this.send(BtCmd.queryRGB());
         await this.getVolume();
         await this.getPauseSleep();
         // }
     }
 
-    getAlert() {
-        this.send(BtCmd.queryAlarm);
+    async getAlert() {
+        await this.send(BtCmd.queryAlarm());
     }
 
-    getSleep() {
-        this.send(BtCmd.querySleep);
+    async getSleep() {
+        await this.send(BtCmd.querySleep());
     }
 
-    setAlert(open, weekCycle, hour, minutes, channel = 1) {
-        this.send(BtCmd.setAlarm({ switchStatus: open, weekCycle, hour, minutes }));
+    async setAlert(open, weekCycle, hour, minutes, channel = 1) {
+        await this.send(BtCmd.setAlarm({ switchStatus: open, weekCycle, hour, minutes }));
     }
 
-    setAutoPlay(open) {
-        this.send(BtCmd.setAutoPlay({ switchStatus: open }));
+    async setAutoPlay(open) {
+        await this.send(BtCmd.setAutoPlay({ switchStatus: open }));
     }
 
-    getAutoPlay() {
-        this.send(BtCmd.getAutoPlay);
+    async getAutoPlay() {
+        await this.send(BtCmd.getAutoPlay);
     }
 
-    setLowKwhWarningTone(notify) {
-        this.send(BtCmd.setLowKwhWarningTone({ notify }));
+    async setLowKwhWarningTone(notify) {
+        await this.send(BtCmd.setLowKwhWarningTone({ notify }));
     }
 
-    setPauseSleep(time) {
-        this.send(BtCmd.setSleepAfterPlayPause({ time }));
+    async setPauseSleep(time) {
+        await this.send(BtCmd.setSleepAfterPlayPause({ time }));
     }
 
-    getPauseSleep() {
-        this.send(BtCmd.querySleepAfterPlayPause);
+    async getPauseSleep() {
+        await this.send(BtCmd.querySleepAfterPlayPause());
     }
 
-    setRGB(r, g, b) {
-        this.send(BtCmd.setRGB({ r, g, b }));
+    async setRGB(r, g, b) {
+        await this.send(BtCmd.setRGB({ r, g, b }));
     }
 
-    setSleep(open, hour, minutes) {
-        this.send(BtCmd.setSleep({ switchStatus: open, hour, minutes }));
+    async setSleep(open, hour, minutes) {
+        await this.send(BtCmd.setSleep({ switchStatus: open, hour, minutes }));
     }
 
-    setTime() {
-        this.send(BtCmd.setTime);
+    async setTime() {
+        await this.send(BtCmd.setTime());
     }
 
     async setVolume(volume) {
@@ -314,11 +293,11 @@ class BtHelper {
 
         console.log(`phoneMax=${phoneMax}, deviceMax=${CmdBase.volumeMax}, setVolume=${volume}, result=${result}`);
 
-        this.send(BtCmd.setVolume({ volume: result }));
+        await this.send(BtCmd.setVolume({ volume: result }));
     }
 
-    getVolume() {
-        this.send(BtCmd.queryVolume);
+    async getVolume() {
+        await this.send(BtCmd.queryVolume());
     }
 
     stop() {
@@ -360,47 +339,47 @@ class BtHelper {
         console.log(`回调结束录音:${supplier}`);
         switch (supplier) {
             case EnumSupplier.jieLi:
-                this.send(BtCmd.jlStopVoiceResponse);
+                this.send(BtCmd.jlStopVoiceResponse());
                 break;
             case EnumSupplier.lingXin:
-                this.send(BtCmd.lxStopVoiceResponse);
+                this.send(BtCmd.lxStopVoiceResponse());
                 break;
             case EnumSupplier.qiXinWei:
-                this.send(BtCmd.b1StopVoiceResponse);
+                this.send(BtCmd.b1StopVoiceResponse());
                 break;
         }
     }
 
-    getLowDelayMode() {
-        this.send(BtCmd.queryLowDelayMode);
+    async getLowDelayMode() {
+        await this.send(BtCmd.queryLowDelayMode());
     }
 
-    setLowDelayMode(open, mode) {
-        this.send(BtCmd.setLowDelayMode({ open, mode }));
+    async setLowDelayMode(open, mode) {
+        await this.send(BtCmd.setLowDelayMode({ open, mode }));
     }
 
-    setLowPowerMode(isOpen) {
-        this.send(BtCmd.setLowPowerMode({ isOpen: isOpen ? EnumOpen.open : EnumOpen.close }));
+    async setLowPowerMode(isOpen) {
+        await this.send(BtCmd.setLowPowerMode({ isOpen: isOpen ? EnumOpen.open : EnumOpen.close }));
     }
 
-    queryLowPower() {
-        this.send(BtCmd.queryLowPower);
+    async queryLowPower() {
+        await this.send(BtCmd.queryLowPower());
     }
 
-    setCtrlStatus(singleClick, doubleClick, longClick) {
-        this.send(BtCmd.setCtrlStatus({ singleClick, doubleClick, longClick }));
+    async setCtrlStatus(singleClick, doubleClick, longClick) {
+        await this.send(BtCmd.setCtrlStatus({ singleClick, doubleClick, longClick }));
     }
 
-    getEQ() {
-        this.send(BtCmd.queryEQ);
+    async getEQ() {
+        await this.send(BtCmd.queryEQ());
     }
 
-    setEQ(list) {
-        this.send(BtCmd.setEQ({ list }));
+    async setEQ(list) {
+        await this.send(BtCmd.setEQ({ list }));
     }
 
-    queryLowKwhWarningTone() {
-        this.send(BtCmd.queryLowKwhWarningTone);
+    async queryLowKwhWarningTone() {
+        await this.send(BtCmd.queryLowKwhWarningTone());
     }
 
     async changeChannelCallBack() {