接上一篇(原生微信小程序蓝牙开发(八))
我们现在说通过蓝牙设备发送指令的操作
第九步:发送信息给蓝牙(wx.writeBLECharacteristicValue)
向蓝牙低功耗设备特征值中写入二进制数据。
注意:必须设备的特征支持 write 才可以成功调用。
参数
Object object
属性 | 类型 | 默认值 | 必填 | 说明 |
---|---|---|---|---|
deviceId | string | 是 | 蓝牙设备 id | |
serviceId | string | 是 | 蓝牙特征对应服务的 UUID | |
characteristicId | string | 是 | 蓝牙特征的 UUID | |
value | ArrayBuffer | 是 | 蓝牙设备特征对应的二进制值 | |
writeType | string | 否 | 蓝牙特征值的写模式设置,有两种模式,iOS 优先 write,安卓优先 writeNoResponse 。(基础库 2.22.0 开始支持) | |
success | function | 否 | 接口调用成功的回调函数 | |
fail | function | 否 | 接口调用失败的回调函数 | |
complete | function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
官方文档:wx.writeBLECharacteristicValue(Object object)
下面是我的代码:
// 将从后台服务获取的指令写入到蓝牙设备当中
sendMy(argument) {
// 生成时间戳
const timestamp = new Date().getTime(); // 获取当前时间的时间戳(流水号
const getsid = `getsid=${this.data.ip}_${this.data.sn}_${timestamp}\n`;
const openid = `openid=${this.data.ip}_${this.data.sn}_${timestamp}\n`;
const that = this;
if (argument == "getsid") {
wx.writeBLECharacteristicValue({
deviceId: that.data.deviceId,
serviceId: that.data.services,
characteristicId: that.data.writeId,
value: that.stringToUint8Array(getsid), // 这里的value是ArrayBuffer类型
success: (res) => {
// 成功后进行的操作
return;
},
fail: (res) => {
// 失败的提示
},
});
} else if (argument == "openid") {
// 后面根据自己项目来
}
},
这里主要是展示怎么使用 api 的,具体操作根据自己项目来
我这里给蓝牙发送信息的时候封装了一个字符串转Uint8Array的方法一并呈现在下面:
stringToUint8Array(str) {
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
var tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array.buffer;
},
欢迎大家补充,一起学习进步