|
★☆☆☆☆☆☆☆☆☆ |
积分:58 |
发帖:62 |
登录:2024/3/26 |
注册:2006/9/17 |
|
(1楼)【原创】小程序读取蓝牙手环数据
在拼多多买了个11块钱的手环(M4),测试用小程序读取手环步数 // 执行完后回调 func(步数, 提示信息);
function getBlueStep(func) {
// 从本地缓存获取绑定的手环参数
var bangle = wx.getStorageSync("bangle") || 0;
if(!bangle) return func(0, "");
// 获取蓝牙手环步数
var deviceId = bangle.deviceId;
var serviceId = bangle.serviceId || "000018D0-0000-1000-8000-00805F9B34FB";
var characteristicId = bangle.characteristicId || "00002D00-0000-1000-8000-00805F9B34FB";
var buf2hex = buffer => [].map.call(new Uint8Array(buffer), x => ("0" + x.toString(16)).slice(-2)).join("");
// 读取到值后
wx.onBLECharacteristicValueChange(charact => {
var val = buf2hex(charact.value);
func(parseInt(val.substr(14, 8), 16), "OK");
});
wx.openBluetoothAdapter({
fail: err => func(0, err.errMsg),
success: () => {
wx.createBLEConnection({
complete: res => {
if(res.errCode) {
wx.closeBluetoothAdapter();
return func(0, res.errMsg);
}
wx.readBLECharacteristicValue({
complete: res => {
// 完成后关闭连接
wx.closeBLEConnection({
complete: () => {
wx.closeBluetoothAdapter();
}, deviceId
});
// 读取没成功
if(res.errCode) func(0, res.errMsg);
}, characteristicId, deviceId, serviceId
});
}, deviceId
});
}
});
}
|
|
★☆☆☆☆☆☆☆☆☆ |
积分:58 |
发帖:62 |
登录:2024/3/26 |
注册:2006/9/17 |
|
(4楼)附带一个枚举特征值的代码
var deviceId = "C2:FC:01:D9:67:75";
// 打开蓝牙
wx.openBluetoothAdapter({
success: () => {
wx.createBLEConnection({
complete: res => {
var closeBlue = () => wx.closeBLEConnection({
complete(){
wx.closeBluetoothAdapter();
console.log("蓝牙已关闭");
}, deviceId
});
listService(deviceId, closeBlue);
}, deviceId
});
}
});
function listService(deviceId, closeBlue) {
var forEach = (arr, id) => {
var item = arr[id];
if(!item) return closeBlue();
listCharact(deviceId, item.uuid, () => forEach(arr, ++id));
};
var buf2hex = buffer => [].map.call(new Uint8Array(buffer), x => ("0" + x.toString(16)).slice(-2)).join("");
wx.onBLECharacteristicValueChange(charact => {
var val = buf2hex(charact.value);
// if(!/133/.test(val)) return;
console.log(val, charact);
});
wx.getBLEDeviceServices({
complete: res => forEach(res.services, 0), deviceId
});
}
function listCharact(deviceId, serviceId, nextService) {
var forEach = (arr, id) => {
var item = arr[id];
if(!item) return nextService();
if(!item.properties.read) return forEach(arr, ++id);
wx.readBLECharacteristicValue({
complete() {
forEach(arr, ++id);
}, characteristicId: item.uuid, deviceId, serviceId
});
};
wx.getBLEDeviceCharacteristics({
complete: res => {
forEach(res.characteristics, 0);
}, deviceId, serviceId
});
}
|