Skip to content

Instantly share code, notes, and snippets.

@taoyuan
Last active June 24, 2018 16:02
Show Gist options
  • Save taoyuan/3e9757ac27c77639e3f6e36c64038026 to your computer and use it in GitHub Desktop.
Save taoyuan/3e9757ac27c77639e3f6e36c64038026 to your computer and use it in GitHub Desktop.
微信小程序蓝牙 Roal 适配器
const rpc = roal.RPC.create(new WxTransport({
serviceUUID: 'F010',
characteristicUUID: 'F011'
});
rpc.request('ping').then(result => console.log(result));
class WxTransport extends roal.Transport {
constructor(options) {
super();
this._buf = [];
this._serviceUUID = options.serviceUUID;
this._characteristicUUID = options.characteristicUUID;
this._deviceId = null; // 扫描连接后,更新此字段
this.ready = this.setup();
}
setup() {
return new Promise((resolve, reject) => {
// 扫描蓝牙设备
// 匹配到对应的设备
// 连接蓝牙设备,成功后,
// * 给 this._deviceId 赋值
// * 调用 onConnect
// * resolve 这个 Promise
// * 错误调用 reject
});
}
onConnect() {
wx.onBLECharacteristicValueChange(c => this.onBLECharacteristicValueChange(c.value));
}
onBLECharacteristicValueChange(value) {
const length = value.length < 0 ? 0 : value.length;
if (length <= 2) {
return this._buf = [];
}
const offset = value[0] | (value[1] << 8);
if (this._buf.length !== (offset & 0x7FFF)) {
return this._buf = [];
}
this._buf = this._buf.concat(value.slice(2));
if (offset & 0x8000) {
const s = fromUTF8Array(this._buf);
console.log('received: ' + s);
this.recv(JSON.parse(s));
this._buf = [];
}
}
// 这是提供给 RPC 调用的方法
// * 当调用 rcp.request 时, RPC 会对请求进行封装,并构建 message 对象,此对象格式参见 roal ts 定义;
// * 然后调用到 transport.send(message) 请求发送数据到目标连接。
// 此方法直接收一个参数,并返回一个 Promise;
send(message) {
return this.ready.then(() => {
const str = JSON.stringify(message);
const buffer = new ArrayBuffer(str.length);
for (let i = 0; i < buffer.byteLength; i++) {
buffer[i] = str[i];
}
wx.writeBLECharacteristicValue({
deviceId: this._deviceId, // deviceId 需要自行补充,在进行设备扫描和连接时,记录到对象中。
serviceId: this._serviceUUID,
characteristicId: this._characteristicUUID,
value: buffer,
success: function (res) {
console.log(res);
console.log('writeBLECharacteristicValue success', res.errMsg);
}
});
});
}
}
function fromUTF8Array(data) {
let str = '', i;
for (i = 0; i < data.length; i++) {
let value = data[i];
if (value < 0x80) {
str += String.fromCharCode(value);
}
else if (value > 0xBF && value < 0xE0) {
str += String.fromCharCode((value & 0x1F) << 6 | data[i + 1] & 0x3F);
i += 1;
}
else if (value > 0xDF && value < 0xF0) {
str += String.fromCharCode((value & 0x0F) << 12 | (data[i + 1] & 0x3F) << 6 | data[i + 2] & 0x3F);
i += 2;
}
else {
let charCode = ((value & 0x07) << 18 | (data[i + 1] & 0x3F) << 12 | (data[i + 2] & 0x3F) << 6 | data[i + 3] & 0x3F) - 0x010000;
str += String.fromCharCode(charCode >> 10 | 0xD800, charCode & 0x03FF | 0xDC00);
i += 3;
}
}
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment