当前位置:网站首页>Applet Bluetooth connection low power device (ble) record
Applet Bluetooth connection low power device (ble) record
2022-04-22 06:43:00 【Bring in the red moon】
First step Check whether Bluetooth is authorized Initialize Bluetooth after authorization Get local Bluetooth status Enable listening for Bluetooth enable / disable events If you don't call openBluetoothAdapter Method The following cannot be done
In the code bluetooth Some common methods for encapsulation It will be written at the bottom
bluetooth.getBluetoothSetting().then(() => {
// Authorized Initialize Bluetooth module
wx.openBluetoothAdapter({
success: () => {},
fail: err => bluetooth.errorCodeToStr(err),
complete: () => {
wx.hideLoading()
this.setData({
bluetoothInit: true
})
// Get the status of the native Bluetooth adapter .
wx.getBluetoothAdapterState().then(res => {
this.setData({
bluetoothAvailable: res.available,
})
}).catch(err => bluetooth.errorCodeToStr(err))
// Monitor Bluetooth adapter status change events Turn on Bluetooth
wx.onBluetoothAdapterStateChange((res) => {
let page = getCurrentPages()
if (page[page.length - 1].route != 'pages/index/index') return
wx.showToast({
title: ' Bluetooth has ' + (res.available ? ' Turn on ' : ' close '),
icon: 'none'
})
this.setData({
bluetoothAvailable: res.available,
})
})
}
})
}).catch(err => {
wx.showToast({
title: err,
icon: 'none'
})
})
The second step Search for low-power Bluetooth devices And stop searching Add the searched device to the list Click the list to select the Bluetooth device you want to connect ( The click event in the list is not written Just write it yourself )
let timer=null
// Start searching for Bluetooth devices 10 Stop automatically after seconds You can also stop the search manually
starSearch() {
wx.hideLoading()
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false
}).then(res => {
this.setData({
status: 1
})
// Timed end of search
timer = setTimeout(() => {
this.stopSearch()
}, 10000)
}).catch(err => bluetooth.errorCodeToStr(err))
// Listen for events when a new device is found Add to list
wx.onBluetoothDeviceFound((res) => {
var devices = res.devices[0];
if (devices.name) {
this.setData({
list: [...this.data.list, devices]
})
}
})
},
// stop searching ( It can be called manually )
stopSearch() {
wx.hideLoading()
// Clear the timer
clearTimeout(timer)
// Cancel listening for the event of finding a new device
wx.offBluetoothDeviceFound()
// Stop searching for nearby Bluetooth peripherals Judge the number of equipment and give a prompt
wx.stopBluetoothDevicesDiscovery().then(res => {
let status = (this.data.list.length < 1 ? 2 : 3)
this.setData({
status: status
})
if (status == 2) {
wx.showModal({
title: ' Tips ',
content: ' No device detected , Please turn on the device and try again ~',
showCancel: false
})
}
}).catch(err => bluetooth.errorCodeToStr(err))
},
The third step Create a Bluetooth connection to get the required information deviceId( Get when a device is searched ) serviceId(isPrimary=true the uuid),characteristicId( This is the need for characteristics in write by true when It is used for writing uuid If you need to monitor the reported information Need to choose notify by true Of uuid) It's a concept Refer to the official documents for details and judge in combination with the information printed on your console
When the Bluetooth connection is successful, the data of the Bluetooth device can be transferred Save to cache or other location Convenient for the next direct trial
original text :
createBLEConnection Connect Bluetooth low-power devices .
If the applet has searched a Bluetooth device before , And successfully established the connection , You can directly enter the information obtained by previous search deviceId Try connecting the device directly , There is no need to search again .
// Create a Bluetooth connection
createMachineLink() {
// Before connecting Disconnect from other Bluetooth low-power devices
wx.showLoading({
title: ' Connecting ...',
mask: true
})
// Listen for disconnection
wx.onBLEConnectionStateChange((res) => {
if (!res.connected)
this.setData({
isLink: res.connected,
})
})
wx.createBLEConnection({
deviceId: this.data.deviceId,
timeout: 5000,
}).then(() => {
// Get all services of Bluetooth low-power devices (service)
wx.getBLEDeviceServices({
deviceId: this.data.deviceId
}).then(servicesData => {
this.setData({
serviceId: servicesData.services[0].uuid
}, () => {
// Get all the features in a service of Bluetooth low-power device (characteristic)
wx.getBLEDeviceCharacteristics({
deviceId: this.data.deviceId,
serviceId: this.data.serviceId,
}).then(res => {
wx.setStorageSync('leaveStatus', 'link')
wx.showToast({
title: ' Successful connection ',
})
this.setData({
isLink: true,
writeCharacteristicId: res.characteristics.find(item => item.properties.write == true).uuid,
notifyCharacteristicId: res.characteristics.find(item => item.properties.notify == true).uuid
}, () => this.notifyBluetoothListener())
}).catch(err => bluetooth.errorCodeToStr(err))
})
}).catch(err => bluetooth.errorCodeToStr(err))
}).catch(err => bluetooth.errorCodeToStr(err))
},
Step four Write data My method of direct encapsulation here You can refer to ( This needs to be passed in 10 byte Of 16 Base string ) This is just a reference
bluetooth.writeData(this.data.deviceId, this.data.serviceId, this.data.writeCharacteristicId, '044000')
// encapsulation
// Write data
writeData(deviceId, serviceId, characteristicId, value) {
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: this.createBuffer(value),
}).then(res => {
setTimeout(() => {
wx.hideLoading()
}, 700)
}).catch(err => this.errorCodeToStr(err))
},
// establish 10 position 0x00 16 Hexadecimal data
createBuffer(num) {
let buffer = new ArrayBuffer(10);
let dataView = new DataView(buffer);
// Fixed head
dataView.setUint8(0, 0x0D);
dataView.setUint8(1, 0x02);
// Fix the head and tail
dataView.setUint8(8, 0x0D);
dataView.setUint8(9, 0x03);
for (let i in num) {
dataView.setUint8(parseInt(i) + 2, ('0x' + num[i].charCodeAt().toString(16)));
}
return dataView.buffer
},
Step five Listen to the information reported by Bluetooth Decode and process accordingly
// monitor Equipment report
notifyBluetoothListener() {
wx.showLoading({
title: ' Get status ...',
mask: true
})
// Enable Bluetooth low-power device when the eigenvalue changes notify function
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: this.data.deviceId,
serviceId: this.data.serviceId,
characteristicId: this.data.notifyCharacteristicId,
}).then(res => {
// Enabled successfully Give orders obtain Equipment status
bluetooth.writeData(this.data.deviceId, this.data.serviceId, this.data.writeCharacteristicId, '018000')
}).catch(err => bluetooth.errorCodeToStr(err))
// You must first enable wx.notifyBLECharacteristicValueChange To listen to the device characteristicValueChange event
wx.onBLECharacteristicValueChange((res) => {
setTimeout(() => {
this.setData({
writeType: false
})
}, 1000)
if (res.value.length >= 11) {
bluetooth.closeBLEConnection(this.data.deviceId)
wx.showToast({
title: ' Unknown error ',
})
return
}
this.handleValueChange(bluetooth.ab2hex(res.value))
})
},
// Report result processing
handleValueChange(str) {
// Remove the fixed head and fixed tail
let hex = str.substring(4,str.length-4)
hex = bluetooth.hexCharCodeToStr(hex)
if (!hex) {
wx.showToast({
title: ' Unknown error ',
})
return
}
let status = Number('0x' + (hex.substring(0, 2)))
if (!status) {
bluetooth.closeBLEConnection(this.data.deviceId)
wx.showToast({
title: ' Unknown error ',
})
return
}
this.setData({
isRun: (status >> 6) & 1, // Is it running
isHot: (status & 1), // heating
speed: (status >> 2) & 3, // Speed
mode: (status >> 4) & 3, // Pattern
})
},
here The method used in the encapsulated code above
module.exports = {
// establish 10 position 0x00 16 Hexadecimal data
createBuffer(num) {
let buffer = new ArrayBuffer(10);
let dataView = new DataView(buffer);
// Fixed head
dataView.setUint8(0, 0x0D);
dataView.setUint8(1, 0x02);
// Fix the head and tail
dataView.setUint8(8, 0x0D);
dataView.setUint8(9, 0x03);
for (let i in num) {
dataView.setUint8(parseInt(i) + 2, ('0x' + num[i].charCodeAt().toString(16)));
}
return dataView.buffer
},
// Write data
writeData(deviceId, serviceId, characteristicId, value) {
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
value: this.createBuffer(value),
}).then(res => {
setTimeout(() => {
wx.hideLoading()
}, 700)
}).catch(err => this.errorCodeToStr(err))
},
// Disconnect Bluetooth
closeBLEConnection(deviceId, type) {
wx.closeBLEConnection({
deviceId: deviceId,
success: () => {
if (type)
wx.showToast({
title: ' disconnect ',
icon: 'none'
})
},
fail: err => this.errorCodeToStr(err, type)
})
},
// Bluetooth authorization query
getBluetoothSetting() {
return new Promise((resolve, reject) => {
wx.getSetting().then(res => {
if (!res.authSetting['scope.bluetooth']) {
this.scopeBluetooth().then(data => {
resolve(data)
}).catch(err => reject(err))
} else {
resolve(res.authSetting)
}
}).catch(err => reject('getSetting error'))
})
},
// Apply for Bluetooth authorization
scopeBluetooth() {
return new Promise((resolve, reject) => {
wx.authorize({
scope: 'scope.bluetooth',
success(res) {
resolve(res)
},
fail(err) {
wx.showModal({
title: ' Tips ',
content: ' Please authorize Bluetooth , In order to use the equipment ',
success(res) {
if (res.cancel) {
reject(' Unauthorized Bluetooth ')
return
}
wx.openSetting({
success(data) {
if (data.authSetting['scope.bluetooth']) {
resolve(data.authSetting)
} else {
reject(' Unauthorized Bluetooth ')
}
}
})
}
})
}
})
})
},
// Unified processing of Bluetooth errors
errorCodeToStr(err, type) {
console.log(err)
if (!err.errCode) {
console.log(err.errMsg)
return
}
if (type) return
wx.showToast({
title: this.codeToStr[err.errCode],
icon: 'none'
})
},
codeToStr: {
"0": " normal ",
"-1": " Connected ",
"10000": " Bluetooth adapter not initialized ",
"10001": " The Bluetooth adapter is currently unavailable ",
"10002": " The specified device was not found ",
"10003": " The connection fails ",
"10004": " The specified service was not found ",
"10005": " The specified feature was not found ",
"10006": " The current connection has been disconnected ",
"10007": " This operation is not supported by the current feature ",
"10008": " All other exceptions reported by the system ",
"10009": "Android System specific , The system version is lower than 4.3 I won't support it BLE",
"10012": " Connection timeout ",
"10013": " Connect deviceId Empty or incorrectly formatted ",
},
// ArrayBuffer turn 16 Base string
ab2hex(buffer) {
let hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
},
// ArrayBuffer turn 16 Hexadecimal string to 16 Hexadecimal Numbers
hexCharCodeToStr(hexCharCodeStr) {
var trimedStr = hexCharCodeStr.trim();
var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
var len = rawStr.length;
if (len % 2 !== 0) {
alert(" There are illegal characters !");
return "";
}
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("");
},
}
This article Just a rough record So that I can have some experience in similar projects again I hope to provide some help to those who read this article
版权声明
本文为[Bring in the red moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220556230544.html
边栏推荐
- Solutions for minors protection in the social industry of digital beauty technology: guarding the "social circle" of minors
- Pure JS chain animation and simultaneous motion
- ArcGIS 纵断面分析
- 关于一段小程序的思考
- Pgdoucer best practices: Series 3
- MongoDB初接触——基础介绍篇
- uniapp解决首页点击返回(手机返回键)跳到登录页
- MySQL在面试中经常被问到的经典问题。
- LeetCode 1547:切棍子的最小成本
- 使用Navicat 备份mysql数据库
猜你喜欢

COM in Wine(2)——基本代码分析

一个三目表达式,引起的空指针

Open source database management systems are now more popular than commercial products

The installation of redis is started and used by rookies (Windows)

Introduction to postgreshub Chinese resource network

OLAP和OLTP的区别及所对应模型(基础知识)

EXCEL VLOOKUP函数的使用(二)

EXCEL IF、AND以及OR函数的嵌套使用

EXCEL 分列功能的使用

webService接口编写并发布与webService接口的调用(二)
随机推荐
Automatically add partitions for PostgreSQL tables
Mvcc transaction isolation in PostgreSQL
The difference between watch and computed
事务不生效之this调用
Pgdoucer best practices: a series
Use PG_ STAT_ Replication monitoring replication
从零开始学安卓(kotlin)五——UI
创新实训(五)中期检查
webService接口编写并发布与webService接口的调用(一)
nodejs+Express+mongodb
APP更新
毕业设计碎碎念
PostgreSQL 13.3, 12.7, 11.12, 10.17 and 9.6.22 have been released!
Solve the problem of error in installing PostgreSQL under windows2012 R2
You can't open more than 10 pages in wechat applet. After reaching 10 pages, you can't open a new page
剑指offer:二叉树中和为某一值的路径(回溯)
总结一下我使用过的定时器:@Scheduled注解
JS judge the PC end or mobile end
js对url进行编码和解码(三种方式区别)
创新实训(十一)机票爬取 公司信息