微信小程序开发笔记[5]-蓝牙控制家居

esp32

[https://www.jianshu.com/p/758f5958bf74]

蓝牙UUID生成

[https://www.uuidgenerator.net/]
打开网址就有一个随机的UUID

What is a version 4 UUID?
A Version 4 UUID is a universally unique identifier that is generated using random numbers. The Version 4 UUIDs produced by this site were generated using a secure random number generator.
What is a Version 1 UUID?
A Version 1 UUID is a universally unique identifier that is generated using a timestamp and the MAC address of the computer on which it was generated.

esp32-devkitv1开发板

板载LED灯:IO2(高电平有效)

esp32程序(Arduino IDE)

/*
微信小程序连接esp32蓝牙,控制LED灯
*/

#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

// See the following for generating UUIDs:
// https://www.uuidgenerator.net/

#define SERVICE_UUID        "9c9f8008-34c7-445a-b53e-4fdb864ccc45"   //你可以通过上面的网址去生成UUID
#define CHARACTERISTIC_UUID "eef52c2d-8b1d-445a-ad6b-5e02e678361d"
void set_light(std::string input){
  if(input=="on"){
    //digitalWrite(LED_BUILTIN,HIGH);
    digitalWrite(2,HIGH);
  }
  if(input=="off"){
    //digitalWrite(LED_BUILTIN,LOW);
    digitalWrite(2,LOW);
  }
}
//由终端发来的信息将在这里显示
class MyCallbacks: public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string value = pCharacteristic->getValue();
    if (value.length() > 0) {
        for (int i = 0; i < value.length(); i++)
          Serial.print(value[i]);
          Serial.println();
          //点灯
          set_light(value);
    }
  }
};

void setup() {
  //LED灯
  //pinMode(LED_BUILTIN,OUTPUT);
  pinMode(2,OUTPUT);

  Serial.begin(9600);

  BLEDevice::init("JDY-16"); //当服务启动时,你将在你的手机蓝牙中发现它
  BLEServer *pServer = BLEDevice::createServer();

  BLEService *pService = pServer->createService(SERVICE_UUID);

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
                                         CHARACTERISTIC_UUID,
                                         BLECharacteristic::PROPERTY_READ |
                                         BLECharacteristic::PROPERTY_WRITE
                                       );

  pCharacteristic->setCallbacks(new MyCallbacks());

  pCharacteristic->setValue("Hello World");
  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();
  pAdvertising->start();
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
}

已编译的二进制文件

