feat(bluetoothScale): 新增蓝牙电子秤接入与演示页
基于 uni-app BLE 实现电子秤「扫描 → 按完整名称精确匹配连接 → 订阅通知 → 解析重量」完整流程。 - 新增 bluetoothScale Vuex 模块(bluetoothScale.js): 蓝牙初始化、设备扫描、按名称连接、BLE 服务/特征值发现、通知订阅、重量解析 - 新增蓝牙秤演示页(bluetoothScale.vue): 实时重量显示、原始数据/HEX 核对、扫描设备列表、操作日志 - 注册 bluetoothScale 模块到 store/index.js - 注册页面路由到 pages.json - 设置页新增「蓝牙秤演示」入口 说明:纯新增改动,不影响现有业务流程;仅支持 BLE,经典蓝牙 SPP 需另引原生插件。
This commit is contained in:
parent
ee00ca7661
commit
dc4c0cd0e5
@ -7,6 +7,7 @@ import setting from './modules/setting.js'
|
|||||||
import broadcast from './modules/broadcast.js'
|
import broadcast from './modules/broadcast.js'
|
||||||
import floatWindowManager from './modules/floatWindowManager.js'
|
import floatWindowManager from './modules/floatWindowManager.js'
|
||||||
import bluetoothPrint from './modules/bluetoothPrint.js'
|
import bluetoothPrint from './modules/bluetoothPrint.js'
|
||||||
|
import bluetoothScale from './modules/bluetoothScale.js'
|
||||||
import print from './modules/print.js'
|
import print from './modules/print.js'
|
||||||
import deviceInfo from './modules/deviceInfo.js'
|
import deviceInfo from './modules/deviceInfo.js'
|
||||||
|
|
||||||
@ -17,6 +18,7 @@ const store = new Vuex.Store({
|
|||||||
broadcast,
|
broadcast,
|
||||||
floatWindowManager,
|
floatWindowManager,
|
||||||
bluetoothPrint,
|
bluetoothPrint,
|
||||||
|
bluetoothScale,
|
||||||
print,
|
print,
|
||||||
deviceInfo
|
deviceInfo
|
||||||
}
|
}
|
||||||
|
|||||||
447
src/core/store/modules/bluetoothScale.js
Normal file
447
src/core/store/modules/bluetoothScale.js
Normal file
@ -0,0 +1,447 @@
|
|||||||
|
// store/modules/bluetoothScale.js
|
||||||
|
// 蓝牙电子秤模块:扫描 -> 按完整名称匹配连接 -> 订阅通知特征 -> 解析重量
|
||||||
|
// 说明:基于 uni-app 内置 BLE(低功耗蓝牙)API 实现,与 bluetoothPrint 模块保持一致。
|
||||||
|
|
||||||
|
// ---------------- 工具函数 ----------------
|
||||||
|
|
||||||
|
// 任意数据 -> Uint8Array
|
||||||
|
function toBytes(value) {
|
||||||
|
if (value instanceof Uint8Array) return value;
|
||||||
|
if (value instanceof ArrayBuffer) return new Uint8Array(value);
|
||||||
|
if (Array.isArray(value)) return new Uint8Array(value);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 字节 -> UTF-8 字符串(ASCII 兼容)
|
||||||
|
function bytesToUtf8(bytes) {
|
||||||
|
if (!bytes || !bytes.length) return '';
|
||||||
|
let out = '';
|
||||||
|
const chunk = 0x8000;
|
||||||
|
for (let i = 0; i < bytes.length; i += chunk) {
|
||||||
|
out += String.fromCharCode.apply(null, Array.prototype.slice.call(bytes, i, i + chunk));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 字节 -> 十六进制字符串
|
||||||
|
function bytesToHex(bytes) {
|
||||||
|
if (!bytes || !bytes.length) return '';
|
||||||
|
const parts = [];
|
||||||
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
|
parts.push(('0' + bytes[i].toString(16)).slice(-2));
|
||||||
|
}
|
||||||
|
return parts.join(' ').toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
function delay(ms) {
|
||||||
|
return new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从文本中解析重量(可配置的启发式解析)
|
||||||
|
function parseWeight(text) {
|
||||||
|
if (!text) return { value: null, unit: '', stable: false, text: '' };
|
||||||
|
const clean = String(text).replace(/[\x00-\x1f\x7f]/g, '').trim();
|
||||||
|
if (!clean) return { value: null, unit: '', stable: false, text: '' };
|
||||||
|
|
||||||
|
// 稳定标志:ST/GS/OK 视为稳定,US 不稳定,OL 超载
|
||||||
|
const stable = /(ST|GS|OK)/i.test(clean) && !/(US|OL|ER)/i.test(clean);
|
||||||
|
|
||||||
|
// 单位
|
||||||
|
let unit = '';
|
||||||
|
if (/kg/i.test(clean)) unit = 'kg';
|
||||||
|
else if (/g\b/i.test(clean)) unit = 'g';
|
||||||
|
|
||||||
|
let value = null;
|
||||||
|
// 优先取稳定/重量标志后的数字
|
||||||
|
const marker = clean.match(/(?:ST|GS|WT|N|NET|G|KG)\s*,?\s*([+-]?\d+(?:\.\d+)?)/i);
|
||||||
|
if (marker) value = parseFloat(marker[1]);
|
||||||
|
|
||||||
|
if (value === null || isNaN(value)) {
|
||||||
|
// 退而取最后一个数字(多数协议重量在末尾)
|
||||||
|
const numbers = clean.match(/[+-]?\d+(?:\.\d+)?/g);
|
||||||
|
if (numbers && numbers.length) value = parseFloat(numbers[numbers.length - 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value === null || isNaN(value)) value = null;
|
||||||
|
|
||||||
|
return { value, unit, stable, text: clean };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 是否已注册全局监听
|
||||||
|
let listenersRegistered = false;
|
||||||
|
|
||||||
|
// ---------------- 模块定义 ----------------
|
||||||
|
|
||||||
|
const state = () => ({
|
||||||
|
available: false, // 蓝牙适配器是否可用
|
||||||
|
discovering: false, // 是否正在扫描
|
||||||
|
devices: [], // 扫描到的设备列表
|
||||||
|
currentDevice: null, // 当前连接的设备
|
||||||
|
connectionStatus: 'disconnected', // disconnected/scanning/connecting/connected/error
|
||||||
|
|
||||||
|
// 称重数据
|
||||||
|
weight: null, // 解析出的重量数值
|
||||||
|
weightUnit: '', // 单位 kg/g
|
||||||
|
stable: false, // 是否稳定
|
||||||
|
rawText: '', // 原始文本
|
||||||
|
rawHex: '', // 原始十六进制
|
||||||
|
lastDataTime: null, // 最近一次收到数据时间
|
||||||
|
|
||||||
|
// 配置
|
||||||
|
filterName: '', // 期望的电子秤完整名称
|
||||||
|
|
||||||
|
lastError: null,
|
||||||
|
logs: []
|
||||||
|
});
|
||||||
|
|
||||||
|
const getters = {
|
||||||
|
isConnected: state => state.connectionStatus === 'connected',
|
||||||
|
weightDisplay: state => (state.weight === null ? '' : String(state.weight)),
|
||||||
|
statusText: state => {
|
||||||
|
const map = {
|
||||||
|
disconnected: '未连接',
|
||||||
|
scanning: '扫描中',
|
||||||
|
connecting: '连接中',
|
||||||
|
connected: '已连接',
|
||||||
|
error: '连接异常'
|
||||||
|
};
|
||||||
|
return map[state.connectionStatus] || state.connectionStatus;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const mutations = {
|
||||||
|
AVAILABLE(state, status) {
|
||||||
|
state.available = status;
|
||||||
|
},
|
||||||
|
DISCOVERING(state, status) {
|
||||||
|
state.discovering = status;
|
||||||
|
},
|
||||||
|
SET_FILTER_NAME(state, name) {
|
||||||
|
state.filterName = name;
|
||||||
|
},
|
||||||
|
RESET_DEVICES(state) {
|
||||||
|
state.devices = [];
|
||||||
|
},
|
||||||
|
ADD_DEVICE(state, device) {
|
||||||
|
if (!device || !device.deviceId) return;
|
||||||
|
if (!state.devices.some(d => d.deviceId === device.deviceId)) {
|
||||||
|
state.devices.push({
|
||||||
|
deviceId: device.deviceId,
|
||||||
|
name: device.name || device.localName || '',
|
||||||
|
RSSI: device.RSSI
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
SET_CURRENT_DEVICE(state, device) {
|
||||||
|
state.currentDevice = device;
|
||||||
|
},
|
||||||
|
SET_CONNECTION_STATUS(state, status) {
|
||||||
|
state.connectionStatus = status;
|
||||||
|
},
|
||||||
|
RAW_DATA(state, { text, hex, time }) {
|
||||||
|
state.rawText = text;
|
||||||
|
state.rawHex = hex;
|
||||||
|
state.lastDataTime = time;
|
||||||
|
},
|
||||||
|
WEIGHT(state, parsed) {
|
||||||
|
const changed = state.weight !== parsed.value;
|
||||||
|
state.weight = parsed.value;
|
||||||
|
state.weightUnit = parsed.unit;
|
||||||
|
state.stable = parsed.stable;
|
||||||
|
if (changed) {
|
||||||
|
state.logs.unshift({
|
||||||
|
type: 'info',
|
||||||
|
message: `收到重量: ${parsed.value}${parsed.unit}`,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
if (state.logs.length > 100) state.logs.pop();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
RESET_CONNECTION(state) {
|
||||||
|
state.currentDevice = null;
|
||||||
|
state.connectionStatus = 'disconnected';
|
||||||
|
state.weight = null;
|
||||||
|
state.weightUnit = '';
|
||||||
|
state.stable = false;
|
||||||
|
state.rawText = '';
|
||||||
|
state.rawHex = '';
|
||||||
|
},
|
||||||
|
SET_ERROR(state, error) {
|
||||||
|
state.lastError = error;
|
||||||
|
if (error) {
|
||||||
|
state.logs.unshift({
|
||||||
|
type: 'error',
|
||||||
|
message: error.message || error.errMsg || String(error),
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
if (state.logs.length > 100) state.logs.pop();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ADD_LOG(state, log) {
|
||||||
|
state.logs.unshift({
|
||||||
|
...log,
|
||||||
|
timestamp: new Date().toISOString()
|
||||||
|
});
|
||||||
|
if (state.logs.length > 100) state.logs.pop();
|
||||||
|
},
|
||||||
|
CLEAR_LOGS(state) {
|
||||||
|
state.logs = [];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 处理收到的特征值数据
|
||||||
|
function parseIncoming(commit, state, res) {
|
||||||
|
if (!res || !state.currentDevice) return;
|
||||||
|
if (res.deviceId && state.currentDevice.id && res.deviceId !== state.currentDevice.id) return;
|
||||||
|
|
||||||
|
const bytes = toBytes(res.value);
|
||||||
|
if (!bytes || !bytes.length) return;
|
||||||
|
|
||||||
|
const text = bytesToUtf8(bytes);
|
||||||
|
const hex = bytesToHex(bytes);
|
||||||
|
commit('RAW_DATA', { text, hex, time: Date.now() });
|
||||||
|
|
||||||
|
const parsed = parseWeight(text);
|
||||||
|
if (parsed.value !== null) {
|
||||||
|
commit('WEIGHT', parsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const actions = {
|
||||||
|
/**
|
||||||
|
* 初始化蓝牙适配器并注册全局监听
|
||||||
|
*/
|
||||||
|
async initialize({ commit, state }) {
|
||||||
|
if (!listenersRegistered) {
|
||||||
|
listenersRegistered = true;
|
||||||
|
|
||||||
|
uni.onBluetoothAdapterStateChange(function(res) {
|
||||||
|
commit('AVAILABLE', res.available);
|
||||||
|
commit('DISCOVERING', res.discovering);
|
||||||
|
});
|
||||||
|
|
||||||
|
uni.onBluetoothDeviceFound(function(res) {
|
||||||
|
const list = (res && res.devices) || [];
|
||||||
|
list.forEach(d => commit('ADD_DEVICE', d));
|
||||||
|
});
|
||||||
|
|
||||||
|
uni.onBLEConnectionStateChange(function(res) {
|
||||||
|
if (state.currentDevice && res.deviceId === state.currentDevice.id) {
|
||||||
|
if (!res.connected) {
|
||||||
|
commit('SET_CONNECTION_STATUS', 'disconnected');
|
||||||
|
commit('ADD_LOG', { type: 'warning', message: '蓝牙连接已断开' });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
uni.onBLECharacteristicValueChange(function(res) {
|
||||||
|
parseIncoming(commit, state, res);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.available) return;
|
||||||
|
|
||||||
|
const [err] = await uni.openBluetoothAdapter();
|
||||||
|
if (err) {
|
||||||
|
commit('AVAILABLE', false);
|
||||||
|
commit('SET_ERROR', err);
|
||||||
|
throw new Error('请开启手机蓝牙');
|
||||||
|
}
|
||||||
|
commit('AVAILABLE', true);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取已配对/已发现的设备(不含新扫描)
|
||||||
|
*/
|
||||||
|
async getBondedDevices() {
|
||||||
|
try {
|
||||||
|
const [err, res] = await uni.getBluetoothDevices();
|
||||||
|
if (err || !res || !res.devices) return [];
|
||||||
|
return res.devices.map(d => ({
|
||||||
|
deviceId: d.deviceId,
|
||||||
|
name: d.name || d.localName || ''
|
||||||
|
}));
|
||||||
|
} catch (e) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开启扫描
|
||||||
|
*/
|
||||||
|
async startScan({ commit }) {
|
||||||
|
commit('RESET_DEVICES');
|
||||||
|
const [err] = await uni.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false });
|
||||||
|
commit('DISCOVERING', true);
|
||||||
|
if (err) {
|
||||||
|
commit('DISCOVERING', false);
|
||||||
|
throw new Error(err.errMsg || '开启扫描失败');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 停止扫描
|
||||||
|
*/
|
||||||
|
async stopScan({ commit }) {
|
||||||
|
try {
|
||||||
|
await uni.stopBluetoothDevicesDiscovery();
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
commit('DISCOVERING', false);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫描设备(供页面手动调用)
|
||||||
|
*/
|
||||||
|
async scanDevices({ commit, dispatch }, status) {
|
||||||
|
if (status) {
|
||||||
|
await dispatch('initialize');
|
||||||
|
await dispatch('startScan');
|
||||||
|
} else {
|
||||||
|
await dispatch('stopScan');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按完整名称精确匹配并连接电子秤
|
||||||
|
*/
|
||||||
|
async connectDeviceByName({ commit, dispatch, state }, name) {
|
||||||
|
const targetName = String(name || '').trim();
|
||||||
|
if (!targetName) throw new Error('请先输入电子秤蓝牙名称');
|
||||||
|
|
||||||
|
commit('SET_FILTER_NAME', targetName);
|
||||||
|
commit('ADD_LOG', { type: 'info', message: `按名称查找设备: ${targetName}` });
|
||||||
|
|
||||||
|
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. 开启扫描,等待匹配设备出现
|
||||||
|
commit('SET_CONNECTION_STATUS', 'scanning');
|
||||||
|
await dispatch('startScan');
|
||||||
|
|
||||||
|
const timeout = 15000;
|
||||||
|
const startAt = Date.now();
|
||||||
|
try {
|
||||||
|
while (Date.now() - startAt < timeout) {
|
||||||
|
const match = state.devices.find(d => String(d.name || '').trim() === targetName);
|
||||||
|
if (match) {
|
||||||
|
return dispatch('connectDevice', match);
|
||||||
|
}
|
||||||
|
await delay(400);
|
||||||
|
}
|
||||||
|
throw new Error(`未找到名为「${targetName}」的蓝牙设备,请确认电子秤已开机并处于可被发现状态`);
|
||||||
|
} finally {
|
||||||
|
await dispatch('stopScan');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接指定设备(创建 BLE 连接并订阅通知特征)
|
||||||
|
*/
|
||||||
|
async connectDevice({ commit }, device) {
|
||||||
|
if (!device || !device.deviceId) throw new Error('无效的设备');
|
||||||
|
|
||||||
|
commit('SET_CONNECTION_STATUS', 'connecting');
|
||||||
|
commit('ADD_LOG', { type: 'info', message: `正在连接: ${device.name || device.deviceId}` });
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [connErr] = await uni.createBLEConnection({
|
||||||
|
deviceId: device.deviceId,
|
||||||
|
timeout: 10000
|
||||||
|
});
|
||||||
|
if (connErr) throw connErr;
|
||||||
|
|
||||||
|
const [srvErr, srvRes] = await uni.getBLEDeviceServices({ deviceId: device.deviceId });
|
||||||
|
if (srvErr || !srvRes || !srvRes.services || !srvRes.services.length) {
|
||||||
|
throw new Error('未发现设备服务');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 遍历服务,找到具备 notify/indicate 的特征值(电子秤重量数据通常通过通知推送)
|
||||||
|
let notifyChar = null;
|
||||||
|
let notifyService = null;
|
||||||
|
for (const service of srvRes.services) {
|
||||||
|
const [chErr, chRes] = await uni.getBLEDeviceCharacteristics({
|
||||||
|
deviceId: device.deviceId,
|
||||||
|
serviceId: service.uuid
|
||||||
|
});
|
||||||
|
if (chErr || !chRes || !chRes.characteristics) continue;
|
||||||
|
|
||||||
|
for (const ch of chRes.characteristics) {
|
||||||
|
if (ch.properties && (ch.properties.notify || ch.properties.indicate)) {
|
||||||
|
notifyChar = ch;
|
||||||
|
notifyService = service;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (notifyChar) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!notifyChar || !notifyService) {
|
||||||
|
throw new Error('未找到可订阅的重量数据特征');
|
||||||
|
}
|
||||||
|
|
||||||
|
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
|
||||||
|
deviceId: device.deviceId,
|
||||||
|
serviceId: notifyService.uuid,
|
||||||
|
characteristicId: notifyChar.uuid,
|
||||||
|
state: true
|
||||||
|
});
|
||||||
|
if (notifyErr) throw notifyErr;
|
||||||
|
|
||||||
|
commit('SET_CURRENT_DEVICE', {
|
||||||
|
id: device.deviceId,
|
||||||
|
name: device.name || '未知设备',
|
||||||
|
serviceId: notifyService.uuid,
|
||||||
|
characteristicId: notifyChar.uuid
|
||||||
|
});
|
||||||
|
commit('SET_CONNECTION_STATUS', 'connected');
|
||||||
|
commit('ADD_LOG', { type: 'success', message: `连接成功: ${device.name || device.deviceId}` });
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
commit('SET_CONNECTION_STATUS', 'error');
|
||||||
|
commit('SET_ERROR', e);
|
||||||
|
commit('ADD_LOG', {
|
||||||
|
type: 'error',
|
||||||
|
message: `连接失败: ${e.message || e.errMsg || '未知错误'}`
|
||||||
|
});
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 断开连接
|
||||||
|
*/
|
||||||
|
async disconnect({ commit, state }) {
|
||||||
|
if (state.currentDevice) {
|
||||||
|
try {
|
||||||
|
await uni.closeBLEConnection({ deviceId: state.currentDevice.id });
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
commit('RESET_CONNECTION');
|
||||||
|
commit('ADD_LOG', { type: 'info', message: '已断开连接' });
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空日志
|
||||||
|
*/
|
||||||
|
clearLogs({ commit }) {
|
||||||
|
commit('CLEAR_LOGS');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export default {
|
||||||
|
namespaced: true,
|
||||||
|
state,
|
||||||
|
getters,
|
||||||
|
mutations,
|
||||||
|
actions
|
||||||
|
};
|
||||||
@ -286,6 +286,13 @@
|
|||||||
"titleNView": false
|
"titleNView": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"path" : "pages/work/order/bluetoothScale",
|
||||||
|
"style" :
|
||||||
|
{
|
||||||
|
"titleNView": false
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"path" : "pages/work/order/interceptionLog",
|
"path" : "pages/work/order/interceptionLog",
|
||||||
"style" :
|
"style" :
|
||||||
|
|||||||
@ -93,6 +93,13 @@
|
|||||||
url: '/pages/settings/scanSound',
|
url: '/pages/settings/scanSound',
|
||||||
badge: 0
|
badge: 0
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: '蓝牙秤演示',
|
||||||
|
icon: 'bag',
|
||||||
|
iconColor: '#2979ff',
|
||||||
|
pageName: 'bluetoothScale',
|
||||||
|
url: '/pages/work/order/bluetoothScale'
|
||||||
|
},
|
||||||
{
|
{
|
||||||
title: '关于',
|
title: '关于',
|
||||||
icon: 'info-circle',
|
icon: 'info-circle',
|
||||||
|
|||||||
388
src/pages/work/order/bluetoothScale.vue
Normal file
388
src/pages/work/order/bluetoothScale.vue
Normal file
@ -0,0 +1,388 @@
|
|||||||
|
<template>
|
||||||
|
<view class="scale-page">
|
||||||
|
<page-nav title="蓝牙秤"></page-nav>
|
||||||
|
|
||||||
|
<view class="container">
|
||||||
|
<!-- 连接状态卡 -->
|
||||||
|
<view class="status-card">
|
||||||
|
<view class="status-line">
|
||||||
|
<text class="status-label">连接状态</text>
|
||||||
|
<text class="status-value" :class="`status-${connectionStatus}`">{{ statusText }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="status-line" v-if="currentDevice">
|
||||||
|
<text class="status-label">当前设备</text>
|
||||||
|
<text class="status-value">{{ currentDevice.name }}</text>
|
||||||
|
</view>
|
||||||
|
<view class="status-line" v-if="!available">
|
||||||
|
<text class="status-value status-error">蓝牙未开启,请先打开系统蓝牙</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 设备名称输入 -->
|
||||||
|
<view class="section">
|
||||||
|
<text class="section-title">电子秤蓝牙名称(完整名称精确匹配)</text>
|
||||||
|
<u-input
|
||||||
|
v-model="filterName"
|
||||||
|
placeholder="例如:SCALE-A01"
|
||||||
|
border="surround"
|
||||||
|
:clearable="true"
|
||||||
|
></u-input>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 操作按钮 -->
|
||||||
|
<view class="btn-row">
|
||||||
|
<u-button
|
||||||
|
type="primary"
|
||||||
|
:disabled="!filterName"
|
||||||
|
:loading="connectionStatus === 'connecting' || connectionStatus === 'scanning'"
|
||||||
|
@click="handleConnectByName"
|
||||||
|
>按名称连接</u-button>
|
||||||
|
<u-button type="info" :disabled="discovering" @click="handleScan">扫描设备</u-button>
|
||||||
|
<u-button
|
||||||
|
type="error"
|
||||||
|
:disabled="connectionStatus !== 'connected'"
|
||||||
|
@click="handleDisconnect"
|
||||||
|
>断开</u-button>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 实时重量 -->
|
||||||
|
<view class="weight-card" :class="{ 'weight-card--connected': connectionStatus === 'connected' }">
|
||||||
|
<text class="weight-label">实时重量</text>
|
||||||
|
<view class="weight-value-wrap">
|
||||||
|
<text class="weight-value">{{ weightDisplay }}</text>
|
||||||
|
<text class="weight-unit">{{ weightUnit }}</text>
|
||||||
|
</view>
|
||||||
|
<text class="weight-stable" v-if="connectionStatus === 'connected'">
|
||||||
|
{{ stable ? '✓ 重量稳定' : '读数中...' }}
|
||||||
|
</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 原始数据 -->
|
||||||
|
<view class="section raw-card">
|
||||||
|
<text class="section-title">原始数据(用于核对协议)</text>
|
||||||
|
<text class="raw-text">文本:{{ rawText || '--' }}</text>
|
||||||
|
<text class="raw-text">HEX:{{ rawHex || '--' }}</text>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 扫描到的设备列表 -->
|
||||||
|
<view class="section">
|
||||||
|
<view class="section-header">
|
||||||
|
<text class="section-title">扫描到的设备({{ devices.length }})</text>
|
||||||
|
<text class="refresh-btn" @click="handleScan">刷新</text>
|
||||||
|
</view>
|
||||||
|
<view
|
||||||
|
v-for="d in devices"
|
||||||
|
:key="d.deviceId"
|
||||||
|
class="device-item"
|
||||||
|
@click="handleSelectDevice(d)"
|
||||||
|
>
|
||||||
|
<view class="device-info">
|
||||||
|
<text class="device-name">{{ d.name || '未知设备' }}</text>
|
||||||
|
<text class="device-id">{{ d.deviceId }}</text>
|
||||||
|
</view>
|
||||||
|
<text class="device-connect">连接</text>
|
||||||
|
</view>
|
||||||
|
<u-empty v-if="devices.length === 0" mode="list" text="暂无设备,点击扫描"></u-empty>
|
||||||
|
</view>
|
||||||
|
|
||||||
|
<!-- 日志 -->
|
||||||
|
<view class="section" v-if="logs.length">
|
||||||
|
<view class="section-header">
|
||||||
|
<text class="section-title">日志</text>
|
||||||
|
<text class="refresh-btn" @click="clearLogs">清空</text>
|
||||||
|
</view>
|
||||||
|
<view v-for="(l, i) in logs" :key="i" class="log-item">
|
||||||
|
<text class="log-text">{{ formatTime(l.timestamp) }} {{ l.message }}</text>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</view>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
export default {
|
||||||
|
data() {
|
||||||
|
return {
|
||||||
|
filterName: ''
|
||||||
|
};
|
||||||
|
},
|
||||||
|
computed: {
|
||||||
|
available() {
|
||||||
|
return this.$store.state.bluetoothScale.available;
|
||||||
|
},
|
||||||
|
discovering() {
|
||||||
|
return this.$store.state.bluetoothScale.discovering;
|
||||||
|
},
|
||||||
|
devices() {
|
||||||
|
return this.$store.state.bluetoothScale.devices;
|
||||||
|
},
|
||||||
|
currentDevice() {
|
||||||
|
return this.$store.state.bluetoothScale.currentDevice;
|
||||||
|
},
|
||||||
|
connectionStatus() {
|
||||||
|
return this.$store.state.bluetoothScale.connectionStatus;
|
||||||
|
},
|
||||||
|
weight() {
|
||||||
|
return this.$store.state.bluetoothScale.weight;
|
||||||
|
},
|
||||||
|
weightUnit() {
|
||||||
|
return this.$store.state.bluetoothScale.weightUnit;
|
||||||
|
},
|
||||||
|
stable() {
|
||||||
|
return this.$store.state.bluetoothScale.stable;
|
||||||
|
},
|
||||||
|
rawText() {
|
||||||
|
return this.$store.state.bluetoothScale.rawText;
|
||||||
|
},
|
||||||
|
rawHex() {
|
||||||
|
return this.$store.state.bluetoothScale.rawHex;
|
||||||
|
},
|
||||||
|
logs() {
|
||||||
|
return this.$store.state.bluetoothScale.logs;
|
||||||
|
},
|
||||||
|
statusText() {
|
||||||
|
return this.$store.getters['bluetoothScale/statusText'];
|
||||||
|
},
|
||||||
|
weightDisplay() {
|
||||||
|
return this.weight === null || this.weight === '' ? '--' : this.weight;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onLoad() {
|
||||||
|
this.$store.dispatch('bluetoothScale/initialize').catch(() => {});
|
||||||
|
},
|
||||||
|
onUnload() {
|
||||||
|
// 离开页面时停止扫描并断开连接,释放蓝牙资源
|
||||||
|
this.$store.dispatch('bluetoothScale/stopScan');
|
||||||
|
this.$store.dispatch('bluetoothScale/disconnect');
|
||||||
|
},
|
||||||
|
methods: {
|
||||||
|
async handleConnectByName() {
|
||||||
|
if (!this.filterName) {
|
||||||
|
uni.showToast({ title: '请输入电子秤蓝牙名称', icon: 'none' });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.$store.dispatch('bluetoothScale/connectDeviceByName', this.filterName);
|
||||||
|
} catch (e) {
|
||||||
|
uni.showToast({ title: e.message || '连接失败', icon: 'none' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async handleScan() {
|
||||||
|
try {
|
||||||
|
await this.$store.dispatch('bluetoothScale/scanDevices', true);
|
||||||
|
} catch (e) {
|
||||||
|
uni.showToast({ title: e.message || '扫描失败', icon: 'none' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
async handleDisconnect() {
|
||||||
|
await this.$store.dispatch('bluetoothScale/disconnect');
|
||||||
|
uni.showToast({ title: '已断开', icon: 'none' });
|
||||||
|
},
|
||||||
|
async handleSelectDevice(device) {
|
||||||
|
try {
|
||||||
|
await this.$store.dispatch('bluetoothScale/connectDevice', device);
|
||||||
|
} catch (e) {
|
||||||
|
uni.showToast({ title: e.message || '连接失败', icon: 'none' });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
clearLogs() {
|
||||||
|
this.$store.dispatch('bluetoothScale/clearLogs');
|
||||||
|
},
|
||||||
|
formatTime(ts) {
|
||||||
|
if (!ts) return '';
|
||||||
|
const d = new Date(ts);
|
||||||
|
const pad = n => (n < 10 ? '0' + n : '' + n);
|
||||||
|
return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style lang="scss" scoped>
|
||||||
|
.scale-page {
|
||||||
|
min-height: 100vh;
|
||||||
|
background-color: #f5f5f5;
|
||||||
|
|
||||||
|
.container {
|
||||||
|
padding: 24rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section {
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12rpx;
|
||||||
|
padding: 24rpx;
|
||||||
|
margin-bottom: 20rpx;
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 28rpx;
|
||||||
|
color: #666;
|
||||||
|
margin-bottom: 16rpx;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 16rpx;
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.refresh-btn {
|
||||||
|
font-size: 26rpx;
|
||||||
|
color: #2979ff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-card {
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12rpx;
|
||||||
|
padding: 24rpx;
|
||||||
|
margin-bottom: 20rpx;
|
||||||
|
|
||||||
|
.status-line {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 8rpx 0;
|
||||||
|
|
||||||
|
.status-label {
|
||||||
|
font-size: 28rpx;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-value {
|
||||||
|
font-size: 28rpx;
|
||||||
|
color: #333;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-connected {
|
||||||
|
color: #19be6b;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-error {
|
||||||
|
color: #fa3534;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-scanning,
|
||||||
|
.status-connecting {
|
||||||
|
color: #2979ff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 16rpx;
|
||||||
|
margin-bottom: 20rpx;
|
||||||
|
|
||||||
|
::v-deep .u-button {
|
||||||
|
flex: 1;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.weight-card {
|
||||||
|
background: #fff;
|
||||||
|
border-radius: 12rpx;
|
||||||
|
padding: 40rpx 24rpx;
|
||||||
|
margin-bottom: 20rpx;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
|
||||||
|
&--connected {
|
||||||
|
background: #f0f7ff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.weight-label {
|
||||||
|
font-size: 28rpx;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
.weight-value-wrap {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
margin: 16rpx 0 8rpx;
|
||||||
|
|
||||||
|
.weight-value {
|
||||||
|
font-size: 120rpx;
|
||||||
|
font-weight: bold;
|
||||||
|
color: #2979ff;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.weight-unit {
|
||||||
|
font-size: 36rpx;
|
||||||
|
color: #999;
|
||||||
|
margin-left: 12rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.weight-stable {
|
||||||
|
font-size: 24rpx;
|
||||||
|
color: #19be6b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.raw-card {
|
||||||
|
.raw-text {
|
||||||
|
display: block;
|
||||||
|
font-size: 24rpx;
|
||||||
|
color: #666;
|
||||||
|
line-height: 1.8;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 20rpx 0;
|
||||||
|
border-bottom: 1rpx solid #f0f0f0;
|
||||||
|
|
||||||
|
&:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-info {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
|
||||||
|
.device-name {
|
||||||
|
font-size: 30rpx;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-id {
|
||||||
|
font-size: 22rpx;
|
||||||
|
color: #999;
|
||||||
|
margin-top: 4rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.device-connect {
|
||||||
|
font-size: 26rpx;
|
||||||
|
color: #2979ff;
|
||||||
|
padding: 8rpx 20rpx;
|
||||||
|
border: 1rpx solid #2979ff;
|
||||||
|
border-radius: 8rpx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.log-item {
|
||||||
|
padding: 8rpx 0;
|
||||||
|
|
||||||
|
.log-text {
|
||||||
|
font-size: 24rpx;
|
||||||
|
color: #666;
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</style>
|
||||||
Loading…
x
Reference in New Issue
Block a user