diff --git a/src/core/store/index.js b/src/core/store/index.js
index 071ed9a..a9ae08b 100644
--- a/src/core/store/index.js
+++ b/src/core/store/index.js
@@ -7,6 +7,7 @@ import setting from './modules/setting.js'
import broadcast from './modules/broadcast.js'
import floatWindowManager from './modules/floatWindowManager.js'
import bluetoothPrint from './modules/bluetoothPrint.js'
+import bluetoothScale from './modules/bluetoothScale.js'
import print from './modules/print.js'
import deviceInfo from './modules/deviceInfo.js'
@@ -17,6 +18,7 @@ const store = new Vuex.Store({
broadcast,
floatWindowManager,
bluetoothPrint,
+ bluetoothScale,
print,
deviceInfo
}
diff --git a/src/core/store/modules/bluetoothScale.js b/src/core/store/modules/bluetoothScale.js
new file mode 100644
index 0000000..212844e
--- /dev/null
+++ b/src/core/store/modules/bluetoothScale.js
@@ -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
+};
diff --git a/src/pages.json b/src/pages.json
index 2f8f397..61fd28d 100644
--- a/src/pages.json
+++ b/src/pages.json
@@ -286,6 +286,13 @@
"titleNView": false
}
},
+ {
+ "path" : "pages/work/order/bluetoothScale",
+ "style" :
+ {
+ "titleNView": false
+ }
+ },
{
"path" : "pages/work/order/interceptionLog",
"style" :
diff --git a/src/pages/settings/index.vue b/src/pages/settings/index.vue
index c69c877..40a4371 100644
--- a/src/pages/settings/index.vue
+++ b/src/pages/settings/index.vue
@@ -93,6 +93,13 @@
url: '/pages/settings/scanSound',
badge: 0
},
+ {
+ title: '蓝牙秤演示',
+ icon: 'bag',
+ iconColor: '#2979ff',
+ pageName: 'bluetoothScale',
+ url: '/pages/work/order/bluetoothScale'
+ },
{
title: '关于',
icon: 'info-circle',
diff --git a/src/pages/work/order/bluetoothScale.vue b/src/pages/work/order/bluetoothScale.vue
new file mode 100644
index 0000000..3a66c10
--- /dev/null
+++ b/src/pages/work/order/bluetoothScale.vue
@@ -0,0 +1,388 @@
+
+
+
+
+
+
+
+
+ 连接状态
+ {{ statusText }}
+
+
+ 当前设备
+ {{ currentDevice.name }}
+
+
+ 蓝牙未开启,请先打开系统蓝牙
+
+
+
+
+
+ 电子秤蓝牙名称(完整名称精确匹配)
+
+
+
+
+
+ 按名称连接
+ 扫描设备
+ 断开
+
+
+
+
+ 实时重量
+
+ {{ weightDisplay }}
+ {{ weightUnit }}
+
+
+ {{ stable ? '✓ 重量稳定' : '读数中...' }}
+
+
+
+
+
+ 原始数据(用于核对协议)
+ 文本:{{ rawText || '--' }}
+ HEX:{{ rawHex || '--' }}
+
+
+
+
+
+
+
+ {{ d.name || '未知设备' }}
+ {{ d.deviceId }}
+
+ 连接
+
+
+
+
+
+
+
+
+ {{ formatTime(l.timestamp) }} {{ l.message }}
+
+
+
+
+
+
+
+
+