kitchendDevice/tools/bluetooth.js

371 lines
9.0 KiB
JavaScript
Raw Normal View History

2025-11-26 17:32:18 +08:00
import $store from '@/store'
2026-01-14 10:23:22 +08:00
import $model from '@/tools/model.js'
import $tools from '@/tools/tools.js'
2025-12-22 09:34:09 +08:00
import messages from '@/language/index.js'
2025-11-26 17:32:18 +08:00
let searchTimer = null
let devicesList = []
// 初始化蓝牙
2025-12-22 09:34:09 +08:00
2025-11-26 17:32:18 +08:00
function openBluetoothAdapter() {
2026-02-10 15:59:50 +08:00
devicesList = []
2025-12-22 09:34:09 +08:00
let Language = $store.state.setLocale
let $t = messages[Language]
2026-02-10 15:59:50 +08:00
clearTimeout(searchTimer);
2025-11-26 17:32:18 +08:00
uni.openBluetoothAdapter({
success: e => {
$store.commit("changeBluetoothValue", {
2025-12-22 09:34:09 +08:00
bleTipsText: $t.SearchBluetooth,
2025-11-26 17:32:18 +08:00
isConnectStatus: 0
})
startBluetoothDeviceDiscovery()
},
fail: e => {
$store.commit("changeBluetoothValue", {
2025-12-22 09:34:09 +08:00
bleTipsText: $t.ConnectionTimeout,
2025-11-26 17:32:18 +08:00
isConnectStatus: 1
})
}
});
}
// 开始搜寻附近的蓝牙外围设备
function startBluetoothDeviceDiscovery() {
2025-12-22 09:34:09 +08:00
let Language = $store.state.setLocale
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
2025-12-24 16:44:43 +08:00
interval: 200,
2025-11-26 17:32:18 +08:00
success: res => {
onBluetoothDeviceFound();
searchTimer = setTimeout(() => {
uni.stopBluetoothDevicesDiscovery()
if (!devicesList.length) {
clearTimeout(searchTimer);
$store.commit("changeBluetoothValue", {
2025-12-22 09:34:09 +08:00
bleTipsText: $t.ConnectionTimeout,
2025-11-26 17:32:18 +08:00
isConnectStatus: 1
});
}
}, 30000); // 30秒超时
},
fail: res => {
$store.commit("changeBluetoothValue", {
2025-12-22 09:34:09 +08:00
bleTipsText: $t.ConnectionTimeout,
2025-11-26 17:32:18 +08:00
isConnectStatus: 1
})
}
});
}
/**
* 发现外围设备
*/
function onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound(res => {
res.devices.forEach(device => {
2025-12-24 16:44:43 +08:00
console.log("name", device.name)
2026-02-10 15:59:50 +08:00
if (!device.name && !device.localName) {
return
}
2026-01-14 10:23:22 +08:00
if (device.name.toLowerCase().indexOf('pc-c06pro') != -1 ||
device.name.toLowerCase().indexOf('pc-c02pro') != -1 ||
device.name.toLowerCase().indexOf('pc-c09pro') != -1 ||
(device.localName && device.localName.toLowerCase().indexOf('pc-c06pro') != -1) ||
(device.localName && device.localName.toLowerCase().indexOf('pc-c02pro') != -1) ||
(device.localName && device.localName.toLowerCase().indexOf('pc-c09pro') != -1)) {
2025-11-26 17:32:18 +08:00
clearTimeout(searchTimer);
2026-01-14 10:23:22 +08:00
const bytes = new Uint8Array(device.advertisData);
const macBytes = bytes.slice(6, 12);
device.macAddr = $tools.ab2hex(macBytes, ':').toUpperCase()
2025-11-26 17:32:18 +08:00
stopBluetoothDevicesDiscovery()
2026-01-14 10:23:22 +08:00
Bluetoothfilter(device)
2025-11-26 17:32:18 +08:00
return
}
})
});
}
// 过滤蓝牙
2026-01-14 10:23:22 +08:00
function Bluetoothfilter(device) {
2025-11-26 17:32:18 +08:00
const foundDevices = devicesList
2026-01-14 10:23:22 +08:00
const idx = inArray(foundDevices, "deviceId", device.deviceId)
2025-11-26 17:32:18 +08:00
if (idx === -1) {
2026-01-14 10:23:22 +08:00
devicesList.push(device);
handleDevType(device)
2025-11-26 17:32:18 +08:00
}
}
2026-01-14 10:23:22 +08:00
// 排查设备
function handleDevType(device) {
2026-02-10 15:29:22 +08:00
let Language = $store.state.setLocale
2026-01-14 10:23:22 +08:00
let $t = messages[Language]
$model.getCheckDevice({
mac: device.macAddr,
}).then(res => {
console.log("排查设备:", device, res)
if (res.code == 0) {
connectDevice(device.deviceId)
} else {
devicesList = []
2026-01-19 11:26:48 +08:00
$tools.msg(res.msg)
2026-01-14 10:23:22 +08:00
$store.commit("changeBluetoothValue", {
type: 1,
isConnectStatus: 1,
bleTipsText: $t.ConnectionTimeout,
})
}
})
}
2025-11-26 17:32:18 +08:00
//连接设备
function connectDevice(device_id) {
2026-02-10 15:29:22 +08:00
let Language = $store.state.setLocale
2026-01-14 10:23:22 +08:00
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
uni.createBLEConnection({
deviceId: device_id,
success: res => {
setTimeout(function() {
getBLEDeviceServices(device_id)
}, 200)
},
fail: res => {
2026-01-14 10:23:22 +08:00
$store.commit("changeBluetoothValue", {
type: 1,
isConnectStatus: 1,
bleTipsText: $t.ConnectionTimeout,
})
2025-11-26 17:32:18 +08:00
console.log("连接失败,点击重新连接", res);
}
});
}
/**
* 获取设备的UUID
*/
function getBLEDeviceServices(device_id) {
let serviceList = [];
2026-02-10 15:29:22 +08:00
let Language = $store.state.setLocale
2026-01-14 10:23:22 +08:00
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
uni.getBLEDeviceServices({
deviceId: device_id,
success: res => {
console.log("获取设备的UUID成功", res)
serviceList = res.services;
for (let i = 0; i < serviceList.length; i++) {
let service = serviceList[i];
if (service.uuid.indexOf("FFF0") != -1) {
2025-12-29 16:54:56 +08:00
stopBluetoothDevicesDiscovery()
2025-11-26 17:32:18 +08:00
getBLEDeviceCharacteristics(device_id, service.uuid);
break;
}
}
},
fail: res => {
2026-01-14 10:23:22 +08:00
$store.commit("changeBluetoothValue", {
type: 1,
isConnectStatus: 1,
bleTipsText: $t.ConnectionTimeout,
})
2025-11-26 17:32:18 +08:00
console.log('获取设备的UUID失败:', res)
}
});
}
/**
* 获取指定服务的特征值
*/
function getBLEDeviceCharacteristics(deviceId, serviceId) {
2026-02-10 15:29:22 +08:00
let Language = $store.state.setLocale
2026-01-14 10:23:22 +08:00
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
let characteristicsList = [];
uni.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: serviceId,
success: res => {
let write, notify
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i];
if (item.uuid.indexOf('0000FFF2') != -1) {
write = item.uuid
} else if (item.uuid.indexOf('0000FFF1') != -1) {
notify = item.uuid
}
}
2025-12-03 15:34:39 +08:00
getBLECharacteristicValueChange(deviceId, serviceId, notify, write)
2025-11-26 17:32:18 +08:00
},
fail: res => {
2026-01-14 10:23:22 +08:00
$store.commit("changeBluetoothValue", {
type: 1,
isConnectStatus: 1,
bleTipsText: $t.ConnectionTimeout,
})
2025-11-26 17:32:18 +08:00
console.log('获取特征值失败:', JSON.stringify(res))
}
})
}
2025-12-03 15:34:39 +08:00
function getBLECharacteristicValueChange(deviceId, serviceId, notify, write) {
2025-11-26 17:32:18 +08:00
let that = this
2025-12-22 09:34:09 +08:00
let Language = $store.state.setLocale
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
uni.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: notify,
state: true,
success: () => {
2025-11-29 10:02:33 +08:00
$store.commit('changeBluetoothValue', {
deviceId: deviceId,
serviceId: serviceId,
notify: notify,
write: write,
unit: "g",
2026-01-14 10:23:22 +08:00
type: 1,
2025-11-29 10:02:33 +08:00
countWeight: "",
2025-12-22 09:34:09 +08:00
bleTipsText: $t.Measuring,
2026-01-14 10:23:22 +08:00
isConnectStatus: 2
2025-11-26 17:32:18 +08:00
})
2025-12-22 09:34:09 +08:00
const units = ['kg', 'g', 'st:lb', 'lb', 'g', 'ml', 'Waterml',
2025-12-03 15:34:39 +08:00
'milkml', 'oz', 'floz', 'lboz'
]
2025-11-26 17:32:18 +08:00
uni.onBLECharacteristicValueChange(function(res) {
const value = res.value
const dataView = new DataView(value)
const header = dataView.getUint8(0)
// MCU主动上报数据
if (header === 0xC7) {
const cmd = dataView.getUint8(2)
switch (cmd) {
case 0x02:
const statusByte = dataView.getUint8(4)
const isNegative = !!(statusByte & 0x80) // 最高位表示正负
const statusType = statusByte & 0x0F // 状态类型
// 组合24位重量值 (大端序)
const weightValue =
(dataView.getUint8(5) << 16) |
(dataView.getUint8(6) << 8) |
dataView.getUint8(7)
// 精度和单位
const unitByte = dataView.getUint8(8)
const precision = (unitByte & 0xF0) >> 4 // 高4位精度
const unitIndex = unitByte & 0x0F // 低4位单位
// 计算实际重量
let finalWeight = weightValue / Math.pow(10, precision)
if (isNegative) finalWeight = -finalWeight
$store.commit("changeBluetoothValue", {
countWeight: finalWeight,
2025-11-29 10:02:33 +08:00
unit: units[unitIndex],
2026-01-14 10:23:22 +08:00
type: statusType
2025-11-26 17:32:18 +08:00
})
break
case 0x03:
break
}
}
})
},
fail: res => {
console.log('获取特征值失败:', JSON.stringify(res))
}
})
}
function inArray(arr, key, val) {
if (!arr || !arr.length || typeof arr != 'object' || !Array.isArray(arr)) {
return -1
}
for (let i = 0; i < arr.length; i++) {
if (!key) {
if (arr[i] == val) {
return i
}
} else if (arr[i][key] === val) {
return i
}
}
return -1;
}
function ab2hex(buffer, split) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join(split);
}
/**
* 断开蓝牙模块
*/
function closeBluetoothAdapter() {
uni.closeBluetoothAdapter({
success: res => {
$store.commit("changeBluetoothValue", {
deviceId: "",
serviceId: "",
notify: "",
write: "",
unit: "g",
2025-11-27 15:04:25 +08:00
countWeight: '',
2026-01-14 10:23:22 +08:00
type: 1,
2025-11-26 17:32:18 +08:00
})
console.log('蓝牙模块关闭成功');
}
})
}
/**
* 断开蓝牙连接
*/
function closeBLEConnection(deviceId) {
uni.closeBLEConnection({
deviceId: deviceId,
success: res => {
console.log('断开蓝牙连接成功');
}
});
}
// 监听蓝牙连接状态
function onBLEConnectionStateChange() {
2025-12-22 09:34:09 +08:00
let Language = $store.state.setLocale
let $t = messages[Language]
2025-11-26 17:32:18 +08:00
uni.onBLEConnectionStateChange(function(res) {
console.log("监听蓝牙连接状态", res.connected)
if (!res.connected) {
$store.commit("changeBluetoothValue", {
2025-12-22 09:34:09 +08:00
bleTipsText: $t.ConnectionTimeout,
2026-01-14 10:23:22 +08:00
isConnectStatus: 1,
type: 1,
2025-11-26 17:32:18 +08:00
})
closeBLEConnection()
closeBluetoothAdapter()
}
$store.commit("changeBluetooth", res.connected);
})
}
/**
* 停止搜索蓝牙设备
*/
function stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery({
success: e => {
console.log("停止搜索蓝牙设备", e)
},
});
}
export default {
ab2hex,
inArray,
openBluetoothAdapter,
startBluetoothDeviceDiscovery,
onBluetoothDeviceFound,
Bluetoothfilter,
connectDevice,
getBLEDeviceServices,
getBLEDeviceCharacteristics,
closeBluetoothAdapter,
closeBLEConnection,
2025-12-03 15:34:39 +08:00
getBLECharacteristicValueChange,
2025-11-26 17:32:18 +08:00
onBLEConnectionStateChange,
stopBluetoothDevicesDiscovery
}