Page({ data: { ShowDlog:false,//是否显示弹框 DeviceList:[],//设配列表 Update:false,//重新连接按钮 intNum:0, time:null, deviceObject:{}, deviceItem:{}, gear:1, Mode:'0x01',//模式 SpeedGear:'0x01',//档位 Status:'0x01'//开始/ 暂停 },
henFun(){ let _self=this; this.setData({ ShowDlog:true }); //初始化蓝牙模块 第一步 wx.openBluetoothAdapter({ success (res) { console.log(res) //蓝牙模块初始化成功 _self.startBluetoothDevicesDiscovery(); }, fail:function (err) { wx.showToast({ title: '蓝牙未开启', icon: 'error', duration: 2000 }); console.log('蓝牙模块初始化失败',err) }
})
},
//开始搜寻附近的蓝牙外围设备 第2步
startBluetoothDevicesDiscovery() {
let _self=this;
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
interval:1,
success: function(res) {
console.log("开始扫描蓝牙设备", res);
_self.onBluetoothDeviceFound();
},
fail:function (err) {
console.log('开始扫描蓝牙设备err',err)
},
});
},
//监听搜索到新设备的事件 第3步
onBluetoothDeviceFound() {
let _self=this;
wx.onBluetoothDeviceFound(function(res) {
var devices = res.devices;
devices.forEach((data,index)=>{
//搜索指定设配
//console.log("监听搜索到新设备的事件", res);
if(data.deviceId=='E015B716-649F-10B6-B0CB-1CBBA1A1ECCD'){
console.log("监听搜索到新设备的事件", res);
_self.data.DeviceList.push(data);
_self.setData({
DeviceList:_self.data.DeviceList
});
// 搜索指定设备 就停止搜索
wx.stopBluetoothDevicesDiscovery({
success (res) {
clearInterval(_self.data.time);
console.log("停止搜寻附近的蓝牙外围设备", res);
}
});
};
})
});
// //超过指定时间 停止监听和搜索
this.data.time=setInterval(()=>{
this.data.intNum++;
console.log(this.data.intNum);
if(this.data.intNum>=15){
clearInterval(this.data.time);
wx.stopBluetoothDevicesDiscovery({
success (res) {
console.log("停止搜寻附近的蓝牙外围设备", res);
_self.setData({
Update:true
})
}
});
};
},1000);
},
//连接蓝牙 第4步
connect(event){
let _self=this;
console.log(event.detail);
_self.createBLEConnection(event)
},
//连接蓝牙低功耗设备 获取蓝牙 第5步
createBLEConnection(event) {
let _self=this;
wx.createBLEConnection({
deviceId:event.detail.deviceId,
success: function(res) {
wx.showToast({
title: '蓝牙连接成功',
icon: 'success',
duration: 2000
});
_self.setData({
ShowDlog:false,
deviceObject:event.detail
});
_self.getBLEDeviceServices(event.detail.deviceId);
// console.log("连接蓝牙低功耗设备:", res);
}
});
},
//获取蓝牙低功耗设备所有服务 (service) 第6步
getBLEDeviceServices(deviceId) {
let _self=this;
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function(res) {
console.log("获取蓝牙低功耗设备所有服务:", res);
let serve = res.services.find(item=>item.uuid.startsWith('0000FF00')).uuid; //读的 通知服务 UUID:
let uuid = res.services.find(item=>item.uuid.startsWith('0000FF10')).uuid; //写入 特征值 UUID
_self.getBLEDeviceCharacteristics(deviceId, uuid,serve)
}
});
},
//获取蓝牙低功耗设备某个服务中所有特征 (characteristic) 第7步
getBLEDeviceCharacteristics(deviceId, uuid,serve) {
let _self=this;
//写入 获取 特征值
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: uuid,
success: function(res) {
// console.log("特征值:", res.characteristics);
let characteristicId = res.characteristics.find(c => c.properties.write).uuid; //写 获取可写的特征值;
_self.setData({
deviceItem:{
deviceId:deviceId,//设备id
serviceId:uuid,//服务id
characteristicId:characteristicId //特征值
}
});
_self.writeDataToDevice(deviceId, uuid, characteristicId);
}
});
//读取
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serve,
success: function(res) {
console.log('获取蓝牙低功耗设备某个服务中所有特征>>>>>>:', res)
let characteristicId = res.characteristics.find(c => c.properties.notify).uuid; //读 获取可写的特征值;
//启用蓝牙低功耗设备特征值变化时的 notify 功能
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId:deviceId,//这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
serviceId:serve, // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
characteristicId:characteristicId,//这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
success (res) {
console.log('启用蓝牙低功耗设备特征值变化时的 success', res)
wx.onBLECharacteristicValueChange(function(data) {
console.log('>>>16',data.value)
const dataView = new DataView(data.value);
let reportedVoltage = dataView.getUint8(4); // 获取电压数据
console.log('reportedVoltage>>>>',reportedVoltage)
let actualVoltage = reportedVoltage / 10;// // 换算成实际电压
// 定义电压阈值
const maxVoltage = 4.35;
const minVoltage = 3.0;
const voltageRange = maxVoltage - minVoltage;
// 计算电量百分比
let batteryLevel = ((actualVoltage - minVoltage) / voltageRange) * 100;
// 保证电量百分比在 0 到 100 之间
batteryLevel = Math.max(0, Math.min(100, batteryLevel));
console.log("设备电量:", batteryLevel.toFixed(0) + "%");
});
},
fail(err){
console.log('启用蓝牙低功耗设备特征值变化时的 err', err)
}
});
}
});
}, /// 向蓝牙低功耗设备特征值中写入二进制数据。注意:必须设备的特征支持 write 才可以成功调用 第8步 writeDataToDevice(deviceId, uuid, characteristicId) {
// //0xDE 0x0A 0x01 0x04 0x00 0x00 0x00 0x01 0x01 0xED 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 //指令
//h //le //Mode //SpeedGear档位 // 开始/暂停 //End:
let arr=['0xDE', '0x0A', this.data.Mode, this.data.SpeedGear, '0x00', '0x00', '0x00', '0x01', this.data.Status, '0xED', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00' ,'0x00', '0x00'];
let buffer = new ArrayBuffer(20);
let dataView = new DataView(buffer);
for(let i=0;i<arr.length;i++){
// console.log('.>>>>',i,arr[i])
dataView.setUint8(i,arr[i]);
}
console.log(arr)
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: uuid,
characteristicId: characteristicId,
value: buffer,
success: function(res) {
console.log("数据发送成功", res);
},
fail: function(err) {
console.log("数据发送失败", err);
}
});
},
//减档 minus(){ this.data.gear--; this.setData({ gear:this.data.gear, SpeedGear:'0x0'+this.data.gear
});
this.writeDataToDevice(this.data.deviceItem.deviceId,this.data.deviceItem.serviceId,this.data.deviceItem.characteristicId) }, //加档 add(){ this.data.gear++; this.setData({ gear:this.data.gear, SpeedGear:'0x0'+this.data.gear }); this.writeDataToDevice(this.data.deviceItem.deviceId,this.data.deviceItem.serviceId,this.data.deviceItem.characteristicId) },
//重新搜索 updatesearch(){ this.setData({ intNum:0, Update:false }); this.henFun() }, //取消按钮 隐藏弹框 concal(){ this.setData({ ShowDlog:false, DeviceList:[], intNum:0 }); }, //断开连接 cones(){ wx.closeBluetoothAdapter({ success (res) { wx.showToast({ title: '断开连接成功', icon: 'error', duration: 2000 }); console.log('断开连接',res) } }) }
})