feat(order): 称重页接入蓝牙电子秤并优化显示与交互

- 新增 bluetoothScale store 模块:BLE 扫描、按完整名称精确连接、
  设备连接(服务/特征发现 + 订阅通知)、重量解析(kg/g、稳定标志)、
  断线自动重连、手动断开
- 新增蓝牙秤演示页 bluetoothScale.vue(扫描/连接/实时重量/原始数据/日志)
- 称重页 weighing.vue 接入蓝牙秤:
  - 称重重量行新增「连秤/读秤」按钮,支持读取重量回填输入框
  - 新增蓝牙秤状态卡:连接状态、实时重量、自动读秤开关、连接/断开/设备管理
  - 新增「连接蓝牙秤」弹窗:设备扫描列表 + 按完整名称连接
- 显示与交互优化:
  - 蓝牙秤状态卡与弹窗字体整体调大
  - 旧真机 flex gap 兼容(改用显式 margin 留间隔)
  - 合并「设备管理」与「连接蓝牙秤」重复入口(未连接只显示连接,已连接显示断开+设备管理)
  - 操作按钮改为浅色背景+彩色文字,并放大高度与字号
  - 连接弹窗布局对齐盘点操作弹窗(居中标题、顶部圆角、底部按钮样式)
  - 断开蓝牙秤增加二次确认弹窗
  - 默认开启自动读秤;实时重量改黑色且不加粗;称重重量字号与实时重量一致
This commit is contained in:
zm2000 2026-10-15 18:12:30 +08:00
parent dc4c0cd0e5
commit fb14f89aef
3 changed files with 883 additions and 24 deletions

View File

