2025-06-06 15:17:30 +08:00

81 lines
2.0 KiB
JavaScript

// bluetoothService.js
const COMMAND = {
START_FREE_JUMP_ROPE: 0x03,
PAUSE: 0x04,
RESUME: 0x05,
STOP: 0x06,
GET_COUNT: 'Get CT',
START_COUNT: 'Start Count',
STOP_COUNT: 'Stop Count',
CLEAN_COUNT: 'Clean Count'
};
const DEVICE_TYPE = {
YD_O1: 'YD-O1',
YD_Jump: 'YD_Jump'
};
function startFreeJumpRope(deviceId, serviceId, type) {
const characteristic = wx.getStorageSync('writeCharacteristic');
if (!characteristic) {
console.error('没有可写的特征值');
return;
}
const commandData = new ArrayBuffer(4);
const dataView = new DataView(commandData);
dataView.setUint8(0, COMMAND.START_FREE_JUMP_ROPE);
dataView.setUint8(1, type);
dataView.setUint8(2, 0x00);
dataView.setUint8(3, 0x00);
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristic,
value: commandData,
success: () => {
console.log("自由跳绳已启动!");
},
fail: (error) => {
console.error("启动自由跳绳失败", error);
}
});
}
function sendCommandJump(deviceId, serviceId, codeStr) {
const characteristic = wx.getStorageSync('writeCharacteristic');
if (!characteristic) {
console.error('没有可写的特征值');
return;
}
const startCommand = `$${codeStr}!`;
const commandData = stringToArrayBuffer(startCommand);
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: characteristic,
value: commandData,
success: () => {
console.log(codeStr, "命令发送成功");
},
fail: (error) => {
console.error(codeStr, "命令发送失败", error);
}
});
}
function stringToArrayBuffer(str) {
const buffer = new ArrayBuffer(str.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < str.length; i++) {
view[i] = str.charCodeAt(i) & 0xFF;
}
return buffer;
}
module.exports = {
COMMAND,
DEVICE_TYPE,
startFreeJumpRope,
sendCommandJump
};