esp32-devkitv1开发板
[http://www.qsbye.cn/files/sketch_dec04a.ino.esp32.bin]
自取.

微信小程序

[https://blog.csdn.net/A_shy_dove/article/details/126857520]
或者参考:
[https://git.weixin.qq.com/hpz/bluetooth]
[https://git.weixin.qq.com/zoser/BlueToothTool-ColorUI]

关键代码

connectBle:function(){
    console.log(this.data.accountInput+"  "+this.data.pswInput);
    let _this=this;
    if (wx.openBluetoothAdapter) {
            wx.openBluetoothAdapter({
                success: function(res) {
                    /* 获取本机的蓝牙状态 */
                    setTimeout(() => {
                        _this.getBluetoothAdapterState()
                    }, 1000)
                    console.log(res)
                },
                fail: function(err) {
                  // 初始化失败
                  console.log("err"+err);
                  console.log(JSON.stringify(err));
                }
            })
        } else {
            console.log("step0");
        }
  },
  getBluetoothAdapterState() {
    let _this=this;
    wx.getBluetoothAdapterState({
        success: function(res) {
          console.log(res)
          _this.startBluetoothDevicesDiscovery();
        },
        fail(res) {
            console.log(res);
        }
    })
  },
  startBluetoothDevicesDiscovery() {
    var _this = this;
        wx.startBluetoothDevicesDiscovery({
            success: function(res) {
                /* 获取蓝牙设备列表 */
                console.log(res);
                _this.getBluetoothDevices();
            },
            fail(err) {
              console.log(err);
            }
        })
  },
  /**
  * JDY-16 为设备名称,由硬件工程师提供
  */
  getBluetoothDevices() {
    var that = this;
        wx.getBluetoothDevices({
            services: [],
            allowDuplicatesKey: false,
            interval: 0,
            success: function(res) {
              console.log(res);
                if (res.devices.length > 0) {
                  console.log(res.devices.length);
                  for (let i = 0; i < res.devices.length; i++) {
                    console.log(res.devices[i].name)
                            if ("JDY-16" == res.devices[i].name) {//这个是你在adruino 代码中设置的蓝牙设备名称
                                /* 根据指定的蓝牙设备名称匹配到deviceId */
                                console.log(res.devices[i].name)
                                that.connectTO(res.devices[i].deviceId);
                                that.setData({
                                  deviceId:res.devices[i].deviceId
                                });
                            };
                        };
                } else {
                }
            },
            fail(err) {
                console.log(err, '获取蓝牙设备列表失败=====')
            }
        })
  },
  connectTO(deviceid) {
    console.log("connect....");
    console.log(deviceid);
    let that=this;
      wx.createBLEConnection({
          deviceId: deviceid,
          success: function(res) {
              console.log(res);
              /* 4.获取连接设备的service服务 */
              console.log("连接完成..");

              wx.stopBluetoothDevicesDiscovery({
                  success: function(res) {
                      console.log(res, '停止搜索')
                  },
                  fail(err) {
                    console.log(err);
                  }
              })
          },
          fail: function(res) {
          }
      })
  },
  getMsg(){
    console.log(this.data.accountInput);
    console.log(this.data.pswInput);
    //表单验证重要
    //发送的消息  id:xxxxxxxxxxx
    //           pw:xxxxxxxxxx
    //每次发送信息不得超过20个字节,在表单验证中限制 除去包头3个字节,wifi账号或密码不得超过17个字节
    this.sendMsg("id:"+this.data.accountInput);
    //因为20个字节的限制,你不能一口气把消息发送完成,只能分批发送,那么你需要延迟,否则会被认为是一条信息,那么超出的部分会被截断
    setTimeout(() => {
       this.sendMsg("pw:"+this.data.pswInput);
    }, 1000);
  },
  sendMsg(str) {

    let that = this;
    let dataBuffer = new ArrayBuffer(str.length);
    let dataView = new DataView(dataBuffer)
    for (var i = 0; i < str.length; i++) {
        dataView.setUint8(i, str.charAt(i).charCodeAt())
    }
    let dataHex = that.ab2hex(dataBuffer);
    this.writeDatas = that.hexCharCodeToStr(dataHex);
    //serviceId、characteristicId 由硬件工程师提供
    wx.writeBLECharacteristicValue({
        deviceId: that.data.deviceId,
        serviceId: "",
        characteristicId:"", //这两个ID请自己生成
        value: dataBuffer,
        success: function (res) {
            console.log(res);
        },
        fail: function (err) {
          console.log(err);
        },
        complete: function (res) {
        }
    })
  },
 /*转成二进制*/
  ab2hex (buffer) {
    var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer), function (bit) {
    return ('00' + bit.toString(16)).slice(-2)
    })
    return hexArr.join('')
  },
  accountInput:function(e){
    this.setData({
      accountInput:e.detail.value
    }) 
  },
 /*转成可展会的文字*/
  hexCharCodeToStr(hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
    var len = rawStr.length;
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16);
      resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join('');
  }

效果

为了图省事,直接用别人现成的小程序
[https://blog.csdn.net/old_brown/article/details/113876226]

连接

点灯

on


off

发现

笔者发现上述提到的小程序还可以实现自定义功能,也就是说可以有更丰富的家居控制玩法。所以也不用造轮子了

posted @ 2022-12-05 02:39  qsBye  阅读(389)  评论(0编辑  收藏  举报