2026-07-01 15:10:17 +08:00

113 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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',
GET_BATTERY: 'Get Batt'
};
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;
}
// 获取设备电量,根据设备型号发送不同协议的命令
function getBattery(deviceId, serviceId, deviceName) {
const characteristic = wx.getStorageSync('writeCharacteristic');
if (!characteristic) {
console.error('没有可写的特征值');
return;
}
if (deviceName === DEVICE_TYPE.YD_O1) {
// YD-O1:二进制协议获取电量
const commandData = new ArrayBuffer(4);
const dataView = new DataView(commandData);
dataView.setUint8(0, 0x07); // 获取电量命令字节
dataView.setUint8(1, 0x00);
dataView.setUint8(2, 0x00);
dataView.setUint8(3, 0x00);
wx.writeBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: characteristic,
value: commandData,
success: () => console.log('YD-O1 获取电量命令已发送'),
fail: err => console.error('YD-O1 获取电量命令失败', err)
});
} else {
// YD_Jump / YD-Jump:字符串协议获取电量
sendCommandJump(deviceId, serviceId, COMMAND.GET_BATTERY);
}
}
module.exports = {
COMMAND,
DEVICE_TYPE,
startFreeJumpRope,
sendCommandJump,
getBattery
};