@ -37,6 +37,25 @@ function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function normalizeBluetoothError(error) {
const raw = error && (error.message || error.errMsg || String(error));
const text = String(raw || '').trim();
if (!text) return '蓝牙扫描失败,请稍后重试';
if (/location services are turned off|定位服务.*关闭|Location service.*off/i.test(text)) {
return 'Android 需要打开“定位服务”(位置信息)后才能扫描蓝牙,请在系统设置中开启定位服务后重试。';
}
if (/permission|权限.*(location|定位)|ACCESS_FINE_LOCATION|ACCESS_COARSE_LOCATION/i.test(text)) {
return '请允许应用使用定位权限后再扫描蓝牙设备。';
}
if (/bluetooth.*(off|关闭)|请开启.*蓝牙|蓝牙.*未开启/i.test(text)) {
return '请先打开手机蓝牙,再扫描设备。';
}
if (/startBluetoothDevicesDiscovery|startBluetoothDevicesDiscovery:fail/i.test(text)) {
return '蓝牙扫描失败,请确认蓝牙和定位服务均已开启。';
}
return text;
}
// 从文本中解析重量(可配置的启发式解析)
function parseWeight(text) {
if (!text) return { value: null, unit: '', stable: false, text: '' };
@ -46,8 +65,8 @@ function parseWeight(text) {
// 稳定标志:ST/GS/OK 视为稳定,US 不稳定,OL 超载
const stable = /(ST|GS|OK)/i.test(clean) && !/(US|OL|ER)/i.test(clean);
// 单位
let unit = '';
// 单位:无显式标志时默认按 kg(电子秤常用标定单位)
let unit = 'kg';
if (/kg/i.test(clean)) unit = 'kg';
else if (/g\b/i.test(clean)) unit = 'g';
@ -69,6 +88,33 @@ function parseWeight(text) {
// 是否已注册全局监听
let listenersRegistered = false;
let reconnectTimer = null;
let disconnectDebounceTimer = null;
let scanStopTimer = null;
let manualDisconnect = false;
const SCAN_TIMEOUT_MS = 12000;
function clearReconnectTimer() {
if (reconnectTimer) {
clearTimeout(reconnectTimer);
reconnectTimer = null;
}
}
function clearDisconnectDebounceTimer() {
if (disconnectDebounceTimer) {
clearTimeout(disconnectDebounceTimer);
disconnectDebounceTimer = null;
}
}
function clearScanStopTimer() {
if (scanStopTimer) {
clearTimeout(scanStopTimer);
scanStopTimer = null;
}
}
// ---------------- 模块定义 ----------------
@ -91,7 +137,12 @@ const state = () => ({
filterName: '', // 期望的电子秤完整名称
lastError: null,
logs: []
logs: [],
reconnectAttempts: 0,
maxReconnectAttempts: 5,
autoReconnect: true,
reconnecting: false,
reconnectMessage: ''
});
const getters = {
@ -177,6 +228,15 @@ const mutations = {
if (state.logs.length > 100) state.logs.pop();
}
},
SET_RECONNECT_ATTEMPTS(state, attempts) {
state.reconnectAttempts = attempts;
},
SET_RECONNECTING(state, value) {
state.reconnecting = value;
},
SET_RECONNECT_MESSAGE(state, message) {
state.reconnectMessage = message;
},
ADD_LOG(state, log) {
state.logs.unshift({
...log,
@ -211,7 +271,7 @@ const actions = {
/**
* 初始化蓝牙适配器并注册全局监听
*/
async initialize({ commit, state }) {
async initialize({ commit, state, dispatch }) {
if (!listenersRegistered) {
listenersRegistered = true;
@ -227,10 +287,43 @@ const actions = {
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: '蓝牙连接已断开' });
if (res.connected) {
manualDisconnect = false;
clearReconnectTimer();
clearDisconnectDebounceTimer();
commit('SET_RECONNECT_ATTEMPTS', 0);
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '连接已恢复,正在持续读取重量');
commit('SET_CONNECTION_STATUS', 'connected');
commit('ADD_LOG', { type: 'success', message: '蓝牙连接恢复' });
return;
}
clearDisconnectDebounceTimer();
disconnectDebounceTimer = setTimeout(() => {
if (manualDisconnect) return;
if (state.currentDevice && state.currentDevice.id === res.deviceId) {
commit('SET_CONNECTION_STATUS', 'disconnected');
commit('SET_RECONNECTING', true);
commit('SET_RECONNECT_MESSAGE', '连接中断,正在尝试自动重连...');
commit('ADD_LOG', { type: 'warning', message: '蓝牙连接已断开' });
if (state.autoReconnect) {
const delayMs = Math.min(2000 + state.reconnectAttempts * 1500, 8000);
commit('SET_RECONNECT_ATTEMPTS', Math.min(state.reconnectAttempts + 1, state.maxReconnectAttempts));
clearReconnectTimer();
reconnectTimer = setTimeout(() => {
if (!manualDisconnect && state.currentDevice && state.currentDevice.id) {
const current = state.currentDevice;
const action = () => dispatch('reconnectIfNeeded').catch(() => {});
action();
if (current && current.name) {
commit('ADD_LOG', { type: 'info', message: `开始自动重连: ${current.name}` });
}
}
}, delayMs);
}
}
}, 1200);
}
});
@ -243,9 +336,10 @@ const actions = {
const [err] = await uni.openBluetoothAdapter();
if (err) {
const normalized = normalizeBluetoothError(err);
commit('AVAILABLE', false);
commit('SET_ERROR', err);
throw new Error('请开启手机蓝牙');
commit('SET_ERROR', { message: normalized, errMsg: normalized });
throw new Error(normalized);
}
commit('AVAILABLE', true);
},
@ -269,20 +363,28 @@ const actions = {
/**
* 开启扫描
*/
async startScan({ commit }) {
async startScan({ commit, dispatch }) {
commit('RESET_DEVICES');
const [err] = await uni.startBluetoothDevicesDiscovery({ allowDuplicatesKey: false });
commit('DISCOVERING', true);
if (err) {
const normalized = normalizeBluetoothError(err);
commit('DISCOVERING', false);
throw new Error(err.errMsg || '开启扫描失败');
commit('SET_ERROR', { message: normalized, errMsg: normalized });
throw new Error(normalized);
}
// 自动扫描会在超时后停止,避免持续耗电
clearScanStopTimer();
scanStopTimer = setTimeout(() => {
dispatch('stopScan');
}, SCAN_TIMEOUT_MS);
},
/**
* 停止扫描
*/
async stopScan({ commit }) {
clearScanStopTimer();
try {
await uni.stopBluetoothDevicesDiscovery();
} catch (e) {
@ -345,9 +447,92 @@ const actions = {
/**
* 连接指定设备(创建 BLE 连接并订阅通知特征)
*/
async connectDevice({ commit }, device) {
if (!device || !device.deviceId) throw new Error('无效的设备');
async reconnectIfNeeded({ commit, state, dispatch }) {
if (manualDisconnect) return;
if (!state.currentDevice || !state.currentDevice.id) return;
if (state.connectionStatus === 'connected') return;
if (state.reconnectAttempts >= state.maxReconnectAttempts) {
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '自动重连已达到上限,可手动重连');
commit('ADD_LOG', { type: 'warning', message: `自动重连已达到上限,设备: ${state.currentDevice.name || state.currentDevice.id}` });
return;
}
commit('SET_RECONNECTING', true);
commit('SET_RECONNECT_MESSAGE', '正在恢复蓝牙连接...');
commit('SET_CONNECTION_STATUS', 'connecting');
commit('ADD_LOG', { type: 'info', message: `恢复连接: ${state.currentDevice.name || state.currentDevice.id}` });
try {
const [adapterErr] = await uni.openBluetoothAdapter();
if (adapterErr) throw adapterErr;
const [connErr] = await uni.createBLEConnection({
deviceId: state.currentDevice.id,
timeout: 10000
});
if (connErr) {
const errText = String(connErr.message || connErr.errMsg || '');
if (/already connect|已连接|already connected/i.test(errText)) {
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '连接已恢复,正在持续读取重量');
commit('SET_CONNECTION_STATUS', 'connected');
commit('SET_RECONNECT_ATTEMPTS', 0);
dispatch('stopScan');
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,继续读取重量: ${state.currentDevice.name || state.currentDevice.id}` });
return true;
}
throw connErr;
}
if (state.currentDevice.serviceId && state.currentDevice.characteristicId) {
const [notifyErr] = await uni.notifyBLECharacteristicValueChange({
deviceId: state.currentDevice.id,
serviceId: state.currentDevice.serviceId,
characteristicId: state.currentDevice.characteristicId,
state: true
});
if (notifyErr) throw notifyErr;
}
clearReconnectTimer();
commit('SET_RECONNECT_ATTEMPTS', 0);
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '连接已恢复,正在持续读取重量');
commit('SET_CONNECTION_STATUS', 'connected');
dispatch('stopScan');
commit('ADD_LOG', { type: 'success', message: `已恢复连接: ${state.currentDevice.name || state.currentDevice.id}` });
return true;
} catch (e) {
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '自动重连失败,可手动重连');
commit('SET_CONNECTION_STATUS', 'error');
commit('SET_ERROR', e);
commit('SET_RECONNECT_ATTEMPTS', Math.min(state.reconnectAttempts + 1, state.maxReconnectAttempts));
if (state.currentDevice && state.currentDevice.id) {
commit('ADD_LOG', {
type: 'error',
message: `恢复连接失败: ${e.message || e.errMsg || '未知错误'}`
});
}
throw e;
}
},
async connectDevice({ commit, state, dispatch }, device) {
if (!device || !device.deviceId) throw new Error('无效的设备');
if (state.currentDevice && state.currentDevice.id === device.deviceId && state.connectionStatus === 'connected') {
commit('ADD_LOG', { type: 'info', message: `设备已连接,继续读取重量: ${device.name || device.deviceId}` });
return true;
}
if (manualDisconnect) {
commit('ADD_LOG', { type: 'info', message: `已手动断开,忽略重复连接: ${device.name || device.deviceId}` });
return false;
}
clearReconnectTimer();
clearDisconnectDebounceTimer();
manualDisconnect = false;
commit('SET_CONNECTION_STATUS', 'connecting');
commit('ADD_LOG', { type: 'info', message: `正在连接: ${device.name || device.deviceId}` });
@ -356,7 +541,27 @@ const actions = {
deviceId: device.deviceId,
timeout: 10000
});
if (connErr) throw connErr;
if (connErr) {
const errText = String(connErr.message || connErr.errMsg || '');
if (/already connect|已连接|already connected/i.test(errText)) {
if (!state.currentDevice || state.currentDevice.id !== device.deviceId) {
commit('SET_CURRENT_DEVICE', {
id: device.deviceId,
name: device.name || '未知设备',
serviceId: (state.currentDevice && state.currentDevice.serviceId) || '',
characteristicId: (state.currentDevice && state.currentDevice.characteristicId) || ''
});
}
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '');
commit('SET_CONNECTION_STATUS', 'connected');
commit('SET_RECONNECT_ATTEMPTS', 0);
dispatch('stopScan');
commit('ADD_LOG', { type: 'warning', message: `设备已处于连接状态,继续读取重量: ${device.name || device.deviceId}` });
return true;
}
throw connErr;
}
const [srvErr, srvRes] = await uni.getBLEDeviceServices({ deviceId: device.deviceId });
if (srvErr || !srvRes || !srvRes.services || !srvRes.services.length) {
@ -401,10 +606,18 @@ const actions = {
serviceId: notifyService.uuid,
characteristicId: notifyChar.uuid
});
clearReconnectTimer();
manualDisconnect = false;
commit('SET_RECONNECT_ATTEMPTS', 0);
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '');
commit('SET_CONNECTION_STATUS', 'connected');
dispatch('stopScan');
commit('ADD_LOG', { type: 'success', message: `连接成功: ${device.name || device.deviceId}` });
return true;
} catch (e) {
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '连接失败,可手动重连');
commit('SET_CONNECTION_STATUS', 'error');
commit('SET_ERROR', e);
commit('ADD_LOG', {
@ -419,6 +632,12 @@ const actions = {
* 断开连接
*/
async disconnect({ commit, state }) {
manualDisconnect = true;
clearReconnectTimer();
clearDisconnectDebounceTimer();
clearScanStopTimer();
commit('SET_RECONNECTING', false);
commit('SET_RECONNECT_MESSAGE', '已手动断开连接');
if (state.currentDevice) {
try {
await uni.closeBLEConnection({ deviceId: state.currentDevice.id });
@ -427,6 +646,7 @@ const actions = {
}
}
commit('RESET_CONNECTION');
commit('SET_RECONNECT_ATTEMPTS', 0);
commit('ADD_LOG', { type: 'info', message: '已断开连接' });
},

View File

@ -13,6 +13,10 @@
<text class="status-label">当前设备</text>
<text class="status-value">{{ currentDevice.name }}</text>
</view>
<view class="status-line" v-if="reconnectMessage">
<text class="status-label">恢复状态</text>
<text class="status-value" :class="reconnectStatusClass">{{ reconnectMessage }}</text>
</view>
<view class="status-line" v-if="!available">
<text class="status-value status-error">蓝牙未开启,请先打开系统蓝牙</text>
</view>
@ -33,11 +37,16 @@
<view class="btn-row">
<u-button
type="primary"
:disabled="!filterName"
:disabled="!filterName || connectionStatus === 'connecting' || connectionStatus === 'scanning'"
:loading="connectionStatus === 'connecting' || connectionStatus === 'scanning'"
@click="handleConnectByName"
>按名称连接</u-button>
<u-button type="info" :disabled="discovering" @click="handleScan">扫描设备</u-button>
<u-button
type="warning"
:disabled="connectionStatus === 'connected' || connectionStatus === 'connecting' || !available"
@click="handleManualReconnect"
>手动重连</u-button>
<u-button
type="error"
:disabled="connectionStatus !== 'connected'"
@ -143,17 +152,30 @@
statusText() {
return this.$store.getters['bluetoothScale/statusText'];
},
reconnectMessage() {
return this.$store.state.bluetoothScale.reconnectMessage;
},
reconnecting() {
return this.$store.state.bluetoothScale.reconnecting;
},
reconnectStatusClass() {
if (this.reconnecting) return 'status-scanning';
if (this.connectionStatus === 'connected') return 'status-connected';
return 'status-error';
},
weightDisplay() {
return this.weight === null || this.weight === '' ? '--' : this.weight;
}
},
onLoad() {
this.$store.dispatch('bluetoothScale/initialize').catch(() => {});
this.$store.dispatch('bluetoothScale/reconnectIfNeeded').catch(() => {});
// 进入页面时自动扫描一次,直接展示扫描到的设备列表
this.$store.dispatch('bluetoothScale/scanDevices', true).catch(() => {});
},
onUnload() {
// 离开页面时停止扫描并断开连接,释放蓝牙资源
// 仅停止扫描,不在页面卸载时强制断开 BLE 连接,避免重进页面后收不到实时重量
this.$store.dispatch('bluetoothScale/stopScan');
this.$store.dispatch('bluetoothScale/disconnect');
},
methods: {
async handleConnectByName() {
@ -174,6 +196,22 @@
uni.showToast({ title: e.message || '扫描失败', icon: 'none' });
}
},
async handleManualReconnect() {
try {
if (this.currentDevice && this.currentDevice.id) {
await this.$store.dispatch('bluetoothScale/reconnectIfNeeded');
uni.showToast({ title: '正在重连设备...', icon: 'none' });
return;
}
if (!this.filterName) {
uni.showToast({ title: '请先输入电子秤蓝牙名称', icon: 'none' });
return;
}
await this.$store.dispatch('bluetoothScale/connectDeviceByName', this.filterName);
} catch (e) {
uni.showToast({ title: e.message || '重连失败', icon: 'none' });
}
},
async handleDisconnect() {
await this.$store.dispatch('bluetoothScale/disconnect');
uni.showToast({ title: '已断开', icon: 'none' });
@ -276,12 +314,13 @@
.btn-row {
display: flex;
gap: 16rpx;
flex-wrap: wrap;
justify-content: space-between;
margin-bottom: 20rpx;
::v-deep .u-button {
flex: 1;
margin: 0;
width: calc(50% - 12rpx);
margin: 0 0 20rpx 0;
}
}

View File

@ -58,15 +58,145 @@
class="weigh-input"
></u-input>
<text class="info-unit">g</text>
<view
class="scale-read-btn"
:class="{ 'scale-read-btn--connected': isScaleConnected }"
@click="handleReadScale"
>
<text class="scale-read-btn-text">{{ isScaleConnected ? '读秤' : '连秤' }}</text>
</view>
</view>
</view>
</view>
<!-- 蓝牙秤状态栏 -->
<view class="scale-status-card" v-show="showOrderInfo">
<view class="scale-status-line">
<text class="scale-status-label">蓝牙秤</text>
<view class="scale-status-right">
<text class="scale-status-value" :class="'scale-status-' + scaleConnectionStatus">{{ scaleStatusText }}</text>
<text v-if="scaleCurrentDevice" class="scale-device-name">{{ scaleCurrentDevice.name }}</text>
</view>
</view>
<view class="scale-status-line" v-if="isScaleConnected">
<text class="scale-status-label">实时重量</text>
<view class="scale-live-wrap">
<text class="scale-live-value">{{ scaleWeightDisplay }}</text>
<text class="scale-live-unit">g</text>
<text class="scale-live-stable">{{ scaleStable ? '稳定' : '读数中' }}</text>
</view>
</view>
<view class="scale-status-line">
<text class="scale-status-label">自动读秤</text>
<u-switch v-model="autoReadScale" size="20" activeColor="#2979ff"></u-switch>
</view>
<view class="scale-status-line scale-status-actions">
<u-button
v-if="!isScaleConnected"
type="primary"
size="mini"
:customStyle="{ color: '#2979ff', backgroundColor: '#eaf3ff', borderColor: '#b3d8ff' }"
@click="openScalePopup"
>连接蓝牙秤</u-button>
<u-button
v-if="isScaleConnected"
type="error"
size="mini"
:customStyle="{ color: '#fa3534', backgroundColor: '#fef0f0', borderColor: '#fbc4c4' }"
@click="handleScaleDisconnect"
>断开</u-button>
<u-button
v-if="isScaleConnected"
type="info"
size="mini"
:customStyle="{ color: '#909399', backgroundColor: '#f4f4f5', borderColor: '#dcdfe6' }"
@click="openScalePopup"
>设备管理</u-button>
</view>
</view>
<!-- 蓝牙秤连接弹窗 -->
<u-popup :show="showScalePopup" mode="bottom" :closeable="true" round="20" @close="closeScalePopup">
<view class="scale-popup">
<view class="scale-popup-header">
<text class="scale-popup-title">连接蓝牙秤</text>
</view>
<view class="scale-popup-input">
<u-input
v-model="scaleFilterName"
placeholder="电子秤蓝牙名称(完整名称)"
border="surround"
fontSize="32rpx"
></u-input>
<u-button
type="primary"
size="mini"
:disabled="!scaleFilterName"
:loading="scaleConnectionStatus === 'connecting'"
:customStyle="{ width: '200rpx', height: '72rpx', padding: '0', fontSize: '32rpx', flexShrink: '0' }"
@click="handleScaleConnectByName"
>按名称连接</u-button>
</view>
<scroll-view scroll-y class="scale-popup-list" v-if="scaleDevices.length">
<view class="scale-popup-list-inner">
<view
v-for="d in scaleDevices"
:key="d.deviceId"
class="scale-device-item"
:class="{ 'scale-device-item--active': isScaleCurrentDevice(d) }"
@click="handleScaleConnectDevice(d)"
>
<view class="scale-device-info">
<view class="scale-device-name">{{ d.name || '未知设备' }}</view>
<view class="scale-device-id">{{ d.deviceId }}</view>
</view>
<view class="scale-device-connect">{{ isScaleCurrentDevice(d) ? '已连接' : '连接' }}</view>
</view>
</view>
</scroll-view>
<u-empty v-else class="scale-popup-list" mode="list" text="暂无设备,点击扫描"></u-empty>
<view class="scale-popup-actions">
<view class="scale-popup-close-btn" @click="closeScalePopup">关闭</view>
<view
class="scale-popup-scan-btn"
:class="{ 'scale-popup-scan-btn--loading': scaleDiscovering }"
@click="handleScaleScan"
>
<text>{{ scaleDiscovering ? '扫描中...' : '扫描' }}</text>
</view>
</view>
</view>
</u-popup>
<!-- 断开蓝牙秤二次确认弹窗 -->
<u-popup
:show="showDisconnectConfirm"
mode="center"
:closeable="true"
:closeOnClickOverlay="false"
border-radius="20"
@close="cancelScaleDisconnect"
>
<view class="disconnect-confirm-popup">
<view class="disconnect-confirm-popup__title">断开蓝牙秤</view>
<view class="disconnect-confirm-popup__body">
<text class="disconnect-confirm-popup__text">确定要断开当前蓝牙秤连接吗?</text>
</view>
<view class="disconnect-confirm-popup__actions">
<view class="disconnect-confirm-popup__btn disconnect-confirm-popup__btn--cancel" @click="cancelScaleDisconnect">取消</view>
<view class="disconnect-confirm-popup__btn disconnect-confirm-popup__btn--confirm" @click="confirmScaleDisconnect">断开</view>
</view>
</view>
</u-popup>
<!-- 提交按钮 -->
<view class="submit-section" v-show="showOrderInfo">
<u-button
type="primary"
:customStyle="{ backgroundColor: '#2979ff', borderColor: '#2979ff', width: '100%' }"
:customStyle="{ backgroundColor: '#2979ff', borderColor: '#2979ff', width: '100%', fontSize: '36rpx' }"
:disabled="!manualWeight"
:loading="submitting"
@click="handleSubmitWeight"
@ -98,14 +228,66 @@ import voice from '@/core/utils/voice';
weightFocused: false,
submitting: false,
showOrderInfo: false,
isGroupOrder: false
isGroupOrder: false,
showScalePopup: false,
scaleFilterName: '',
autoReadScale: true,
showDisconnectConfirm: false
};
},
computed: {
scaleWeight() {
return this.$store.state.bluetoothScale.weight;
},
scaleWeightUnit() {
return this.$store.state.bluetoothScale.weightUnit;
},
scaleStable() {
return this.$store.state.bluetoothScale.stable;
},
scaleConnectionStatus() {
return this.$store.state.bluetoothScale.connectionStatus;
},
scaleCurrentDevice() {
return this.$store.state.bluetoothScale.currentDevice;
},
scaleDevices() {
return this.$store.state.bluetoothScale.devices;
},
scaleDiscovering() {
return this.$store.state.bluetoothScale.discovering;
},
isScaleConnected() {
return this.scaleConnectionStatus === 'connected';
},
scaleStatusText() {
return this.$store.getters['bluetoothScale/statusText'];
},
scaleWeightDisplay() {
const g = this.scaleWeightInGrams();
return g === '' ? '--' : g;
}
},
watch: {
scaleWeight(val) {
if (!this.autoReadScale || !this.isScaleConnected || val === null || val === undefined) return;
const g = this.scaleWeightInGrams();
if (g === '' || String(g) === this.manualWeight) return;
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weightFocused = false;
this.$nextTick(() => {
this.manualWeight = String(g);
});
}
},
onLoad() {
this.$store.dispatch('broadcast/setCallbacks', {
onResult: this.onScanData
});
this.$store.dispatch('broadcast/start');
// 蓝牙秤:初始化并尝试恢复已有连接
this.$store.dispatch('bluetoothScale/initialize').catch(() => {});
this.$store.dispatch('bluetoothScale/reconnectIfNeeded').catch(() => {});
},
onShow() {
this.$store.dispatch('broadcast/resume');
@ -115,6 +297,7 @@ import voice from '@/core/utils/voice';
},
onUnload() {
this.$store.dispatch('broadcast/stop');
this.$store.dispatch('bluetoothScale/stopScan').catch(() => {});
},
methods: {
onScanData(data) {
@ -301,6 +484,84 @@ import voice from '@/core/utils/voice';
this.showOrderInfo = false;
this.isGroupOrder = false;
this.scanFocused = true;
},
scaleWeightInGrams() {
const raw = this.scaleWeight;
if (raw === null || raw === undefined || raw === '') return '';
const num = Number(raw);
if (isNaN(num)) return '';
const unit = String(this.scaleWeightUnit || '').toLowerCase();
// 仅当单位明确为 g 时才原样返回,其余(kg 或未识别)按 kg ×1000
const grams = unit === 'g' ? num : num * 1000;
return Math.round(grams * 1000) / 1000;
},
openScalePopup() {
this.showScalePopup = true;
this.$store.dispatch('bluetoothScale/scanDevices', true).catch(() => {});
},
closeScalePopup() {
this.showScalePopup = false;
this.$store.dispatch('bluetoothScale/stopScan').catch(() => {});
},
handleScaleScan() {
this.$store.dispatch('bluetoothScale/scanDevices', true).catch(e => {
uni.showToast({ title: (e && e.message) || '扫描失败', icon: 'none' });
});
},
async handleScaleConnectByName() {
if (!this.scaleFilterName) {
uni.showToast({ title: '请输入电子秤蓝牙名称', icon: 'none' });
return;
}
try {
await this.$store.dispatch('bluetoothScale/connectDeviceByName', this.scaleFilterName);
uni.showToast({ title: '连接成功', icon: 'success' });
this.showScalePopup = false;
this.speakVoice('蓝牙秤连接成功');
} catch (e) {
uni.showToast({ title: (e && e.message) || '连接失败', icon: 'none' });
}
},
async handleScaleConnectDevice(device) {
try {
await this.$store.dispatch('bluetoothScale/connectDevice', device);
uni.showToast({ title: '连接成功', icon: 'success' });
this.showScalePopup = false;
this.speakVoice('蓝牙秤连接成功');
} catch (e) {
uni.showToast({ title: (e && e.message) || '连接失败', icon: 'none' });
}
},
handleScaleDisconnect() {
this.showDisconnectConfirm = true;
},
cancelScaleDisconnect() {
this.showDisconnectConfirm = false;
},
async confirmScaleDisconnect() {
this.showDisconnectConfirm = false;
await this.$store.dispatch('bluetoothScale/disconnect').catch(() => {});
uni.showToast({ title: '已断开', icon: 'none' });
},
handleReadScale() {
if (!this.isScaleConnected) {
this.openScalePopup();
return;
}
const grams = this.scaleWeightInGrams();
if (grams === '') {
uni.showToast({ title: '未读取到重量,请确认物品已放上秤', icon: 'none' });
return;
}
// App 端聚焦中的原生 input 不响应数据更新,先失焦再回填
this.weightFocused = false;
this.$nextTick(() => {
this.manualWeight = String(grams);
this.speakVoice('已读取重量');
});
},
isScaleCurrentDevice(device) {
return !!(this.scaleCurrentDevice && device && this.scaleCurrentDevice.id === device.deviceId);
}
}
};
@ -432,27 +693,366 @@ import voice from '@/core/utils/voice';
flex-direction: row;
align-items: center;
display: flex;
gap: 8rpx;
.info-unit {
font-size: 32rpx;
color: #000;
white-space: nowrap;
margin-left: 8rpx;
}
}
.weigh-input {
::v-deep .u-input__content__field-wrapper__field {
font-size: 40rpx !important;
font-size: 56rpx !important;
text-align: center !important;
}
}
}
}
/* ===== 读秤按钮 ===== */
.scale-read-btn {
display: flex;
align-items: center;
justify-content: center;
height: 64rpx;
padding: 0 20rpx;
margin-left: 20rpx;
background: #fa8c16;
border-radius: 8rpx;
flex-shrink: 0;
&--connected {
background: #2979ff;
}
.scale-read-btn-text {
font-size: 30rpx;
color: #fff;
white-space: nowrap;
}
}
/* ===== 蓝牙秤状态栏 ===== */
.scale-status-card {
background: #fff;
margin: 0 24rpx 16rpx;
border-radius: 12rpx;
overflow: hidden;
.scale-status-line {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 24rpx;
border-bottom: 1rpx solid #f0f0f0;
&:last-child {
border-bottom: none;
}
.scale-status-label {
font-size: 32rpx;
color: #333;
}
.scale-status-right {
display: flex;
align-items: center;
.scale-status-value {
font-size: 32rpx;
font-weight: 500;
&.scale-status-connected {
color: #19be6b;
}
&.scale-status-error {
color: #fa3534;
}
&.scale-status-scanning,
&.scale-status-connecting {
color: #2979ff;
}
}
.scale-device-name {
font-size: 34rpx;
color: #999;
margin-left: 12rpx;
}
}
.scale-live-wrap {
display: flex;
align-items: baseline;
.scale-live-value {
font-size: 56rpx;
color: #000000;
}
.scale-live-unit {
font-size: 30rpx;
color: #999;
margin-left: 10rpx;
}
.scale-live-stable {
font-size: 28rpx;
color: #19be6b;
margin-left: 16rpx;
}
}
&.scale-status-actions {
justify-content: flex-start;
::v-deep .u-button {
height: 72rpx;
min-height: 72rpx;
padding: 0 32rpx;
border-radius: 8rpx;
font-size: 32rpx !important;
}
::v-deep .u-button__text {
font-size: 32rpx !important;
}
::v-deep .u-button + .u-button {
margin-left: 16rpx;
}
}
}
}
/* ===== 蓝牙秤连接弹窗 ===== */
.scale-popup {
display: flex;
flex-direction: column;
height: 60vh;
.scale-popup-header {
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 32rpx 0;
.scale-popup-title {
font-size: 38rpx;
font-weight: 600;
color: #303133;
text-align: center;
white-space: nowrap;
}
}
.scale-popup-input {
display: flex;
align-items: center;
padding: 32rpx 32rpx 0;
::v-deep .u-input {
flex: 1;
min-width: 0;
height: 72rpx;
box-sizing: border-box;
padding-top: 0 !important;
padding-bottom: 0 !important;
}
::v-deep .u-button {
margin-left: 16rpx;
flex-shrink: 0;
}
}
.scale-popup-list {
flex: 1;
width: 100%;
box-sizing: border-box;
overflow: hidden;
.scale-popup-list-inner {
padding: 12rpx 32rpx 8rpx;
}
.scale-device-item {
display: flex;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
padding: 28rpx 24rpx;
margin-bottom: 16rpx;
border-radius: 16rpx;
border: 2rpx solid #eee;
background-color: #fff;
&--active {
border-color: #2979ff;
background-color: #f0f7ff;
}
.scale-device-info {
flex: 1;
min-width: 0;
overflow: hidden;
display: flex;
flex-direction: column;
.scale-device-name {
font-size: 36rpx;
color: #333;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.scale-device-id {
font-size: 24rpx;
color: #999;
margin-top: 6rpx;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.scale-device-connect {
flex-shrink: 0;
margin-left: 16rpx;
padding: 12rpx 32rpx;
font-size: 34rpx;
color: #2979ff;
background-color: #eaf3ff;
border-radius: 30rpx;
white-space: nowrap;
}
&--active .scale-device-connect {
color: #19be6b;
background-color: #e8f9f0;
}
}
}
.scale-popup-actions {
display: flex;
align-items: center;
padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
border-top: 1rpx solid #f0f0f0;
}
.scale-popup-close-btn {
flex: 1;
height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 34rpx;
color: #909399;
border: 2rpx solid #dcdfe6;
border-radius: 16rpx;
background: #f5f5f5;
&:active {
opacity: 0.88;
}
}
.scale-popup-scan-btn {
flex: 1;
height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 34rpx;
color: #ffffff;
background: #2979ff;
border: 2rpx solid #2979ff;
border-radius: 16rpx;
margin-left: 20rpx;
&:active {
opacity: 0.9;
}
&--loading {
opacity: 0.6;
pointer-events: none;
}
}
}
/* ===== 提交按钮 ===== */
.submit-section {
padding: 40rpx 24rpx;
}
/* ===== 断开蓝牙秤二次确认弹窗 ===== */
.disconnect-confirm-popup {
width: 640rpx;
padding: 40rpx 32rpx 32rpx;
background: #ffffff;
border-radius: 20rpx;
box-sizing: border-box;
}
.disconnect-confirm-popup__title {
font-size: 42rpx;
font-weight: 600;
color: #303133;
text-align: center;
margin-bottom: 32rpx;
}
.disconnect-confirm-popup__body {
margin-bottom: 36rpx;
padding: 24rpx;
background: #f5f7fa;
border-radius: 12rpx;
}
.disconnect-confirm-popup__text {
font-size: 36rpx;
color: #303133;
line-height: 1.6;
}
.disconnect-confirm-popup__actions {
display: flex;
align-items: center;
}
.disconnect-confirm-popup__btn {
flex: 1;
height: 88rpx;
border-radius: 12rpx;
display: flex;
align-items: center;
justify-content: center;
font-size: 36rpx;
font-weight: 500;
}
.disconnect-confirm-popup__btn + .disconnect-confirm-popup__btn {
margin-left: 20rpx;
}
.disconnect-confirm-popup__btn--cancel {
background: #f5f7fa;
color: #606266;
border: 1rpx solid #dcdfe6;
}
.disconnect-confirm-popup__btn--confirm {
background: #f56c6c;
color: #ffffff;
}
}
</style>