feat(称重): 优化蓝牙电子秤连接稳定性并支持 HC-06/08 协议
- 支持 HC-06/HC-08 类 BLE 电子秤协议:帧头 '=' + 数字,整数部分按固件逆序解析,单位按 g、视为稳定读数;兼容旧秤 ST/GS/WT/NET/OK 标志,不误反转 - 发现并订阅全部可订阅特征(不再只看首个),订阅前先关闭再开启通知强制重写 CCCD,规避安卓 GATT 缓存导致“已连接但收不到数据” - 服务发现增加重试(3 次),规避同名设备切换后 getBLEDeviceServices 返回空/旧缓存 - 新增“已连接但无数据”看门狗:3 秒未收到数据自动强制重连(最多 2 次) - 扫描优先连接“正在广播”的匹配设备,解决同名多设备(新旧秤都叫 HC-06)连到旧设备的问题 - 连接互斥锁增加超时兜底,防止个别机型连接 API 卡死导致锁永不释放 - 断开后延迟等待系统完成 GATT 断开,切换设备后清空旧秤残留读数 - 称重页新增“原始数据”展示,便于排查读数问题 - 版本号升级 1.0.127 -> 1.0.128
This commit is contained in:
parent
e21e9d7464
commit
7090396cf0
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "wms-pda",
|
||||
"version": "1.0.127",
|
||||
"version": "1.0.128",
|
||||
"private": true,
|
||||
"description": "天豹云仓 WMS_PDA(uni-app Vue2 + @vue/cli 4.5)",
|
||||
"scripts": {
|
||||
|
||||
@ -86,6 +86,27 @@ function parseWeight(text) {
|
||||
const clean = String(text).replace(/[\x00-\x1f\x7f]/g, '').trim();
|
||||
if (!clean) return { value: null, unit: '', stable: false, text: '' };
|
||||
|
||||
// HC-06/HC-08 类 BLE 电子秤协议:帧头 '=' + 数字,例如 "=603.000"。
|
||||
// 该协议无 ST/GS 稳定标志、无 kg/g 单位标志;且整数字段被固件按逆序发送
|
||||
// (实测:秤显示屏 306g,收到文本 "=603.000"),故反转整数部分,单位按 g,视为稳定读数。
|
||||
// 兼容旧秤:旧秤帧含 ST/GS/WT/NET/OK/kg/g 等标志,不会命中下方纯 '=' + 数字的匹配,
|
||||
// 再叠加 hasLegacyMarker 兜底,确保旧协议走原有解析、不被误反转。
|
||||
const eqMatch = clean.match(/^=([+-]?)(\d+)(?:\.(\d+))?/);
|
||||
const hasLegacyMarker = /(?:ST|GS|WT|NET|OK|KG|G\b)/i.test(clean);
|
||||
if (eqMatch && !hasLegacyMarker) {
|
||||
const sign = eqMatch[1] || '';
|
||||
const intPart = eqMatch[2] || '';
|
||||
const decPart = eqMatch[3] || '';
|
||||
const reversedInt = intPart.split('').reverse().join('');
|
||||
const rawValue = parseFloat(sign + reversedInt + (decPart ? '.' + decPart : ''));
|
||||
return {
|
||||
value: isNaN(rawValue) ? null : rawValue,
|
||||
unit: 'g',
|
||||
stable: true,
|
||||
text: clean
|
||||
};
|
||||
}
|
||||
|
||||
// 稳定标志:ST/GS/OK 视为稳定,US 不稳定,OL 超载
|
||||
const stable = /(ST|GS|OK)/i.test(clean) && !/(US|OL|ER)/i.test(clean);
|
||||
|
||||
@ -116,8 +137,18 @@ let reconnectTimer = null;
|
||||
let disconnectDebounceTimer = null;
|
||||
let scanStopTimer = null;
|
||||
let manualDisconnect = false;
|
||||
// 连接互斥锁:避免手动连接与自动重连并发执行
|
||||
// 连接互斥锁:避免手动连接与自动重连并发执行;带超时兜底,防止个别机型连接 API 卡死导致锁永不释放
|
||||
let connectLock = false;
|
||||
let connectLockAt = 0;
|
||||
const CONNECT_LOCK_TIMEOUT_MS = 20000;
|
||||
// 最近一次手动断开时间:显式断开后紧接着连新设备时,需等待系统完成上次 GATT 断开
|
||||
let lastDisconnectAt = 0;
|
||||
// 本轮扫描中实时广播发现的设备 ID(区别于已配对/历史设备),用于同名设备时优先连“正在广播”的那个
|
||||
let discoveredDeviceIds = new Set();
|
||||
// 连接后未收到数据的看门狗:规避安卓 BLE 缓存导致“已连接但收不到重量”
|
||||
let dataWatchdogTimer = null;
|
||||
let lastConnectedAt = 0;
|
||||
let watchdogRetries = 0;
|
||||
|
||||
const SCAN_TIMEOUT_MS = 12000;
|
||||
|
||||
@ -142,6 +173,31 @@ function clearScanStopTimer() {
|
||||
}
|
||||
}
|
||||
|
||||
function clearDataWatchdog() {
|
||||
if (dataWatchdogTimer) {
|
||||
clearTimeout(dataWatchdogTimer);
|
||||
dataWatchdogTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 连接成功后启动看门狗:若 3 秒内未收到任何数据,说明通知订阅未生效(安卓 GATT 缓存等),强制重连一次
|
||||
function startDataWatchdog(commit, state, dispatch) {
|
||||
clearDataWatchdog();
|
||||
lastConnectedAt = Date.now();
|
||||
dataWatchdogTimer = setTimeout(() => {
|
||||
if (!state.currentDevice || state.connectionStatus !== 'connected') return;
|
||||
const gotData = state.lastDataTime && state.lastDataTime >= lastConnectedAt;
|
||||
if (gotData) return;
|
||||
if (watchdogRetries >= 2) {
|
||||
commit('ADD_LOG', { type: 'warning', message: '多次重连后仍未收到数据,请手动断开后重连' });
|
||||
return;
|
||||
}
|
||||
watchdogRetries++;
|
||||
commit('ADD_LOG', { type: 'warning', message: `连接后未收到数据,强制重连(${watchdogRetries}/2)...` });
|
||||
dispatch('forceReconnect').catch(() => {});
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
// ---------------- 模块定义 ----------------
|
||||
|
||||
const state = () => ({
|
||||
@ -243,6 +299,13 @@ const mutations = {
|
||||
state.rawText = '';
|
||||
state.rawHex = '';
|
||||
},
|
||||
RESET_WEIGHT(state) {
|
||||
state.weight = null;
|
||||
state.weightUnit = '';
|
||||
state.stable = false;
|
||||
state.rawText = '';
|
||||
state.rawHex = '';
|
||||
},
|
||||
SET_ERROR(state, error) {
|
||||
state.lastError = error;
|
||||
if (error) {
|
||||
@ -286,6 +349,9 @@ function parseIncoming(commit, state, res) {
|
||||
const text = bytesToUtf8(bytes);
|
||||
const hex = bytesToHex(bytes);
|
||||
commit('RAW_DATA', { text, hex, time: Date.now() });
|
||||
// 收到任意数据即说明通知订阅生效,清除“已连接但无数据”看门狗
|
||||
clearDataWatchdog();
|
||||
watchdogRetries = 0;
|
||||
|
||||
const parsed = parseWeight(text);
|
||||
if (parsed.value !== null) {
|
||||
@ -293,12 +359,26 @@ function parseIncoming(commit, state, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// 发现可订阅(notify/indicate)的重量特征值,返回 { service, characteristic, error }
|
||||
async function discoverNotifyCharacteristic(deviceId) {
|
||||
// 简写 128 位标准 BLE UUID,便于日志展示
|
||||
// 用 indexOf/lastIndexOf 实现,避免 startsWith/endsWith,兼容老机型 WebView
|
||||
function shortUuid(uuid) {
|
||||
if (!uuid) return '';
|
||||
const u = String(uuid).toLowerCase();
|
||||
const suffix = '-0000-1000-8000-00805f9b34fb';
|
||||
if (u.indexOf('0000') === 0 && u.lastIndexOf(suffix) === u.length - suffix.length) {
|
||||
return '0x' + u.slice(4, 8);
|
||||
}
|
||||
return uuid;
|
||||
}
|
||||
|
||||
// 发现设备全部可订阅(notify/indicate)特征,返回 { characteristics, error }。
|
||||
// 注意:不只看第一个 notify 特征——部分电子秤会暴露多个特征(电量/状态等),重量数据可能不在首个特征上。
|
||||
async function discoverNotifyCharacteristics(deviceId, commit) {
|
||||
const [srvErr, srvRes] = await uni.getBLEDeviceServices({ deviceId });
|
||||
if (srvErr || !srvRes || !srvRes.services || !srvRes.services.length) {
|
||||
return { service: null, characteristic: null, error: new Error('未发现设备服务') };
|
||||
return { characteristics: [], error: new Error('未发现设备服务') };
|
||||
}
|
||||
const characteristics = [];
|
||||
for (const service of srvRes.services) {
|
||||
const [chErr, chRes] = await uni.getBLEDeviceCharacteristics({
|
||||
deviceId,
|
||||
@ -306,12 +386,83 @@ async function discoverNotifyCharacteristic(deviceId) {
|
||||
});
|
||||
if (chErr || !chRes || !chRes.characteristics) continue;
|
||||
for (const ch of chRes.characteristics) {
|
||||
if (ch.properties && (ch.properties.notify || ch.properties.indicate)) {
|
||||
return { service, characteristic: ch, error: null };
|
||||
const props = ch.properties || {};
|
||||
const enabled = Object.keys(props).filter(k => props[k]);
|
||||
if (commit) {
|
||||
commit('ADD_LOG', {
|
||||
type: 'info',
|
||||
message: `特征 ${shortUuid(ch.uuid)} [${enabled.join(',') || '无'}]`
|
||||
});
|
||||
}
|
||||
if (props.notify || props.indicate) {
|
||||
characteristics.push({ serviceId: service.uuid, characteristicId: ch.uuid });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { service: null, characteristic: null, error: new Error('未找到可订阅的重量数据特征') };
|
||||
return { characteristics, error: null };
|
||||
}
|
||||
|
||||
// 服务发现重试:部分安卓机型在切换同名设备后 getBLEDeviceServices 会短暂返回空/旧缓存,
|
||||
// 稍等重试可拿到正确服务列表(正是“换到同名新秤读不到数据、先连其他设备再切回来又正常”的根因)。
|
||||
async function discoverNotifyCharacteristicsWithRetry(deviceId, commit, retries = 3) {
|
||||
let lastError = null;
|
||||
for (let i = 0; i < retries; i++) {
|
||||
const res = await discoverNotifyCharacteristics(deviceId, commit);
|
||||
if (!res.error && res.characteristics.length) return res;
|
||||
lastError = res.error;
|
||||
if (i < retries - 1) {
|
||||
await delay(500);
|
||||
}
|
||||
}
|
||||
return { characteristics: [], error: lastError || new Error('未找到可订阅的重量数据特征') };
|
||||
}
|
||||
|
||||
// 订阅全部可订阅特征,返回成功订阅数量
|
||||
async function subscribeWeightNotifications(deviceId, characteristics, commit) {
|
||||
let subscribed = 0;
|
||||
for (const ch of characteristics) {
|
||||
// 先关闭再开启通知,强制重写 CCCD(客户端特征配置描述符),
|
||||
// 规避安卓缓存跳过 CCCD 写入导致的“已连接但收不到数据”
|
||||
const [offErr] = await uni.notifyBLECharacteristicValueChange({
|
||||
deviceId,
|
||||
serviceId: ch.serviceId,
|
||||
characteristicId: ch.characteristicId,
|
||||
state: false
|
||||
});
|
||||
if (commit) {
|
||||
if (offErr) {
|
||||
commit('ADD_LOG', {
|
||||
type: 'info',
|
||||
message: `关闭特征通知: ${shortUuid(ch.characteristicId)} (${offErr.message || offErr.errMsg || 'ok'})`
|
||||
});
|
||||
}
|
||||
}
|
||||
// 关闭与开启之间留间隔,避免底层把 CCCD 写入合并/乱序
|
||||
await delay(300);
|
||||
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
|
||||
deviceId,
|
||||
serviceId: ch.serviceId,
|
||||
characteristicId: ch.characteristicId,
|
||||
state: true
|
||||
});
|
||||
if (notifyErr) {
|
||||
if (commit) {
|
||||
commit('ADD_LOG', {
|
||||
type: 'warning',
|
||||
message: `订阅特征 ${shortUuid(ch.characteristicId)} 失败: ${notifyErr.message || notifyErr.errMsg || '未知错误'}`
|
||||
});
|
||||
}
|
||||
} else {
|
||||
subscribed++;
|
||||
if (commit) {
|
||||
commit('ADD_LOG', {
|
||||
type: 'success',
|
||||
message: `已订阅特征 ${shortUuid(ch.characteristicId)}`
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return subscribed;
|
||||
}
|
||||
|
||||
const actions = {
|
||||
@ -329,7 +480,10 @@ const actions = {
|
||||
|
||||
uni.onBluetoothDeviceFound(function(res) {
|
||||
const list = (res && res.devices) || [];
|
||||
list.forEach(d => commit('ADD_DEVICE', d));
|
||||
list.forEach(d => {
|
||||
if (d && d.deviceId) discoveredDeviceIds.add(d.deviceId);
|
||||
commit('ADD_DEVICE', d);
|
||||
});
|
||||
});
|
||||
|
||||
uni.onBLEConnectionStateChange(function(res) {
|
||||
@ -412,6 +566,7 @@ const actions = {
|
||||
*/
|
||||
async startScan({ commit, dispatch }) {
|
||||
commit('RESET_DEVICES');
|
||||
discoveredDeviceIds = new Set();
|
||||
// 已配对/已连接设备不会出现在 discovery 结果中,先并入列表;
|
||||
// 并加载历史连接过的设备,避免切换设备后扫描找不到之前连接过的设备名称
|
||||
const bonded = await dispatch('getBondedDevices');
|
||||
@ -469,27 +624,31 @@ const actions = {
|
||||
|
||||
await dispatch('initialize');
|
||||
|
||||
// 1. 先从已发现/已配对设备中查找
|
||||
const bonded = await dispatch('getBondedDevices');
|
||||
const bondedMatch = bonded.find(d => String(d.name || '').trim() === targetName);
|
||||
if (bondedMatch) {
|
||||
return dispatch('connectDevice', bondedMatch);
|
||||
}
|
||||
|
||||
// 2. 开启扫描,等待匹配设备出现
|
||||
// 先扫描,优先连接“当前正在广播”的匹配设备:同名多设备(如新旧秤都叫 HC-06)时,
|
||||
// 已配对列表里可能是旧设备,而新秤此刻正在广播,应优先连广播中的新秤。
|
||||
commit('SET_CONNECTION_STATUS', 'scanning');
|
||||
await dispatch('startScan');
|
||||
|
||||
const timeout = SCAN_TIMEOUT_MS;
|
||||
const discoverTimeout = 6000;
|
||||
const startAt = Date.now();
|
||||
try {
|
||||
while (Date.now() - startAt < timeout) {
|
||||
const match = state.devices.find(d => String(d.name || '').trim() === targetName);
|
||||
while (Date.now() - startAt < discoverTimeout) {
|
||||
const match = state.devices.find(d =>
|
||||
String(d.name || '').trim() === targetName && discoveredDeviceIds.has(d.deviceId)
|
||||
);
|
||||
if (match) {
|
||||
return dispatch('connectDevice', match);
|
||||
}
|
||||
await delay(400);
|
||||
}
|
||||
|
||||
// 6 秒内未发现广播设备,回退到已配对设备(可能是已配对但未广播的设备)
|
||||
const bonded = await dispatch('getBondedDevices');
|
||||
const bondedMatch = bonded.find(d => String(d.name || '').trim() === targetName);
|
||||
if (bondedMatch) {
|
||||
return dispatch('connectDevice', bondedMatch);
|
||||
}
|
||||
|
||||
throw new Error(`未找到名为「${targetName}」的蓝牙设备,请确认电子秤已开机并处于可被发现状态`);
|
||||
} finally {
|
||||
await dispatch('stopScan');
|
||||
@ -510,11 +669,12 @@ const actions = {
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectLock) {
|
||||
if (connectLock && Date.now() - connectLockAt < CONNECT_LOCK_TIMEOUT_MS) {
|
||||
commit('ADD_LOG', { type: 'info', message: '正在连接设备,跳过本次自动重连' });
|
||||
return;
|
||||
}
|
||||
connectLock = true;
|
||||
connectLockAt = Date.now();
|
||||
|
||||
commit('SET_RECONNECTING', true);
|
||||
commit('SET_RECONNECT_MESSAGE', '正在恢复蓝牙连接...');
|
||||
@ -538,31 +698,26 @@ const actions = {
|
||||
commit('SET_RECONNECT_ATTEMPTS', 0);
|
||||
dispatch('stopScan');
|
||||
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,继续读取重量: ${state.currentDevice.name || state.currentDevice.id}` });
|
||||
startDataWatchdog(commit, state, dispatch);
|
||||
return true;
|
||||
}
|
||||
throw connErr;
|
||||
}
|
||||
|
||||
// 连接建立后部分安卓机型服务可用存在延时,短暂等待再重新发现服务
|
||||
await delay(400);
|
||||
await delay(800);
|
||||
|
||||
// 重连后重新发现服务/特征,避免直接复用旧特征实例导致 notify 失败
|
||||
const discovered = await discoverNotifyCharacteristic(state.currentDevice.id);
|
||||
const discovered = await discoverNotifyCharacteristicsWithRetry(state.currentDevice.id, commit);
|
||||
if (discovered.error) throw discovered.error;
|
||||
|
||||
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
|
||||
deviceId: state.currentDevice.id,
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid,
|
||||
state: true
|
||||
});
|
||||
if (notifyErr) throw notifyErr;
|
||||
if (!discovered.characteristics.length) throw new Error('未找到可订阅的重量数据特征');
|
||||
const subscribed = await subscribeWeightNotifications(state.currentDevice.id, discovered.characteristics, commit);
|
||||
if (!subscribed) throw new Error('订阅重量数据特征失败');
|
||||
|
||||
commit('SET_CURRENT_DEVICE', {
|
||||
id: state.currentDevice.id,
|
||||
name: state.currentDevice.name || '未知设备',
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid
|
||||
characteristics: discovered.characteristics
|
||||
});
|
||||
|
||||
clearReconnectTimer();
|
||||
@ -572,6 +727,7 @@ const actions = {
|
||||
commit('SET_CONNECTION_STATUS', 'connected');
|
||||
dispatch('stopScan');
|
||||
commit('ADD_LOG', { type: 'success', message: `已恢复连接: ${state.currentDevice.name || state.currentDevice.id}` });
|
||||
startDataWatchdog(commit, state, dispatch);
|
||||
return true;
|
||||
} catch (e) {
|
||||
commit('SET_RECONNECTING', false);
|
||||
@ -588,6 +744,7 @@ const actions = {
|
||||
throw e;
|
||||
} finally {
|
||||
connectLock = false;
|
||||
connectLockAt = 0;
|
||||
}
|
||||
},
|
||||
|
||||
@ -597,16 +754,25 @@ const actions = {
|
||||
commit('ADD_LOG', { type: 'info', message: `设备已连接,继续读取重量: ${device.name || device.deviceId}` });
|
||||
return true;
|
||||
}
|
||||
if (connectLock) {
|
||||
if (connectLock && Date.now() - connectLockAt < CONNECT_LOCK_TIMEOUT_MS) {
|
||||
commit('ADD_LOG', { type: 'info', message: '正在连接其他设备,请稍候' });
|
||||
throw new Error('正在连接中,请稍候');
|
||||
}
|
||||
connectLock = true;
|
||||
connectLockAt = Date.now();
|
||||
|
||||
clearReconnectTimer();
|
||||
clearDisconnectDebounceTimer();
|
||||
clearDataWatchdog();
|
||||
watchdogRetries = 0;
|
||||
manualDisconnect = false;
|
||||
|
||||
// 显式断开后紧接着连新设备:等待系统完成上次 GATT 断开,避免服务发现返回空/旧缓存
|
||||
const sinceDisconnect = Date.now() - lastDisconnectAt;
|
||||
if (sinceDisconnect < 600) {
|
||||
await delay(600 - sinceDisconnect);
|
||||
}
|
||||
|
||||
// 单连接:切换设备前先显式断开旧设备,避免旧设备残留连接;
|
||||
// 断开期间置 manualDisconnect=true,阻止全局监听对旧设备触发自动重连
|
||||
const prev = state.currentDevice;
|
||||
@ -618,6 +784,10 @@ const actions = {
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
// 等待系统完成旧设备 GATT 断开,避免同名设备切换时连接已建立但服务发现返回空/旧缓存
|
||||
await delay(1200);
|
||||
// 切换设备后清空旧秤残留读数,避免称重页展示旧秤重量
|
||||
commit('RESET_WEIGHT');
|
||||
commit('ADD_LOG', { type: 'info', message: `已断开旧设备: ${prev.name || prevId}` });
|
||||
}
|
||||
|
||||
@ -634,23 +804,17 @@ const actions = {
|
||||
// 避免复用旧特征实例导致收不到重量数据
|
||||
if (connErr && /already connect|已连接|already connected/i.test(String(connErr.message || connErr.errMsg || ''))) {
|
||||
// 连接已建立,短暂等待服务可用后重新发现服务/特征
|
||||
await delay(400);
|
||||
const discovered = await discoverNotifyCharacteristic(device.deviceId);
|
||||
await delay(800);
|
||||
const discovered = await discoverNotifyCharacteristicsWithRetry(device.deviceId, commit);
|
||||
if (discovered.error) throw discovered.error;
|
||||
|
||||
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
|
||||
deviceId: device.deviceId,
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid,
|
||||
state: true
|
||||
});
|
||||
if (notifyErr) throw notifyErr;
|
||||
if (!discovered.characteristics.length) throw new Error('未找到可订阅的重量数据特征');
|
||||
const subscribed = await subscribeWeightNotifications(device.deviceId, discovered.characteristics, commit);
|
||||
if (!subscribed) throw new Error('订阅重量数据特征失败');
|
||||
|
||||
commit('SET_CURRENT_DEVICE', {
|
||||
id: device.deviceId,
|
||||
name: device.name || '未知设备',
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid
|
||||
characteristics: discovered.characteristics
|
||||
});
|
||||
saveHistoryDevice({ deviceId: device.deviceId, name: device.name || '' });
|
||||
manualDisconnect = false;
|
||||
@ -660,26 +824,23 @@ const actions = {
|
||||
commit('SET_RECONNECT_ATTEMPTS', 0);
|
||||
dispatch('stopScan');
|
||||
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,已重新订阅重量数据: ${device.name || device.deviceId}` });
|
||||
startDataWatchdog(commit, state, dispatch);
|
||||
return true;
|
||||
}
|
||||
if (connErr) throw connErr;
|
||||
|
||||
const discovered = await discoverNotifyCharacteristic(device.deviceId);
|
||||
// 连接建立后部分安卓机型服务可用存在延时,等待后再发现服务,并重试规避同名设备切换的缓存问题
|
||||
await delay(800);
|
||||
const discovered = await discoverNotifyCharacteristicsWithRetry(device.deviceId, commit);
|
||||
if (discovered.error) throw discovered.error;
|
||||
|
||||
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
|
||||
deviceId: device.deviceId,
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid,
|
||||
state: true
|
||||
});
|
||||
if (notifyErr) throw notifyErr;
|
||||
if (!discovered.characteristics.length) throw new Error('未找到可订阅的重量数据特征');
|
||||
const subscribed = await subscribeWeightNotifications(device.deviceId, discovered.characteristics, commit);
|
||||
if (!subscribed) throw new Error('订阅重量数据特征失败');
|
||||
|
||||
commit('SET_CURRENT_DEVICE', {
|
||||
id: device.deviceId,
|
||||
name: device.name || '未知设备',
|
||||
serviceId: discovered.service.uuid,
|
||||
characteristicId: discovered.characteristic.uuid
|
||||
characteristics: discovered.characteristics
|
||||
});
|
||||
saveHistoryDevice({ deviceId: device.deviceId, name: device.name || '' });
|
||||
clearReconnectTimer();
|
||||
@ -690,6 +851,7 @@ const actions = {
|
||||
commit('SET_CONNECTION_STATUS', 'connected');
|
||||
dispatch('stopScan');
|
||||
commit('ADD_LOG', { type: 'success', message: `连接成功: ${device.name || device.deviceId}` });
|
||||
startDataWatchdog(commit, state, dispatch);
|
||||
return true;
|
||||
} catch (e) {
|
||||
manualDisconnect = false;
|
||||
@ -704,9 +866,40 @@ const actions = {
|
||||
throw e;
|
||||
} finally {
|
||||
connectLock = false;
|
||||
connectLockAt = 0;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 已连接但收不到数据时强制重连:先断开再走完整重连流程,规避安卓 GATT 缓存
|
||||
*/
|
||||
async forceReconnect({ commit, state, dispatch }) {
|
||||
const device = state.currentDevice;
|
||||
if (!device || !device.id) return;
|
||||
if (connectLock && Date.now() - connectLockAt < CONNECT_LOCK_TIMEOUT_MS) return;
|
||||
connectLock = true;
|
||||
connectLockAt = Date.now();
|
||||
try {
|
||||
manualDisconnect = true;
|
||||
try {
|
||||
await uni.closeBLEConnection({ deviceId: device.id });
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
await delay(1000);
|
||||
clearDisconnectDebounceTimer();
|
||||
manualDisconnect = false;
|
||||
commit('SET_CONNECTION_STATUS', 'disconnected');
|
||||
commit('SET_RECONNECTING', false);
|
||||
commit('SET_RECONNECT_MESSAGE', '');
|
||||
} finally {
|
||||
connectLock = false;
|
||||
connectLockAt = 0;
|
||||
}
|
||||
// 释放锁后再走完整重连流程
|
||||
await dispatch('reconnectIfNeeded').catch(() => {});
|
||||
},
|
||||
|
||||
/**
|
||||
* 断开连接
|
||||
*/
|
||||
@ -715,14 +908,19 @@ const actions = {
|
||||
clearReconnectTimer();
|
||||
clearDisconnectDebounceTimer();
|
||||
clearScanStopTimer();
|
||||
clearDataWatchdog();
|
||||
watchdogRetries = 0;
|
||||
commit('SET_RECONNECTING', false);
|
||||
commit('SET_RECONNECT_MESSAGE', '已手动断开连接');
|
||||
if (state.currentDevice) {
|
||||
lastDisconnectAt = Date.now();
|
||||
try {
|
||||
await uni.closeBLEConnection({ deviceId: state.currentDevice.id });
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
// 等待系统完成 GATT 断开,避免紧接着连接新设备时服务发现返回空/旧缓存
|
||||
await delay(1000);
|
||||
}
|
||||
commit('RESET_CONNECTION');
|
||||
commit('SET_RECONNECT_ATTEMPTS', 0);
|
||||
|
||||
@ -88,6 +88,10 @@
|
||||
<text class="scale-live-stable">{{ scaleStable ? '稳定' : '读数中' }}</text>
|
||||
</view>
|
||||
</view>
|
||||
<view class="scale-status-line" v-if="isScaleConnected">
|
||||
<text class="scale-status-label">原始数据</text>
|
||||
<text class="scale-live-value" style="font-size: 22rpx; word-break: break-all;">{{ scaleRawText || '--' }}</text>
|
||||
</view>
|
||||
<view class="scale-status-line">
|
||||
<text class="scale-status-label">自动读秤</text>
|
||||
<u-switch v-model="autoReadScale" size="20" activeColor="#2979ff"></u-switch>
|
||||
@ -272,6 +276,9 @@ import voice from '@/core/utils/voice';
|
||||
scaleWeightDisplay() {
|
||||
const g = this.scaleWeightInGrams();
|
||||
return g === '' ? '--' : g;
|
||||
},
|
||||
scaleRawText() {
|
||||
return this.$store.state.bluetoothScale.rawText;
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user