微信小程序BLE发送一串16进制数据,低字节在前
场景
- 以时间
2000-01-01 00:00:00
和当前时间
计算差值秒
- 低字节在前,发送给设备
- 设备执行指令后返回数据,其中也包括当前UTC时间,需要进行转换
获取UTC时间
function sendCurrentTime() {
let writeSer = filterWriteServiceArr(_writeServiceArr, 'FFXX');
let writeChar = filterWriteCharacteristicArr(_writeCharacteristicArr, 'FFXX');
status = true;
let _currentTime = calcUTCTime(); // 获取UTC时间 687425644
writeData(writeSer, writeChar, _currentTime);
}
写入数据
function writeData(servicePar, characterPar, hex) {
if (!status) {
return;
}
if (!_deviceId) {
writeErrorCallback('w');
return;
}
// 处理写入数据
let buffer = utils.hexStringToArrayBuffer(4, hex.toString(16));
wx.writeBLECharacteristicValue({
deviceId: _deviceId,
serviceId: servicePar.toString(),
characteristicId: characterPar.toString(),
value: buffer,
success: (res) => {
console.log("写数据返回结果", res.errMsg);
},
fail(res) {
console.log("写数据失败..", res);
errorCallback(res.errCode, "writeBLECharacteristicValue");
}
})
}
向设备发送16进制数据
例:
28fa8561
/**
* 向设备发送16进制数据
* byteLen:字节长度
* str: 字符串
*/
const hexStringToArrayBuffer = (byteLen, str) =>{
if (byteLen <= 0) {
return new ArrayBuffer(0);
}
if (!str) {
return new ArrayBuffer(0);
}
str = str.padStart(byteLen * 2, '0')
// 发送数据低字节在前
let tmpByte = byteConversion();
str = tmpByte.toString(16);
// ArrayBuffer
var buffer = new ArrayBuffer(byteLen);
let dataView = new DataView(buffer)
let idx = 0;
for (var i = 0, len = str.length; i < len; i += 2) {
let subStr = str.substr(i, 2);
let code = parseInt(subStr, 16)
dataView.setUint8(idx, code)
idx ++
}
return buffer;
}
字节转换
- 假设:时间为
687506785
,转16进制后:28fa8561
低字节
在前:即6185fa28
,10进制为:1636170280
const byteConversion = (val) => {
val = '0x' + val;
var res = 0;
for(var i = 0; i < 4; i++){
res = res * 256 + ((val >> (i*8)) & 0xff);
}
return res;
}
验证发送UTC时间
2000-01-01 00:00:00
这个时间为基准 【946656000】
let currentUTCTime = 687425644;
currentUTCTime + 基准时间 = 当前时间【再+8小时】 // 1634110444