# 一、小程序如何开发蓝牙通信
小程序蓝牙连接跟业务逻辑我就不一一介绍,自行百度,下面直接说如何给蓝牙设备发送指令
// 直接定义一个通用函数发送指令
// 操作数据
writeBLECharacteristicValue(hex = 'AB BC 08 30 01 00 00 2E') {
// let app = ['AB','BC','08','40','00','00','00']
// console.log(this.yfnc(app), "<=app")
// console.log(app,"<=app")
// 向蓝牙设备发送一个0x00的16进制数据
const t = this
let arr = hex.split(' ').map(item => {
return '0x' + item
})
console.log(arr)
console.log(hex)
let typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
}))
let buffer = typedArray.buffer
let dataView = new DataView(buffer) // 操作硬件内存,输入指令
arr.forEach((item, i) => {
dataView.setUint8(i, arr[i]) // 定义的是8字节, 循环操作
})
console.log("%c写入数据", "color: red;",dataView,typedArray, buffer)
console.log("%cdeviceId=>", "color: green;", this._deviceId, )
console.log("%cserviceId=>", "color: green;", this._serviceId)
console.log("%ccharacteristicId=>", "color: green;", this._characteristicId)
wx.writeBLECharacteristicValue({
deviceId: t._deviceId,
serviceId: t._serviceId,
characteristicId: t._characteristicId,
value: buffer,
// value: arr,
// writeType: 'write',
success (res) {
console.log('%c发送成功 success', "color: blue;", res)
},
fail(res) {
console.log('%cwriteBLE error', "color: red;", res)
wx.showToast({
title: '设备发送失败',
icon: 'none'
})
},
complete(res) {
// console.log('%cwriteBLE complete', "color: red;", res)
}
})
},
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
如图所见 先组成一个数组["0xAB", "0xBC", "0x08", "0x30", "0x01", "0x00", "0x00", "0x2E"]
一共 8 个值,前两个是头,类似前后端交互中的 header,第三个是注明此次是几字节, 其次第四五个是指令内容,六七位硬件没做要求,第八位就是校验码,防止传输后发生意外错误,具体以硬件给的文档为主
// 最后一位指令校验 异或处理 有兴趣的可以自己试下
yfnc(arr){
for(let i = 0; i < arr.length; i++){
result = result ^ arr[i].match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
});
}
return t.d2h(result);
},
d2h(d) { return (+d).toString(16).toUpperCase(); },
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11