1.需求
模仿蓝牙钥匙靠近充电桩桩开始自动充电(广播指定数据047F0E770416桩接收并启动自动充电)
2.微信官方API
添加链接描述
3.注意点分两个
3.1 需要开启蓝牙wx.openBluetoothAdapter的mode:peripheral
3.2 发送数有变化BLEPeripheralServer.startAdvertising的manufacturerData修改ios系统不支持可以通过 serviceUuids传值(ps这个需要嵌入式配合才行)
deepseek蓝牙数据包解析
4.Demo页面
4.代码
/*停止蓝牙广播*/
stopBLE() {
this.server.stopAdvertising({
success(res) {
console.log('蓝牙广播停止成功')
},
fail(err) {
console.log('蓝牙广播停止失败')
}
})
},
/*开启蓝牙*/
openBLE() {
let that = this;
wx.openBluetoothAdapter({
mode: 'peripheral',
success(res) {
that.createBLE()
},
fail(err) {
console.log('蓝牙初始化失败' + err)
}
})
},
/*开始广播*/
createBLE() {
let _this = this
wx.createBLEPeripheralServer({
success: (res) => {
_this.server = res.server
if (res.errMsg == "createBLEPeripheralServer:ok") {
wx.showToast({
title: '创建成功',
icon: 'success'
})
}
_this.addService();
}
})
},
/*添加服务*/
addService() {
const that = this;
this.server.addService({
service: {
uuid: '0000FFF0-0000-1000-8000-00205F9B34EB', // 服务 UUID
characteristics: [{
uuid: "0000FFF1-0000-1000-8000-00205F9B34EB",
properties: {
read: true, // 允许读取
write: true, // 允许写入
notify: true, // 允许通知
},
permission: {
readable: true
},
value: '',
},
{
uuid: "0000FFF2-0000-1000-8000-00205F9B34EB",
properties: {
writeNoResponse: true,
extendedProperties: true
},
permission: {
writeable: true
},
value: '',
}
],
},
success(res) {
console.log('服务添加成功', res);
// 开始广播
that.startAdvertising();
},
fail(err) {
console.error('服务添加失败', err);
}
});
},
/*开始广播本地创建的外围设备*/
startAdvertising() {
const that = this;
console.log('开始广播数据哟')
that.server.startAdvertising({
advertiseRequest: {
connectable: true, // 允许连接
deviceName: "CCC", // 设备名称
serviceUuids: ['FFFF','7F04', '770E', '1604'], // 广播的服务 UUID
powerLevel: "high",
},
success(res) {
console.log('广播开始成功', res);
// that.startWrite()
},
fail(err) {
console.error('广播开始失败', err);
}
});
},
5.小程序广播出来蓝牙调试工具搜索到的蓝牙广播数据包
6.充电桩成功充电