Quellcode durchsuchen

蓝牙灯光控制器管理

kindring vor 1 Jahr
Ursprung
Commit
5fa9ff2b4d

+ 1 - 1
components/scanHandle/scanHandle.wxss

@@ -1,7 +1,7 @@
 
 .header{
     width: 100%;
-    height: 35px;
+    height: 39px;
     border-bottom: 1px solid gray;
     display: flex;
     align-items: center;

+ 1 - 0
components/tabList/tabList.wxss

@@ -6,6 +6,7 @@
     flex-direction: column;
     overflow: hidden;
     /* margin-top: 10px; */
+    padding-bottom: 50px;
   }
   .bleDevices .titleBox{
     width: 100%;

+ 3 - 3
data/lampType.js

@@ -8,9 +8,9 @@ export const COLOR_TEMPERATURE_STEP = 50;
 // 蓝牙相关信息
 export const bleInfo = {
     // 控制uuid
-    controlUuid: "0000ffe9-0000-1000-8000-00805f9b34fb",
+    controlUuid: "0000FF01",
     // 监听数据uuid
-    notifyUuid: "0000ffe4-0000-1000-8000-00805f9b34fb",
+    notifyUuid: "0000FF10",
     // 控制uuid前几位
-    characteristicFirstUuid: "ff01",
+    characteristicFirstUuid: "0000FF02",
 }

+ 130 - 84
pages/light/light.js

@@ -7,7 +7,7 @@ import light_cmd from '../../utils/light_cmd.js'
 import { _curry } from '../../utils/mjs_curry.js'
 import BLE from '../../utils/mjs_wxble.js'
 console.log(BLE);
-const ble = new BLE();
+const ble = new BLE(null, ["bleLight"]);
 const tmpDevs = [
     {
         id: 1,
@@ -61,7 +61,8 @@ Page({
         bleDevs: tmpDevs,
     },
     // 获取蓝牙发送数据对象
-    getBleSendHandle(){
+    excuteBleSend(data){
+      console.log('获取蓝牙发送数据对象');
       // 固定值
       let controlUuid = bleInfo.controlUuid;
       let characteristicFirstUuid = bleInfo.characteristicFirstUuid;
@@ -69,21 +70,26 @@ Page({
       let deviceId = this.data.ble.deviceId;
       let serverUuid = '';
       let characteristicUuid = '';
-      
-      let server = bleServices.find(s=>s.uuid === controlUuid);
+      let characteristic;
+      let server = bleServices.find(s=>{
+        console.log(`服务uuid ${s.uuid}`);
+        console.log(s);
+        return s.uuid.startsWith(controlUuid);
+      });
       if(!server)
       {
-        // return bleFail('获取服务失败', '该设备不支持该程序');
         serverUuid = bleInfo.controlUuid;
       }else
       {
         serverUuid = server.uuid;
+        characteristic = server.characteristics.find(c=>
+          c.uuid.startsWith(characteristicFirstUuid)
+        );
       }
 
       //获取
-      let characteristic = server.characteristics.find(c=>
-        c.uuid.startsWith(characteristicFirstUuid)
-      );
+      
+      
       if(!characteristic)
       {
         // return bleFail('获取服务失败', '该设备不支持该程序');
@@ -93,8 +99,9 @@ Page({
       {
         characteristicUuid = characteristic.uuid;
       }
+      console.log(`服务uuid ${serverUuid} 特征uuid ${characteristicUuid}`);
 
-      return _curry(ble.sendData, deviceId, serverUuid, characteristicUuid);
+      return ble.sendData(deviceId, serverUuid, characteristicUuid, data);
     },
     // 亮度调节
     async brightnessChangeHandle(e){
@@ -104,72 +111,84 @@ Page({
           lamp: {...this.data.lamp, brightness: e.detail.value}
         })
         this.reComputeBgColor();
-        let fn = light_cmd.set_light(
-          this.getBleSendHandle(), 
-          this.data.lamp.brightness
-        );
+        
+        let fn = this.excuteBleSend(
+          light_cmd.set_light(this.data.lamp.brightness)
+          );
         let [_err,_res] = await handle(fn);
         if(_err){
+          console.log(_err);
           return this.bleFail('发送失败', _err.errMsg);
         }
         console.log(`亮度调节命令发送成功,亮度:${this.data.lamp.brightness}`);
     },
-      async colorChangeHandle(e){
-        console.log("色温改变");
-        console.log(e);
-        this.setData({
-          lamp: {...this.data.lamp, colorTemperature: e.detail.value}
-        })
-        this.reComputeBgColor();
+    async colorChangeHandle(e){
+      console.log("色温改变");
+      console.log(e);
+      this.setData({
+        lamp: {...this.data.lamp, colorTemperature: e.detail.value}
+      })
+      this.reComputeBgColor();
 
-        let fn = light_cmd.set_temp(
-          this.getBleSendHandle(), 
-          this.data.lamp.colorTemperature
-        );
-        let [_err,_res] = await handle(fn);
-        if(_err){
-          return this.bleFail('发送失败', _err.errMsg);
-        }
-        console.log(`亮度调节命令发送成功,亮度:${this.data.lamp.colorTemperature}`);
-      },
-      // 计算背景色
-      reComputeBgColor(){
-        let newBgC;
-        let temp = this.data.lamp.colorTemperature;
-        let light = this.data.lamp.brightness;
-        if(this.data.lamp.fullOpen){
-            temp = MAX_COLOR_TEMPERATURE / 2;
-        }
-        if(this.data.lamp.switch){
-            newBgC = calculateColor(temp, light);
-        }else{
-            newBgC = "#3b3b3b";
-        }
-        this.setData({
-            lamp: {...this.data.lamp, bgc: newBgC}
-        })
-      },
-      async fullModeSwitchHandle(e){
-        // 全开模式切换
-        console.log("全开模式切换");
-        this.setData({
-            lamp: {...this.data.lamp, fullOpen: !this.data.lamp.fullOpen}
-        })
+      let fn = this.excuteBleSend(
+        light_cmd.set_temp(this.data.lamp.colorTemperature)
+      );
+      let [_err,_res] = await handle(fn);
+      if(_err){
+        return this.bleFail('发送失败', _err.errMsg);
+      }
+      console.log(`亮度调节命令发送成功,亮度:${this.data.lamp.colorTemperature}`);
+    },
+    async executeFullModeSwitch(flag){
+      this.setData({
+        lamp: {...this.data.lamp, fullOpen: flag}
+      })
 
-        let fn;
-        let nextMode = light_cmd.light_worker_mode.DEFAULT;
-        if(this.data.lamp.fullOpen){
-          nextMode = light_cmd.light_worker_mode.FULL;
-        }
+      let fn;
+      let nextMode = light_cmd.light_worker_mode.DEFAULT;
+      if(flag){
+        nextMode = light_cmd.light_worker_mode.FULL;
+      }
 
-        fn = light_cmd.set_mode(this.getBleSendHandle(), nextMode);
-        let [_err,_res] = await handle(fn);
-        if(_err){
-          return this.bleFail('发送失败', _err.errMsg);
-        }
-        console.log(`工作模式切换成功:${this.data.lamp.fullOpen}`);
-      },
-      async switchHandle(e){
+      fn = this.excuteBleSend(
+        light_cmd.set_mode(nextMode)
+      );
+      console.log(fn);
+      [_err,_res] = await handle(fn());
+      if(_err){
+        return this.bleFail('发送失败', _err.errMsg);
+      }
+      console.log(`工作模式切换成功:${this.data.lamp.fullOpen}`);
+    },
+    async fullModeSwitchHandle(e){
+      // 全开模式切换
+      console.log("全开模式切换");
+      let _err,_res;
+      let flag = !this.data.lamp.fullOpen;
+      if(!this.data.lamp.switch){
+        return;
+      }
+
+      if (flag) {
+        // 弹窗询问是否需要启动全开模式
+        wx.showModal({
+              title: '提示',
+              content: '是否启动全开模式',
+              success: (res) => {
+                  if (res.confirm) {
+                    this.executeFullModeSwitch(flag);
+                  } else if (res.cancel) {
+                    console.log('用户点击取消')
+                    return;
+                  }
+              }
+          });
+      }else{
+        this.executeFullModeSwitch(flag);
+      }
+    },
+    async switchHandle(e){
+        let _err,_res;
         // 开关切换
         this.setData({
             lamp: {...this.data.lamp, switch: !this.data.lamp.switch}
@@ -177,37 +196,64 @@ Page({
         this.setData({
             lamp: {...this.data.lamp, fullOpen: false}
         })
+        
         this.reComputeBgColor();
 
+        console.log(`开关切换:${this.data.lamp.switch}`);
         let fn;
         if(this.data.lamp.switch){
-            fn = light_cmd.open_light(this.getBleSendHandle());
+          fn = this.excuteBleSend(
+            light_cmd.open_light()
+          );
         }else{
-            fn = light_cmd.close_light(this.getBleSendHandle());
+          fn = this.excuteBleSend(
+            light_cmd.close_light()
+          );
         }
-        let [_err,_res] = await handle(fn);
+        
+        [_err,_res] = await handle(fn);
         if(_err){
+          console.log(_err);
           return this.bleFail('发送失败', _err.errMsg);
         }
         console.log(`开关命令发送成功,开关:${this.data.lamp.switch}`);
     },
+
+    // 计算背景色
+    reComputeBgColor(){
+      let newBgC;
+      let temp = this.data.lamp.colorTemperature;
+      let light = this.data.lamp.brightness;
+      if(this.data.lamp.fullOpen){
+          temp = MAX_COLOR_TEMPERATURE / 2;
+      }
+      if(this.data.lamp.switch){
+          newBgC = calculateColor(temp, light);
+      }else{
+          newBgC = "#3b3b3b";
+      }
+      this.setData({
+          lamp: {...this.data.lamp, bgc: newBgC}
+      })
+    },
     
     bleFail(title,msg){
-      this.setData({
-        ble: {...this.data.ble, 
-          state: connectStateTypes.unConnect, 
-          init: false,
-          devName: "",
-          deviceId: "",
-        },
-        bleDevs: []
-      });
-      bleServices = [];
       wx.showModal({
         title: title,
         content: msg,
-        success (res) { }
-      }) 
+        success (res) { 
+          this.setData({
+            ble: {...this.data.ble, 
+              state: connectStateTypes.unConnect, 
+              init: false,
+              devName: "",
+              deviceId: "",
+            },
+            bleDevs: []
+          });
+          bleServices = [];
+        }
+      });
     },
     // 蓝牙控制板块
     searchDeviceHandle() {
@@ -274,12 +320,12 @@ Page({
         ble:{...this.data.ble, state:connectStateTypes.connected }
       });
       // 设备服务管理
-      this.connectServices();
+      this.connectServices(dev.deviceId);
   },
 
-  async connectServices(){
+  async connectServices(deviceId){
       // uuid FF01
-      let [err,res] = await handle(ble.getBleServices());
+      let [err,res] = await handle(ble.getBleServices(deviceId));
       if(err){ return this.bleFail('获取服务失败', err.errMsg);}
       // 保存服务信息;
       bleServices = res;

+ 19 - 5
pages/light/light.wxml

@@ -1,10 +1,13 @@
 <!--pages/light/light.wxml-->
 <view class="lamp" hover-class="none" hover-stop-propagation="false">
-    <scanHandle 
-    state="{{ble.state}}" 
-    dev-name="{{ble.devName}}"
-    bindsearchDevice="searchDeviceHandle"
-    />
+    <view class="lamp_header">
+        <scanHandle 
+            state="{{ble.state}}" 
+            dev-name="{{ble.devName}}"
+            bindsearchDevice="searchDeviceHandle"
+            />
+    </view>
+    
 
     <view class="lamp__content" style="background-color:{{lamp.bgc}}">
         <tabList
@@ -93,6 +96,17 @@
 
         </view>
 
+        <!-- 灯光控制 end -->
+
+        <!-- 开始扫描按钮 -->
+        <view class="lampControl lampControl__scan"
+        wx:if="{{ble.state === connectStateTypes.unConnect}}"
+        bindtap="searchDeviceHandle"
+        >
+            <view class="scanBtn" hover-class="none" hover-stop-propagation="false">
+                开始扫描
+            </view>
+        </view>
 
     </view>
 </view>

+ 41 - 2
pages/light/light.wxss

@@ -2,8 +2,14 @@
     width: 100vw;
     height: 100vh;
     position: relative;
+    background-color: #3b3b3b;
+}
+.lamp_header{
+    width: 100%;
+    height: 40px;
+    background-color: #fff;
+    box-sizing: border-box;
 }
-
 .lamp__content{
     width: 100%;
     height: auto;
@@ -12,6 +18,8 @@
     height: calc(100% - 40px);
     /* 暗灰 */
     background-color: #3b3b3b;
+    box-sizing: border-box;
+    padding-bottom: 40px;
 }
 
 .lampControl{
@@ -85,4 +93,35 @@
 .lampControl_slider{
     width: 100%;
     height: 50px;
-}
+}
+
+.lampControl__scan{
+    width: 100%;
+    height: calc(100% - 40px);
+    border-radius: 5px;
+    box-shadow: 0 0 1px 0px #3b3b3b;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    box-sizing: border-box;
+}
+
+.lampControl__scan .scanBtn{
+    width: 130px;
+    height: 130px;
+    border-radius: 50%;
+    background-color: #f58505;
+    color:#fff;
+    padding: 5px;
+    font-size: larger;
+    box-sizing: border-box;
+    display: flex;
+    align-items: center;
+    justify-content: center;
+    box-shadow: 0 0 1px 0px #3b3b3b;
+}
+
+.scanBtn:active{
+    background-color: #f78e16;
+    box-shadow: 0 0 3px 0px #858484;
+}

+ 19 - 16
utils/light_cmd.js

@@ -160,7 +160,7 @@ export function parseCmdData(data){
  */
 export function generateCmdData(cmd, data){
     let cmdStr = ``;
-    let cmdLen = data.length || 0;
+    let cmdLen = data? data.length : 0;
     let sn = cmdList.length + 1;
     // 拼接起始码
     cmdStr += dec2hex(light_cmd_start_code.START_CODE_CMD);
@@ -171,7 +171,7 @@ export function generateCmdData(cmd, data){
     // 拼接序列号
     cmdStr += dec2hex(sn);
     // 拼接数据
-    cmdStr += data;
+    if(data) cmdStr += data;
 
     // 记录命令
     cmdList.push({
@@ -187,9 +187,10 @@ export function generateCmdData(cmd, data){
  * @param {function} sendFn 发送函数,从外部传入
  * @returns 
  */
-export function open_light(sendFn){
+export function open_light(){
+    console.log('开灯');
     let data = generateCmdData(light_cmd_code.CMD_OPEN);
-    return sendFn(data);
+    return data;
 }
 
 /**
@@ -197,9 +198,9 @@ export function open_light(sendFn){
  * @param {function} sendFn 发送函数,从外部传入
  * @returns 
  */
-export function close_light(sendFn){
+export function close_light(){
     let data = generateCmdData(light_cmd_code.CMD_CLOSE);
-    return sendFn(data);
+    return data;
 }
 
 /**
@@ -207,9 +208,9 @@ export function close_light(sendFn){
  * @param {function} sendFn 发送函数,从外部传入
  * @returns 
  */
-export function query_light(sendFn){
+export function query_light(){
     let data = generateCmdData(light_cmd_code.CMD_QUERY);
-    return sendFn(data);
+    return data;
 }
 
 /**
@@ -218,9 +219,11 @@ export function query_light(sendFn){
  * @param {number} light 亮度
  * @returns 
  */
-export function set_light(sendFn, light){
+export function set_light( light){
+    console.log("亮度调节");
     let data = generateCmdData(light_cmd_code.CMD_LIGTH, dec2hex(light));
-    return sendFn(data);
+    console.log(data);
+    return data;
 }
 
 /**
@@ -229,9 +232,9 @@ export function set_light(sendFn, light){
  * @param {number} temp 色温
  * @returns 
  */
-export function set_temp(sendFn, temp){
+export function set_temp( temp){
     let data = generateCmdData(light_cmd_code.CMD_TEMP, dec2hex(temp));
-    return sendFn(data);
+    return data;
 }
 
 /**
@@ -240,9 +243,9 @@ export function set_temp(sendFn, temp){
  * @param {number} fun 功能
  * @returns 
  */
-export function set_fun(sendFn, fanSpeed){
+export function set_fun( fanSpeed){
     let data = generateCmdData(light_cmd_code.CMD_FAN, dec2hex(fanSpeed));
-    return sendFn(data);
+    return data;
 }
 
 /**
@@ -251,9 +254,9 @@ export function set_fun(sendFn, fanSpeed){
  * @param {number} mode 模式
  * @returns 
  */
-export function set_mode(sendFn, mode){
+export function set_mode( mode){
     let data = generateCmdData(light_cmd_code.CMD_MODE, dec2hex(mode));
-    return sendFn(data);
+    return data;
 }
 
 

+ 5 - 0
utils/mjs_buffer.js

@@ -34,6 +34,11 @@ export function hexStr2Arr(hexStr){
   return arr;
 }
 
+// 任意数字转字符串
+export function num2str(num){
+  return num.toString();
+}
+
 function hexStrToBuffer(str){
   // 填充首位
   if(str.length % 2){str=`0${str}`}

+ 4 - 5
utils/mjs_curry.js

@@ -1,12 +1,11 @@
 export function _curry(fn){
     let _arguments = Array.from(arguments);
     let params = _arguments.splice(1);
+    console.log(params);
     return function(){
         let __arguments = Array.from(arguments);
-        if(__arguments.length >= 1){
-            params.push(...__arguments);
-        }else{
-            return fn(...params,...arguments);
-        }
+        console.log('执行函数');
+        console.log(params, arguments);
+        return fn(...params,...arguments);
     }
 }

+ 60 - 30
utils/mjs_wxble.js

@@ -4,12 +4,16 @@ import {buf2hex, hex2ab} from "./mjs_buffer";
 class BLE{
   // 白名单设备id列表
   whiteList = [];
+  nameList = [];
   useWhiteList = false;
-  constructor(whiteList = []){
+  constructor(whiteList = [], nameList = []){
     // this代表实例对象
-     this.isInit= false;
+    this.isInit= false;
+    whiteList = whiteList?whiteList:[];
+    nameList = nameList?nameList:[];
     this.whiteList = whiteList;
-    this.useWhiteList = whiteList.length > 0;
+    this.nameList = nameList;
+    this.useWhiteList = whiteList.length > 0 || nameList.length > 0;
  }
   
   
@@ -33,42 +37,66 @@ class BLE{
      setTimeout(() => {
       console.log("test");
     }, 2500);
-    wx.onBluetoothDeviceFound(function (res) {
-        var bleArray = res.devices;
+    wx.onBluetoothDeviceFound((res)=> {
+        let bleArray = res.devices;
+        let advertisData = "",
+          deviceId = "";
+        let isAdd = false;
         //这里会收到周边搜索到的蓝牙
         console.log("\n\nfind devices ----");
         // console.log(res);
         console.log(res.devices);
         // 对
         for (let index = 0; index < bleArray.length; index++) {
-          const ble = bleArray[index];
-
-          if(ble.advertisData){
-            // 解析到特征值设备
-            let advertisData = buf2hex(ble.advertisData);
-            let deviceId = buf2hex(ble.deviceId);
-            let devName = ble.name;
-            console.log(`设备名:${devName} 设备id:${deviceId} 特征值:${advertisData}`);
-            console.log(advertisData);
+          let ble = bleArray[index];
+          isAdd = false;
+          deviceId = buf2hex(ble.deviceId);
+          // 特征值
+          if(ble.advertisData) advertisData = ble.advertisData;
+          // 判断是否有白名单
+          if (this.useWhiteList  ){
+            // 特征值检测
+            isAdd = !!this.whiteList.find( codeStr => advertisData.startsWith(codeStr));
+            // 设备名检测
+            isAdd = !!this.nameList.find( codeStr => ble.name.startsWith(codeStr)) 
+          }else{
+            // 没有白名单,全部返回
+            isAdd = true;
+          }
 
-            console.log(ble);
-            if (this.useWhiteList ){
-              if(whiteList.find(codeStr=>advertisData.startsWith(codeStr))){
-                console.log('找到匹配到的设备');
-                  // 找到相机
-                  onSearchCallback({
-                    ...ble,
-                    hexAdvertisData: advertisData
-                  })
-              }
-            }else{
-              onSearchCallback({
-                ...ble,
-                hexAdvertisData: advertisData
-              })
-            }
+          if(isAdd){
+            console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
+            onSearchCallback({
+              ...ble,
+              hexAdvertisData: advertisData
+            });
           }
+          
         }
+        // 防止检索漏掉设备
+        // wx.getBluetoothDevices({complete:(res, err)=> {
+        //   for (let i = 0; i < res.devices.length; i++) {
+        //     let ble = res.devices[i];
+        //     isAdd = false;
+        //     if(ble.advertisData){
+        //       advertisData = ble.advertisData;
+        //     }
+        //     if(this.useWhiteList){
+        //       isAdd = !!this.nameList.find(nameStr=>ble.name.startsWith(nameStr));
+        //       isAdd = !!this.whiteList.find(codeStr=>advertisData.startsWith(codeStr));
+        //     }else{
+        //       isAdd = true;
+        //     }
+
+        //     if(isAdd){
+        //       console.log(`设备名:${ble.name} 设备id:${deviceId} 特征值:${advertisData}`);
+        //       onSearchCallback({
+        //         ...ble,
+        //         hexAdvertisData: advertisData
+        //       })
+        //     }
+        //   }
+        // }});
     });
     wx.startBluetoothDevicesDiscovery({
       success(res) {
@@ -107,6 +135,7 @@ class BLE{
   // 获取蓝牙服务
   getBleServices(devId){
     let self = this;
+    console.log(`获取蓝牙[ ${devId} ]的服务`);
     return new Promise((resolve,reject)=>{
 
       wx.getBLEDeviceServices({
@@ -171,6 +200,7 @@ class BLE{
 
   // 向指定特征发送数据
   sendData(devId, serviceId,characteristicId, hexStr){
+    console.log(`向${devId}的${serviceId}的${characteristicId}发送数据`);
     console.log(hexStr);
     hexStr = hex2ab(hexStr);
     console.log(hexStr);