微信小程式開發筆記[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
發現
筆者發現上述提到的小程式還可以實現自定義功能,也就是說可以有更豐富的家居控制玩法。所以也不用造輪子了