fix:蓝牙bug解决

This commit is contained in:
李伊帆
2026-10-29 10:09:43 +08:00
parent 91bca314ba
commit 98402548eb
28 changed files with 1018 additions and 186 deletions

View File

@@ -1,20 +1,44 @@
import { onShow } from '@dcloudio/uni-app'
function clearStaleNativeLoading() {
try {
uni.hideLoading()
} catch {
// 部分端无 loading 时 hideLoading 可能抛错,忽略即可
}
}
/**
* 页面再次显示时执行刷新(从子页返回、切换 Tab 等)。
* skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求。
* - skipInitialShow:首屏由 onLoad 加载时设为 true,避免与 onLoad 重复请求
* - 自动清掉残留的原生 showLoading(避免改名等流程的 loading 串到其他页)
* - 短防抖 + 进行中跳过,避免连点返回/快速切页触发重复请求或闪提示
*/
export function usePageShowRefresh(
handler: () => void | Promise<void>,
options?: { skipInitialShow?: boolean },
options?: { skipInitialShow?: boolean; debounceMs?: number },
) {
let skipFirst = Boolean(options?.skipInitialShow)
let inflight = false
let timer: ReturnType<typeof setTimeout> | undefined
const debounceMs = options?.debounceMs ?? 280
onShow(() => {
clearStaleNativeLoading()
if (skipFirst) {
skipFirst = false
return
}
void handler()
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
if (inflight) return
inflight = true
Promise.resolve()
.then(() => handler())
.catch(() => {})
.finally(() => {
inflight = false
})
}, debounceMs)
})
}

View File

@@ -2,7 +2,7 @@
"name" : "虫子智家",
"appid" : "__UNI__925D0CC",
"description" : "",
"versionName" : "1.1.9",
"versionName" : "1.2.2",
"versionCode" : "100",
"transformPx" : false,
/* 5+App特有相关 */

View File

@@ -7,7 +7,6 @@
<text class="device-list__badge-text">{{ onlineCount }} 台在线</text>
</view>
</view>
<text class="device-list__manage" @tap="$emit('manage')">管理 &gt;</text>
</view>
<view class="device-list__grid">
@@ -31,7 +30,6 @@ defineProps<{
}>()
defineEmits<{
manage: []
select: [device: DeviceListItem]
}>()
</script>
@@ -44,7 +42,6 @@ defineEmits<{
.device-list__head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
@@ -72,11 +69,6 @@ defineEmits<{
line-height: 1;
}
.device-list__manage {
font-size: 26rpx;
color: $color-text-secondary;
}
.device-list__grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));

View File

@@ -0,0 +1,126 @@
<template>
<view
v-if="visible"
class="ble-reconnect-loading"
:style="{ top: `${topOffsetPx}px` }"
@tap.stop.prevent
@touchmove.stop.prevent
>
<view class="ble-reconnect-loading__center" @tap.stop.prevent>
<view class="ble-reconnect-loading__spinner" aria-hidden="true">
<view class="ble-reconnect-loading__ring" />
<view class="ble-reconnect-loading__core" />
</view>
<text class="ble-reconnect-loading__title">{{ title }}</text>
<text class="ble-reconnect-loading__desc">{{ desc }}</text>
</view>
</view>
</template>
<script setup lang="ts">
withDefaults(
defineProps<{
visible?: boolean
title?: string
desc?: string
/** 顶部留白(状态栏+导航),保证返回可点 */
topOffsetPx?: number
}>(),
{
visible: false,
title: '设备连接中',
desc: '正在重新连接蓝牙,请靠近设备并稍候',
topOffsetPx: 88,
},
)
</script>
<style lang="scss" scoped>
.ble-reconnect-loading {
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
background: rgba(16, 24, 40, 0.28);
pointer-events: auto;
}
.ble-reconnect-loading__center {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 420rpx;
padding: 48rpx 36rpx 44rpx;
border-radius: 28rpx;
background: #fff;
box-shadow: 0 16rpx 48rpx rgba(16, 24, 40, 0.16);
text-align: center;
}
.ble-reconnect-loading__spinner {
position: relative;
width: 96rpx;
height: 96rpx;
margin-bottom: 28rpx;
}
.ble-reconnect-loading__ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 6rpx solid #e8f8ef;
border-top-color: #21c25e;
animation: ble-reconnect-spin 0.9s linear infinite;
}
.ble-reconnect-loading__core {
position: absolute;
left: 50%;
top: 50%;
width: 18rpx;
height: 18rpx;
margin: -9rpx 0 0 -9rpx;
border-radius: 50%;
background: #21c25e;
opacity: 0.85;
animation: ble-reconnect-pulse 1.2s ease-in-out infinite;
}
.ble-reconnect-loading__title {
font-size: 32rpx;
font-weight: 600;
color: #1a1a1a;
line-height: 1.4;
}
.ble-reconnect-loading__desc {
margin-top: 12rpx;
font-size: 24rpx;
color: #667085;
line-height: 1.5;
}
@keyframes ble-reconnect-spin {
to {
transform: rotate(360deg);
}
}
@keyframes ble-reconnect-pulse {
0%,
100% {
transform: scale(0.85);
opacity: 0.55;
}
50% {
transform: scale(1);
opacity: 1;
}
}
</style>

View File

@@ -1,8 +1,9 @@
import {
mapZ2StateToRuntimePatch,
Z2_BLE_CMD,
type Z2AirQuality,
} from '@/utils/z2-ble-protocol'
import { queryZ2BleState } from '@/utils/z2-ble'
import { queryZ2BleState, sendZ2BleCommand } from '@/utils/z2-ble'
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
@@ -11,12 +12,61 @@ export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
airQuality?: Z2AirQuality
}
/** 通过 Z2 BLE 协议查询设备运行数据 */
function toUpdateRuntimeBody(patch: BleRuntimePatch): Partial<UpdateDeviceRuntimeBody> {
const {
runMode,
fanLevel,
tvoc,
powerMode,
deviceBattery,
filterLife,
charging,
status,
bluetoothConnected,
signalLevel,
} = patch
return {
...(runMode != null ? { runMode } : {}),
...(fanLevel != null ? { fanLevel } : {}),
...(tvoc != null ? { tvoc } : {}),
...(powerMode != null ? { powerMode } : {}),
...(deviceBattery != null ? { deviceBattery } : {}),
...(filterLife != null ? { filterLife } : {}),
...(charging != null ? { charging } : {}),
...(status != null ? { status } : {}),
...(bluetoothConnected != null ? { bluetoothConnected } : {}),
...(signalLevel != null ? { signalLevel } : {}),
}
}
/** 通过 Z2 BLE 协议查询设备运行数据(Q 全量 + I 滤芯,滤芯始终单独查) */
export async function readRuntimeFromBle(
bleDeviceId: string,
): Promise<BleRuntimePatch> {
if (typeof uni.readBLECharacteristicValue !== 'function') return {}
const state = await queryZ2BleState(bleDeviceId)
return mapZ2StateToRuntimePatch(state)
let patch = mapZ2StateToRuntimePatch(state)
// 滤芯衰减靠嵌入式维护,Q 里经常没有;每次同步都发 I,避免一直显示云端旧百分比
try {
const filterState = await sendZ2BleCommand(bleDeviceId, Z2_BLE_CMD.QUERY_FILTER, {
timeoutMs: 4000,
})
const filterPatch = mapZ2StateToRuntimePatch(filterState)
if (filterPatch.filterLife != null) {
patch = { ...patch, filterLife: filterPatch.filterLife }
} else if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
console.log('[Z2 BLE] filter query returned no filterLife', filterState)
}
} catch (err) {
if (import.meta.env.DEV || import.meta.env.VITE_BLE_DEBUG === 'true') {
console.log('[Z2 BLE] filter query failed', err)
}
}
return {
...toUpdateRuntimeBody(patch),
...(patch.airQuality != null ? { airQuality: patch.airQuality } : {}),
}
}

View File

@@ -97,11 +97,26 @@
}
}
.device-detail-hero__status-spinner {
width: 20rpx;
height: 20rpx;
border-radius: 50%;
border: 3rpx solid rgba(255, 255, 255, 0.35);
border-top-color: #fff;
animation: device-detail-status-spin 0.8s linear infinite;
}
.device-detail-hero__status-text {
font-size: 24rpx;
color: rgba(255, 255, 255, 0.92);
}
@keyframes device-detail-status-spin {
to {
transform: rotate(360deg);
}
}
.device-detail-hero__metric-row {
position: relative;
z-index: 1;

View File

@@ -22,6 +22,12 @@
<view class="device-detail-hero__status">
<view
v-if="showReconnectLoading"
class="device-detail-hero__status-spinner"
aria-hidden="true"
/>
<view
v-else
class="device-detail-hero__status-dot"
:class="{ 'device-detail-hero__status-dot--offline': !isOnline }"
/>
@@ -151,6 +157,14 @@
@confirm="onConfirmFilterReplace"
/>
<run-mode-explain-dialog v-model:visible="runModeExplainVisible" />
<!-- 页面居中加载,挡住下方操作区;顶栏返回仍可点 -->
<ble-reconnect-loading
:visible="showReconnectLoading"
:title="reconnectLoadingTitle"
:desc="reconnectLoadingDesc"
:top-offset-px="statusBarHeight + 44"
/>
</view>
</template>
@@ -158,6 +172,7 @@
import { ref } from 'vue'
import { usePageScrollHeight } from '@/hooks/use-page-scroll-height'
import { staticAssets } from '@/utils/static-assets'
import BleReconnectLoading from './components/ble-reconnect-loading/index.vue'
import FilterReplaceDialog from './components/filter-replace-dialog/index.vue'
import RunModeExplainDialog from './components/run-mode-explain-dialog/index.vue'
import { useDeviceDetail } from './use-device-detail'
@@ -168,14 +183,13 @@ const { scrollStyle: detailScrollStyle } = usePageScrollHeight({
})
const runModeExplainVisible = ref(false)
function onOpenRunModeExplain() {
runModeExplainVisible.value = true
}
const {
deviceName,
connectionText,
isOnline,
showReconnectLoading,
reconnectLoadingTitle,
reconnectLoadingDesc,
tvocDisplay,
tvocLevel,
syncText,
@@ -199,6 +213,11 @@ const {
onConfirmFilterReplace,
} = useDeviceDetail()
function onOpenRunModeExplain() {
if (showReconnectLoading.value) return
runModeExplainVisible.value = true
}
function onBack() {
const pages = getCurrentPages()
if (pages.length > 1) {

View File

@@ -1,13 +1,15 @@
import { onShow, onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import { buildBleDeviceName } from '@/utils/ble-device-name'
import { recallBleDeviceId, rememberBleDeviceId } from '@/utils/ble-device-id-cache'
import {
closeBleConnection,
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getConnectedBleDeviceByMac,
getDiscoveredBluetoothDevices,
isBleDeviceConnected,
isBluetoothApiSupported,
rssiToSignalLevel,
scanForBleDeviceByMac,
@@ -20,7 +22,10 @@ import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-rea
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
const SYNC_INTERVAL_MS = 15000
const SCAN_TIMEOUT_MS = 15000
const QUICK_SCAN_MS = 5000
const RETRY_SCAN_MS = 10000
/** 断连事件防抖:避免 create/notify 过程中的瞬时断连触发重连循环 */
const DISCONNECT_CONFIRM_MS = 700
export interface DeviceBluetoothSyncContext {
getDeviceId: () => string | number
@@ -35,17 +40,34 @@ export interface DeviceBluetoothSyncContext {
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
const syncing = ref(false)
const connecting = ref(false)
const bleDeviceId = ref<string>()
let syncTimer: ReturnType<typeof setInterval> | undefined
let disconnectTimer: ReturnType<typeof setTimeout> | undefined
let unsubscribeConnection: (() => void) | undefined
let active = false
let tearingDown = false
let hadSuccessfulSync = false
/** 正在主动建连,忽略期间的断连回调 */
let linking = false
function setSyncText(text: string) {
context.onSyncTextChange(text)
}
function resolveBleBroadcastName(mac: string): string | undefined {
try {
return buildBleDeviceName(mac)
} catch {
return undefined
}
}
function persistBleId(mac: string, id: string) {
bleDeviceId.value = id
rememberBleDeviceId(mac, id)
}
async function reportBleDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
@@ -66,25 +88,70 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
context.onBluetoothConnectedChange(false)
}
async function resolveBleTarget(
mac: string,
preferredBleId?: string,
): Promise<UniApp.BluetoothDeviceInfo | null> {
const connected = await getConnectedBleDeviceByMac(mac)
if (connected) return connected
function clearDisconnectTimer() {
if (disconnectTimer) {
clearTimeout(disconnectTimer)
disconnectTimer = undefined
}
}
if (preferredBleId) {
const discovered = await getDiscoveredBluetoothDevices()
const cached = discovered.find((item) => item.deviceId === preferredBleId)
if (cached) return cached
async function resolveBleTarget(mac: string): Promise<UniApp.BluetoothDeviceInfo | null> {
const bleName = resolveBleBroadcastName(mac)
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
const connected = await getConnectedBleDeviceByMac(mac, {
name: bleName,
preferredBleId,
})
if (connected) {
persistBleId(mac, connected.deviceId)
return connected
}
const deviceName = context.getDeviceName?.()
return scanForBleDeviceByMac(mac, {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
skipCached: !preferredBleId && !hadSuccessfulSync,
if (preferredBleId) {
try {
linking = true
await ensureBleConnection(preferredBleId, { settleMs: 200 })
const after = await getConnectedBleDeviceByMac(mac, {
name: bleName,
preferredBleId,
})
if (after) {
persistBleId(mac, after.deviceId)
return after
}
if (await isBleDeviceConnected(preferredBleId)) {
persistBleId(mac, preferredBleId)
return {
deviceId: preferredBleId,
name: bleName,
localName: bleName,
} as UniApp.BluetoothDeviceInfo
}
} catch {
if (bleDeviceId.value === preferredBleId) bleDeviceId.value = undefined
} finally {
linking = false
}
}
const foundQuick = await scanForBleDeviceByMac(mac, {
timeoutMs: QUICK_SCAN_MS,
name: bleName,
skipCached: false,
})
if (foundQuick) {
persistBleId(mac, foundQuick.deviceId)
return foundQuick
}
const foundRetry = await scanForBleDeviceByMac(mac, {
timeoutMs: RETRY_SCAN_MS,
name: bleName,
skipCached: true,
})
if (foundRetry) persistBleId(mac, foundRetry.deviceId)
return foundRetry
}
async function syncBleData(
@@ -103,16 +170,21 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
hadSuccessfulSync = true
context.onBluetoothConnectedChange(true)
// 先更新本地 UI(含滤芯),再上报云端
context.onBleRuntimeRead?.(blePayload)
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
const {
airQuality: _airQuality,
...bleRuntimeBody
} = blePayload
try {
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
...bleRuntimeBody,
status: '1',
bluetoothConnected: '1',
signalLevel,
@@ -125,6 +197,33 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
return true
}
/** 已连上时只拉数据,绝不重新 createBLEConnection */
async function syncIfAlreadyConnected(mac: string): Promise<boolean | null> {
const bleName = resolveBleBroadcastName(mac)
const preferredBleId = bleDeviceId.value || recallBleDeviceId(mac)
const connected = await getConnectedBleDeviceByMac(mac, {
name: bleName,
preferredBleId,
})
if (!connected) {
if (preferredBleId && await isBleDeviceConnected(preferredBleId)) {
persistBleId(mac, preferredBleId)
try {
return await syncBleData(preferredBleId, null)
} catch {
return null
}
}
return null
}
persistBleId(mac, connected.deviceId)
try {
return await syncBleData(connected.deviceId, connected)
} catch {
return null
}
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
@@ -142,14 +241,21 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false
syncing.value = true
connecting.value = !hadSuccessfulSync
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
let targetBleId = bleDeviceId.value || recallBleDeviceId(mac)
try {
if (connecting.value) {
setSyncText('正在搜索并连接设备…')
}
await ensureBluetoothReady()
foundDevice = await resolveBleTarget(mac, targetBleId)
// 周期同步 / 回前台:链路还在就只读数据,避免反复建连闪断
const quiet = await syncIfAlreadyConnected(mac)
if (quiet != null) return quiet
const foundDevice = await resolveBleTarget(mac)
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
if (!tearingDown) {
@@ -164,18 +270,31 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
persistBleId(mac, targetBleId)
if (!hadSuccessfulSync) {
setSyncText('正在连接蓝牙…')
const alreadyLinked = await isBleDeviceConnected(targetBleId)
if (!alreadyLinked) {
if (!hadSuccessfulSync) {
connecting.value = true
setSyncText('正在连接蓝牙…')
}
linking = true
try {
await ensureBleConnection(targetBleId)
} finally {
linking = false
}
}
await ensureBleConnection(targetBleId)
return await syncBleData(targetBleId, foundDevice)
} catch (err) {
const stillConnected = await getConnectedBleDeviceByMac(mac)
const bleName = resolveBleBroadcastName(mac)
const stillConnected = await getConnectedBleDeviceByMac(mac, {
name: bleName,
preferredBleId: targetBleId,
})
if (stillConnected) {
bleDeviceId.value = stillConnected.deviceId
persistBleId(mac, stillConnected.deviceId)
context.onBluetoothConnectedChange(true)
try {
return await syncBleData(stillConnected.deviceId, stillConnected)
@@ -187,7 +306,6 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
setSyncText(getBluetoothErrorMessage(err))
if (!tearingDown) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId)
if (hadSuccessfulSync) {
hadSuccessfulSync = false
@@ -199,9 +317,35 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
return false
} finally {
syncing.value = false
connecting.value = active && !hadSuccessfulSync && !tearingDown
}
}
async function handleConfirmedDisconnect(disconnectedId: string) {
if (tearingDown || !active) return
const mac = context.getMac()
if (mac) {
const stillConnected = await getConnectedBleDeviceByMac(mac, {
name: resolveBleBroadcastName(mac),
preferredBleId: bleDeviceId.value || disconnectedId,
})
if (stillConnected) {
persistBleId(mac, stillConnected.deviceId)
return
}
if (await isBleDeviceConnected(disconnectedId)) return
}
hadSuccessfulSync = false
reportBleLinkLostLocal()
connecting.value = true
setSyncText('蓝牙已断开,正在尝试重连…')
if (bleDeviceId.value === disconnectedId) bleDeviceId.value = undefined
clearZ2BleHandleCache(disconnectedId)
void reportBleDisconnected()
if (!syncing.value) void connectAndSync()
}
async function sendBleCommand(command: string): Promise<boolean> {
if (!bleDeviceId.value) {
const ok = await connectAndSync()
@@ -215,7 +359,18 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
return true
} catch {
return false
const ok = await connectAndSync()
if (!ok || !bleDeviceId.value) return false
try {
const state = await sendZ2BleCommand(bleDeviceId.value, command)
const runtimePatch = mapZ2StateToRuntimePatch(state)
if (Object.keys(runtimePatch).length) {
context.onBleRuntimeRead?.(runtimePatch)
}
return true
} catch {
return false
}
}
}
@@ -223,37 +378,42 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (active) return
if (!isBluetoothApiSupported()) {
connecting.value = false
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
return
}
active = true
connecting.value = true
setSyncText('正在搜索并连接设备…')
const mac = context.getMac()
if (mac) {
const cached = recallBleDeviceId(mac)
if (cached) bleDeviceId.value = cached
}
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (tearingDown) return
if (tearingDown || !active) return
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
void (async () => {
const mac = context.getMac()
if (mac) {
const stillConnected = await getConnectedBleDeviceByMac(mac)
if (stillConnected) {
bleDeviceId.value = stillConnected.deviceId
return
}
}
bleDeviceId.value = undefined
clearZ2BleHandleCache(res.deviceId)
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
void connectAndSync()
})()
if (res.connected) {
clearDisconnectTimer()
return
}
// 主动建连 / 同步中的瞬时断连忽略,等结束后再判定
if (linking || syncing.value) return
clearDisconnectTimer()
disconnectTimer = setTimeout(() => {
disconnectTimer = undefined
void handleConfirmedDisconnect(res.deviceId)
}, DISCONNECT_CONFIRM_MS)
})
void connectAndSync()
syncTimer = setInterval(() => {
if (syncing.value || tearingDown || linking) return
void connectAndSync()
}, SYNC_INTERVAL_MS)
}
@@ -262,6 +422,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
tearingDown = true
active = false
hadSuccessfulSync = false
connecting.value = false
linking = false
clearDisconnectTimer()
if (syncTimer) {
clearInterval(syncTimer)
syncTimer = undefined
@@ -280,6 +443,11 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
onShow(() => {
try {
uni.hideLoading()
} catch {
// ignore
}
if (!active || tearingDown) return
void connectAndSync()
})
@@ -290,6 +458,7 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
return {
syncing,
connecting,
startSyncLoop,
stopSync,
connectAndSync,

View File

@@ -6,7 +6,7 @@ import { getErrorMessage } from '@/utils/api-error'
import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api'
import { fetchAllDeviceList } from '../device.api'
import { findPatchedDeviceName } from '../device-list-patch'
import { findPatchedDeviceLocation, findPatchedDeviceName } from '../device-list-patch'
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
import {
@@ -50,6 +50,8 @@ export function useDeviceDetail() {
const bluetoothConnected = ref(false)
const charging = ref(false)
const loading = ref(false)
/** 进入详情后、首轮蓝牙连接开始前也展示加载态 */
const awaitingBleStart = ref(true)
const isOnline = computed(() => bluetoothConnected.value)
const runMode = ref<RunMode>('0')
@@ -64,6 +66,8 @@ export function useDeviceDetail() {
const filterReplaceDialogVisible = ref(false)
const batteryLevel = ref<number | null>(null)
let pendingBatteryReading: number | null = null
/** 本页已从蓝牙读到滤芯后,避免云端旧值盖住实时衰减 */
let filterLifeFromBle = false
const syncText = ref('数据实时同步中')
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
@@ -75,13 +79,6 @@ export function useDeviceDetail() {
const batteryDisplay = computed(() =>
batteryLevel.value != null ? `${batteryLevel.value}%` : '--',
)
const connectionText = computed(() =>
formatConnectionText({
status: deviceStatus.value,
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
locationName: locationName.value,
}),
)
const showFanLevelControl = computed(() => isAutoRunMode(runMode.value))
const fanLevelOptions = computed(() =>
showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [],
@@ -135,6 +132,7 @@ export function useDeviceDetail() {
if (patch.powerMode != null) powerMode.value = patch.powerMode
if (patch.filterLife != null) {
filterLife.value = patch.filterLife
filterLifeFromBle = true
updateFilterRemainText()
}
if (patch.deviceBattery != null) applyBatteryLevel(patch.deviceBattery, true)
@@ -148,8 +146,13 @@ export function useDeviceDetail() {
fanLevel.value = view.fanLevel
if (view.tvoc != null) tvoc.value = view.tvoc
powerMode.value = view.powerMode
filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText
// 蓝牙已读到实时滤芯时,不以云端缓存覆盖(否则 15 分钟衰减看不到)
if (!filterLifeFromBle) {
filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText
} else {
updateFilterRemainText()
}
filterReplaced.value = view.filterReplaced
if (data.deviceBattery != null) applyBatteryLevel(data.deviceBattery, false)
if (!bluetoothConnected.value && data.status !== undefined) {
@@ -162,6 +165,11 @@ export function useDeviceDetail() {
const bleConnectedLocally = bluetoothConnected.value
const patchedName = findPatchedDeviceName(deviceId.value)
if (patchedName) deviceName.value = patchedName
const patchedLocation = findPatchedDeviceLocation(deviceId.value)
if (patchedLocation) {
locationId.value = patchedLocation.locationId
locationName.value = patchedLocation.locationName
}
try {
const list = await fetchAllDeviceList()
const device = list?.find((item) => String(item.deviceId) === deviceId.value)
@@ -169,22 +177,34 @@ export function useDeviceDetail() {
if (device.deviceId != null) deviceId.value = String(device.deviceId)
if (device.deviceNo) deviceNo.value = device.deviceNo
if (device.mac) deviceMac.value = device.mac
if (device.name) deviceName.value = device.name
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
// 本地刚改名优先,避免 onShow 刷新用接口旧名称盖回去
if (patchedName && device.name !== patchedName) {
deviceName.value = patchedName
} else if (device.name) {
deviceName.value = device.name
}
const parsedHomeId = parseId(device.homeId)
if (parsedHomeId) homeId.value = parsedHomeId
if (parsedHomeId && parsedLocationId) {
const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched) locationName.value = matched.name
if (patchedLocation) {
// 本地刚切换的房间优先,避免接口短暂延迟把展示盖回旧房间
} else {
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
if (parsedHomeId && parsedLocationId) {
const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched) locationName.value = matched.name
}
}
charging.value = device.charging === '1'
// 详情页连接态以本地 BLE 为准:云端不能把状态打成「已连接」,
// 否则会提前关掉重连加载遮罩(列表/接口常有脏在线态)
if (!bleConnectedLocally) {
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
deviceStatus.value = bluetoothConnected.value
? '1'
: (device.status === '0' ? '0' : '2')
const apiConnected = isBluetoothConnected(device.bluetoothConnected)
if (!apiConnected) {
bluetoothConnected.value = false
deviceStatus.value = device.status === '0' ? '0' : '2'
}
}
} catch {
// 列表刷新失败时保留路由参数状态
@@ -255,17 +275,20 @@ export function useDeviceDetail() {
}
function onSelectRunMode(mode: RunMode) {
if (showReconnectLoading.value) return
if (runMode.value === mode) return
void patchRuntime({ runMode: mode })
}
function onSelectFanLevel(level: FanLevel) {
if (showReconnectLoading.value) return
if (!isAutoRunMode(runMode.value)) return
if (fanLevel.value === level) return
void patchRuntime({ fanLevel: level })
}
function onSettings() {
if (showReconnectLoading.value) return
if (!deviceId.value) {
uni.showToast({ title: '设备信息不完整', icon: 'none' })
return
@@ -284,6 +307,7 @@ export function useDeviceDetail() {
}
function onFilterReplace() {
if (showReconnectLoading.value) return
if (filterReplaced.value) return
filterReplaceDialogVisible.value = true
}
@@ -300,11 +324,16 @@ export function useDeviceDetail() {
}
filterReplaced.value = true
filterLife.value = 100
filterLifeFromBle = true
updateFilterRemainText()
uni.showToast({ title: '操作成功', icon: 'success' })
}
const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({
const {
connecting: bleConnecting,
startSyncLoop,
sendBleCommand,
} = useDeviceBluetoothSync({
getDeviceId: () => deviceId.value,
getMac: () => deviceMac.value,
getDeviceName: () => deviceName.value,
@@ -330,6 +359,33 @@ export function useDeviceDetail() {
},
})
/** 仅离线进入或断线重连时展示;在线进入 / 改名返回不闪遮罩 */
const showReconnectLoading = computed(
() => !bluetoothConnected.value && (awaitingBleStart.value || bleConnecting.value),
)
const reconnectLoadingTitle = computed(() => {
if (/重连/.test(syncText.value)) return '设备重连中'
return '设备连接中'
})
const reconnectLoadingDesc = computed(() => {
const text = syncText.value.trim()
if (text && /连接|搜索|同步|重连/.test(text)) return text
return '正在重新连接蓝牙,请靠近设备并稍候'
})
const connectionText = computed(() => {
if (showReconnectLoading.value) {
return reconnectLoadingTitle.value
}
return formatConnectionText({
status: deviceStatus.value,
bluetoothConnected: bluetoothConnected.value ? '1' : '0',
locationName: locationName.value,
})
})
onLoad((query?: DeviceDetailRouteQuery) => {
deviceId.value = parseDeviceId(query?.deviceId)
if (query?.deviceNo) {
@@ -346,12 +402,19 @@ export function useDeviceDetail() {
if (parsedHomeId) homeId.value = parsedHomeId
if (query?.model) productModel.value = decodeURIComponent(String(query.model))
if (query?.mac) deviceMac.value = decodeURIComponent(String(query.mac))
bluetoothConnected.value = false
deviceStatus.value = '2'
// 以列表带入的在线态为准:在线进入不闪重连遮罩;离线进入才展示连接中
const enteredOnline = isBluetoothConnected(query?.bluetoothConnected)
|| query?.status === '1'
bluetoothConnected.value = enteredOnline
deviceStatus.value = enteredOnline ? '1' : (query?.status === '0' ? '0' : '2')
awaitingBleStart.value = !enteredOnline
charging.value = query?.charging === '1'
void loadRuntime().then(() => {
startSyncLoop()
})
void loadRuntime()
.catch(() => {})
.finally(() => {
startSyncLoop()
awaitingBleStart.value = false
})
})
usePageShowRefresh(() => refreshDeviceMeta(), { skipInitialShow: true })
@@ -360,6 +423,9 @@ export function useDeviceDetail() {
deviceName,
connectionText,
isOnline,
showReconnectLoading,
reconnectLoadingTitle,
reconnectLoadingDesc,
tvocDisplay,
tvocLevel,
syncText,

View File

@@ -1,7 +1,9 @@
import { sameId } from '@/utils/device-id'
import type { DeviceListItem } from './device.types'
/** 设置页改名等本地补丁:首页列表在接口尚未返回新值时也能立刻展示 */
/** 设置页改名 / 换房等本地补丁:接口尚未返回新值时也能立刻展示 */
const namePatches = new Map<string, string>()
const locationPatches = new Map<string, { locationId: string; locationName: string }>()
export function rememberDeviceNamePatch(deviceId: string | number, name: string) {
const id = String(deviceId).trim()
@@ -14,17 +16,105 @@ export function clearDeviceNamePatch(deviceId: string | number) {
namePatches.delete(String(deviceId).trim())
}
export function rememberDeviceLocationPatch(
deviceId: string | number,
locationId: string | number,
locationName: string,
) {
const id = String(deviceId).trim()
const nextId = String(locationId).trim()
const nextName = locationName.trim()
if (!id || !nextId || !nextName) return
locationPatches.set(id, { locationId: nextId, locationName: nextName })
}
export function clearDeviceLocationPatch(deviceId: string | number) {
locationPatches.delete(String(deviceId).trim())
}
export function findPatchedDeviceLocation(
deviceId: string | number | undefined,
): { locationId: string; locationName: string } | undefined {
if (deviceId == null) return undefined
return locationPatches.get(String(deviceId))
}
const ROOM_SELECT_STORAGE_KEY = 'czzj_device_room_selected'
/** 房间页选择结果兜底(部分端 EventChannel 不可靠) */
export function stashRoomSelection(payload: {
deviceId?: string | number
locationId: string | number
name: string
}) {
try {
uni.setStorageSync(ROOM_SELECT_STORAGE_KEY, {
deviceId: payload.deviceId != null ? String(payload.deviceId) : '',
locationId: String(payload.locationId),
name: payload.name.trim(),
at: Date.now(),
})
} catch {
// ignore
}
}
export function consumeRoomSelection(deviceId?: string | number): {
locationId: string
name: string
} | null {
try {
const raw = uni.getStorageSync(ROOM_SELECT_STORAGE_KEY) as {
deviceId?: string
locationId?: string
name?: string
at?: number
} | null
uni.removeStorageSync(ROOM_SELECT_STORAGE_KEY)
if (!raw?.locationId || !raw.name) return null
if (raw.at && Date.now() - raw.at > 60_000) return null
if (deviceId != null && raw.deviceId && String(deviceId) !== String(raw.deviceId)) {
return null
}
return { locationId: String(raw.locationId), name: raw.name }
} catch {
return null
}
}
export function applyDeviceListPatches(devices: DeviceListItem[]): DeviceListItem[] {
if (!namePatches.size) return devices
if (!namePatches.size && !locationPatches.size) return devices
return devices.map((device) => {
if (device.deviceId == null) return device
const patched = namePatches.get(String(device.deviceId))
if (!patched) return device
if (device.name === patched) {
namePatches.delete(String(device.deviceId))
return device
const key = String(device.deviceId)
let next = device
const patchedName = namePatches.get(key)
if (patchedName) {
if (device.name === patchedName) {
namePatches.delete(key)
} else {
next = { ...next, name: patchedName }
}
}
return { ...device, name: patched }
const patchedLocation = locationPatches.get(key)
if (patchedLocation) {
if (sameId(device.locationId, patchedLocation.locationId)) {
locationPatches.delete(key)
if (device.locationName !== patchedLocation.locationName) {
next = { ...next, locationName: patchedLocation.locationName }
}
} else {
next = {
...next,
locationId: patchedLocation.locationId,
locationName: patchedLocation.locationName,
}
}
}
return next
})
}

View File

@@ -3,10 +3,11 @@ const lastSeenAt = new Map<string, number>()
/** 已向云端上报离线的设备,避免轮询重复写库 */
const cloudOfflineReported = new Set<string>()
/** 连续扫描未命中次数达到该值后才判定离线 */
const OFFLINE_AFTER_MISSES = 2
/** 最近一次 BLE 命中后的宽限期(避免切换页面时瞬时扫不到) */
const ONLINE_GRACE_MS = 25_000
/**
* 扫描未命中次数达到该值后判定离线。
* 关机后广播立刻消失,1 次完整扫描未命中即可标离线(不再做长宽限)。
*/
const OFFLINE_AFTER_MISSES = 1
function deviceKey(deviceId: string | number | undefined): string {
return deviceId != null ? String(deviceId) : ''
@@ -26,21 +27,14 @@ export function recordPresenceMiss(deviceId: string | number) {
missCounts.set(key, (missCounts.get(key) ?? 0) + 1)
}
/** 是否应将设备展示为离线(需连续未命中且超出宽限期) */
/** 是否应将设备展示为离线:完整扫描未命中即离线 */
export function shouldMarkDeviceOffline(
deviceId: string | number,
wasOnline = false,
_wasOnline = false,
): boolean {
if (!wasOnline) return true
const key = deviceKey(deviceId)
const misses = missCounts.get(key) ?? 0
if (misses < OFFLINE_AFTER_MISSES) return false
const lastSeen = lastSeenAt.get(key) ?? 0
if (lastSeen && Date.now() - lastSeen < ONLINE_GRACE_MS) return false
return true
return misses >= OFFLINE_AFTER_MISSES
}
export function resetPresenceState(deviceId?: string | number) {
@@ -67,3 +61,7 @@ export function markPresenceOfflineReportedToCloud(deviceId: string | number) {
if (!key) return
cloudOfflineReported.add(key)
}
export function getLastPresenceSeenAt(deviceId: string | number): number {
return lastSeenAt.get(deviceKey(deviceId)) ?? 0
}

View File

@@ -1,6 +1,7 @@
import { buildBleDeviceName } from '@/utils/ble-device-name'
import {
findDeviceInBleScan,
getConnectedBleDeviceByMac,
isBluetoothApiSupported,
scanBluetoothDevices,
} from '@/utils/bluetooth'
@@ -17,7 +18,8 @@ import type { DeviceListItem } from './device.types'
let syncing = false
const PRESENCE_SCAN_MS = 8000
/** 关机后广播马上消失,缩短扫描窗口以便更快判定离线 */
const PRESENCE_SCAN_MS = 4500
const PRESENCE_DEBUG = import.meta.env.DEV
|| import.meta.env.VITE_BLE_DEBUG === 'true'
@@ -35,6 +37,27 @@ function wasDeviceOnlineInCloud(device: DeviceListItem): boolean {
return device.status === '1' && device.bluetoothConnected === '1'
}
function resolveBleName(mac?: string): string | undefined {
if (!mac) return undefined
try {
return buildBleDeviceName(mac)
} catch {
return undefined
}
}
function findDeviceInPresenceScan(
device: DeviceListItem,
scanned: UniApp.BluetoothDeviceInfo[],
): UniApp.BluetoothDeviceInfo | null {
if (!device.mac) return null
return findDeviceInBleScan(
{ mac: device.mac, name: resolveBleName(device.mac) },
scanned,
{ strictName: true },
)
}
function applyPresence(
device: DeviceListItem,
blePresent: boolean,
@@ -103,7 +126,7 @@ function shouldSyncOfflineToCloud(before: DeviceListItem, after: DeviceListItem)
return false
}
/** 通过 BLE 扫描刷新设备在线状态(仅 MAC 精确匹配,不用缓存广播) */
/** 通过 BLE 扫描刷新设备在线状态;扫描未命中即刻离线 */
export async function refreshDevicePresence(
devices: DeviceListItem[],
): Promise<DeviceListItem[]> {
@@ -119,6 +142,17 @@ export async function refreshDevicePresence(
syncing = true
try {
// 先看 GATT 是否仍连接:已断开的在线设备可立刻标离线,不必等完整扫描
const connectedFlags = await Promise.all(
targets.map(async (device) => {
if (!device.mac || !device.isOnline) return false
const connected = await getConnectedBleDeviceByMac(device.mac, {
name: resolveBleName(device.mac),
})
return !!connected
}),
)
const scanned = await scanBluetoothDevices({ timeoutMs: PRESENCE_SCAN_MS })
logPresence('scan result', {
count: scanned.length,
@@ -129,19 +163,19 @@ export async function refreshDevicePresence(
const nextDevices = devices.map((device) => {
if (!device.deviceId) return device
const isTarget = targets.some((item) => sameId(item.deviceId, device.deviceId))
if (!isTarget) return device
const targetIndex = targets.findIndex((item) => sameId(item.deviceId, device.deviceId))
if (targetIndex < 0) return device
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
const present = !!found
const found = findDeviceInPresenceScan(device, scanned)
const gattConnected = connectedFlags[targetIndex]
const present = !!found || gattConnected
logPresence('device presence', {
name: device.name,
mac: device.mac,
present,
foundId: found?.deviceId,
bleName: device.mac ? buildBleDeviceName(device.mac) : '',
found: !!found,
gattConnected,
bleName: resolveBleName(device.mac),
})
const next = applyPresence(device, present)
if (shouldSyncOfflineToCloud(device, next)) {
@@ -152,9 +186,7 @@ export async function refreshDevicePresence(
void Promise.allSettled(
targets.map(async (device) => {
const found = device.mac
? findDeviceInBleScan({ mac: device.mac }, scanned, { strictName: true })
: null
const found = findDeviceInPresenceScan(device, scanned)
if (found) {
await reportPresenceOnlineToCloud(device)
}

View File

@@ -28,6 +28,12 @@ export interface AppDeviceVo {
name?: string
imei?: string
mac?: string
sn?: string
/** 产品主键(绑定时常写入;列表若返回则可据此解析型号) */
productId?: string | number
/** 产品型号,如 CZ-Z2023(OpenAPI 可能未声明,后端可能仍返回) */
model?: string
productName?: string
homeId?: string | number
locationId?: string | number
status?: DeviceStatus | string

View File

@@ -22,7 +22,6 @@
v-if="hasDevices"
:devices="devices"
:online-count="onlineCount"
@manage="onManageDevices"
@select="onSelectDevice"
/>
<view v-else-if="loading" class="device-page__loading">
@@ -81,7 +80,6 @@ const {
onNotify,
onHomeManage,
onSelectHome,
onManageDevices,
onSelectDevice,
} = useDevice()
</script>

View File

@@ -5,12 +5,14 @@ import { createLocation, fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error'
import { parseId, sameId } from '@/utils/device-id'
import type { RoomOption } from '@/types/location'
import { stashRoomSelection } from '../../device-list-patch'
import type { DeviceRoomRouteQuery } from './room.types'
let openerEventChannel: UniApp.EventChannel | undefined
export function useDeviceRoom() {
const homeId = ref('')
const deviceId = ref('')
const selectedLocationId = ref('')
const pendingLocationName = ref<string>()
const roomOptions = ref<RoomOption[]>([])
@@ -20,6 +22,7 @@ export function useDeviceRoom() {
const initialized = ref(false)
function applyQuery(query?: DeviceRoomRouteQuery) {
if (query?.deviceId) deviceId.value = String(query.deviceId)
const locationId = parseId(query?.locationId)
if (locationId) {
selectedLocationId.value = locationId
@@ -124,10 +127,16 @@ export function useDeviceRoom() {
selectedLocationId.value = String(room.locationId)
pendingLocationName.value = room.name
openerEventChannel?.emit('roomSelected', {
const payload = {
locationId: room.locationId,
name: room.name,
}
stashRoomSelection({
deviceId: deviceId.value,
locationId: payload.locationId,
name: payload.name,
})
openerEventChannel?.emit('roomSelected', payload)
uni.navigateBack()
}

View File

@@ -10,7 +10,13 @@ import { fetchRoomList } from '@/api/location'
import { isValidDeviceId, parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchAllDeviceList } from '../device.api'
import { rememberDeviceNamePatch } from '../device-list-patch'
import {
consumeRoomSelection,
findPatchedDeviceLocation,
findPatchedDeviceName,
rememberDeviceLocationPatch,
rememberDeviceNamePatch,
} from '../device-list-patch'
import { isBluetoothConnected } from '../detail/device-detail.utils'
import { unbindDevice, updateDeviceSettings } from './device-settings.api'
@@ -114,21 +120,32 @@ export function useDeviceSettings() {
if (device.deviceNo) deviceNo.value = device.deviceNo
if (device.name) deviceName.value = device.name
const namePatch = findPatchedDeviceName(deviceId.value)
if (namePatch && device.name !== namePatch) {
deviceName.value = namePatch
} else if (device.name) {
deviceName.value = device.name
}
const parsedHomeId = parseId(device.homeId)
if (parsedHomeId) homeId.value = parsedHomeId
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
const locationPatch = findPatchedDeviceLocation(deviceId.value)
if (locationPatch) {
locationId.value = locationPatch.locationId
locationName.value = locationPatch.locationName
} else {
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
if (parsedHomeId && parsedLocationId) {
try {
const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched?.name) locationName.value = matched.name
} catch {
// 房间列表失败时保留当前展示
if (parsedHomeId && parsedLocationId) {
try {
const locations = await fetchRoomList(parsedHomeId)
const matched = locations.find((item) => sameId(item.locationId, parsedLocationId))
if (matched?.name) locationName.value = matched.name
} catch {
// 房间列表失败时保留当前展示
}
}
}
@@ -189,11 +206,21 @@ export function useDeviceSettings() {
async function onConfirmRoom(data: { locationId: string | number; name: string }) {
if (!isValidDeviceId(deviceId.value)) {
locationId.value = String(data.locationId)
locationName.value = data.name
const nextLocationId = String(data.locationId)
const nextLocationName = data.name?.trim() || ''
if (!nextLocationId || !nextLocationName) return
if (sameId(locationId.value, nextLocationId) && locationName.value === nextLocationName) {
return
}
// 先更新 UI,避免返回设置页时 onShow 拉旧数据把展示盖回去
locationId.value = nextLocationId
locationName.value = nextLocationName
if (isValidDeviceId(deviceId.value)) {
rememberDeviceLocationPatch(deviceId.value, nextLocationId, nextLocationName)
}
if (!isValidDeviceId(deviceId.value)) return
if (saving.value) return
saving.value = true
@@ -203,10 +230,8 @@ export function useDeviceSettings() {
await updateDeviceSettings({
deviceId: deviceId.value,
homeId: validHomeId,
locationId: data.locationId,
locationId: nextLocationId,
})
locationId.value = String(data.locationId)
locationName.value = data.name
uni.showToast({ title: '修改成功', icon: 'success' })
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '修改房间失败'), icon: 'none' })
@@ -315,6 +340,11 @@ export function useDeviceSettings() {
async function reloadFromServer() {
const pendingRoom = consumeRoomSelection(deviceId.value)
if (pendingRoom) {
// 仅消费房间选择结果;已与当前一致则不再请求/弹 toast
await onConfirmRoom(pendingRoom)
}
await syncDeviceFromList()
homeId.value = await resolveValidHomeId(homeId.value)
}

View File

@@ -30,8 +30,8 @@ import {
mapDeviceItem,
} from './device.utils'
/** 与设备详情页 BLE 同步间隔一致 */
const PRESENCE_INTERVAL_MS = 15000
/** 在线态轮询:缩短以便关机后尽快变为离线 */
const PRESENCE_INTERVAL_MS = 8000
const DEFAULT_HOT_DEVICES: HotDeviceItem[] = [
{
@@ -202,10 +202,16 @@ export function useDevice() {
}
onShow(() => {
try {
uni.hideLoading()
} catch {
// ignore
}
if (!getStoredToken()) {
uni.reLaunch({ url: '/pages/login/index' })
return
}
// 已有列表时静默刷新,避免改名返回首页再闪「加载中」
void loadDevices(devices.value.length > 0)
void refreshUnreadMessageCount()
startPresencePolling()
@@ -268,10 +274,6 @@ export function useDevice() {
uni.navigateTo({ url: '/pages/device/home-manage/index' })
}
function onManageDevices() {
uni.showToast({ title: '设备管理功能开发中', icon: 'none' })
}
function onSelectDevice(device: DeviceListItem) {
if (!device.deviceId) {
uni.showToast({ title: '设备信息不完整', icon: 'none' })
@@ -315,7 +317,6 @@ export function useDevice() {
onNotify,
onHomeManage,
onSelectHome,
onManageDevices,
onSelectDevice,
loadDevices,
}

View File

@@ -67,9 +67,10 @@
@tap="onItemTap(row.raw)"
>
<view class="notify-page__thumb-wrap">
<view
<image
class="notify-page__thumb"
:style="{ backgroundImage: `url(${staticAssets.logo})` }"
:src="staticAssets.logo"
mode="aspectFit"
/>
<view v-if="row.unread" class="notify-page__thumb-dot" />
</view>

View File

@@ -131,9 +131,8 @@
height: 96rpx;
border-radius: 12rpx;
background-color: #f2f4f7;
background-repeat: no-repeat;
background-position: center;
background-size: 72%;
padding: 12rpx;
box-sizing: border-box;
}
.notify-page__thumb-dot {

View File

@@ -1,5 +1,9 @@
import type { AppMessageVo } from '@/types/message'
import { buildMessageFromPush, normalizeMessageId } from '@/utils/message-push'
import {
buildMessageFromPush,
correctPowerNotifyText,
normalizeMessageId,
} from '@/utils/message-push'
import { sameId } from '@/utils/device-id'
export { buildMessageFromPush, normalizeMessageId }
@@ -47,3 +51,9 @@ export function formatNotifyTime(message: AppMessageVo): string {
return formatNotifyDateTime(date)
}
export function formatNotifyContent(message: AppMessageVo): string {
const raw = message.content?.trim()
if (!raw) return '暂无详情'
return correctPowerNotifyText(raw)
}

View File

@@ -19,6 +19,7 @@ import {
import type { AppMessageVo } from '@/types/message'
import type { AppHomeVo } from '@/types/location'
import {
formatNotifyContent,
formatNotifyLocation,
formatNotifyTime,
isUnreadMessage,
@@ -76,7 +77,7 @@ export function useNotify() {
title: item.deviceName || item.title || '系统通知',
timeText: formatNotifyTime(item),
locationText: formatNotifyLocation(item),
content: item.content || '暂无详情',
content: formatNotifyContent(item),
unread: isUnreadMessage(item),
}
}),

View File

@@ -1,7 +1,12 @@
import type { ProductOption } from '@/pages/add-device/complete/complete.types'
import type { AppDeviceVo } from '@/pages/device/device.types'
import { resolveDeviceListOnline } from '@/pages/device/device-online'
import { sameId } from '@/utils/device-id'
import type { SupportConsultDeviceItem } from './support-device-consult.types'
/** 与设备详情/设置页一致的默认型号 */
const DEFAULT_PRODUCT_MODEL = 'CZ-Z2023'
function formatSnSegment(value: string): string {
const compact = value.replace(/[^a-zA-Z0-9]/g, '').toUpperCase()
if (compact.length >= 8) {
@@ -11,24 +16,56 @@ function formatSnSegment(value: string): string {
}
function resolveSn(device: AppDeviceVo): string {
const raw = device.deviceNo?.trim() || device.mac?.trim() || device.imei?.trim()
const raw = device.sn?.trim()
|| device.deviceNo?.trim()
|| device.mac?.trim()
|| device.imei?.trim()
if (raw) return formatSnSegment(raw)
if (device.deviceId != null) return String(device.deviceId)
return '--'
}
/** 列表无产品型号字段时,用设备名后缀或默认占位 */
function resolveModelLabel(device: AppDeviceVo): string {
/**
* 解析展示用型号:
* 1) 列表字段 model / productName
* 2) productId 对照产品目录
* 3) 设备名中的 CZ-Z2023 形态后缀
* 4) 目录仅一项 / 首项 / 应用默认
*/
export function resolveModelLabel(
device: AppDeviceVo,
products: ProductOption[] = [],
): string {
const fromApi = device.model?.trim() || device.productName?.trim()
if (fromApi) return fromApi
if (device.productId != null && device.productId !== '') {
const matched = products.find((item) => sameId(item.productId, device.productId))
const byProduct = matched?.model?.trim() || matched?.name?.trim()
if (byProduct) return byProduct
}
const name = device.name?.trim() || ''
const match = name.match(/\b([A-Z]{1,3}[- ]?[A-Z0-9]{2,})\b/i)
if (match?.[1]) return match[1].replace(/\s+/g, '-')
return '--'
// 仅认带连字符的型号(如 CZ-Z2023),避免把 Z2_A_xxx 蓝牙名误当成型号
const match = name.match(/\b([A-Z]{1,4}-\s?[A-Z0-9]{2,})\b/i)
if (match?.[1]) return match[1].replace(/\s+/g, '')
if (products.length === 1) {
const sole = products[0].model?.trim() || products[0].name?.trim()
if (sole) return sole
}
const first = products[0]?.model?.trim() || products[0]?.name?.trim()
return first || DEFAULT_PRODUCT_MODEL
}
export function mapVoToConsultDevice(device: AppDeviceVo): SupportConsultDeviceItem | null {
export function mapVoToConsultDevice(
device: AppDeviceVo,
products: ProductOption[] = [],
): SupportConsultDeviceItem | null {
if (device.deviceId == null || device.deviceId === '') return null
const name = device.name?.trim() || '未命名设备'
const modelText = resolveModelLabel(device)
const modelText = resolveModelLabel(device, products)
const snText = resolveSn(device)
return {
deviceId: String(device.deviceId),

View File

@@ -1,4 +1,6 @@
import { computed, ref } from 'vue'
import { fetchProductOptions } from '@/pages/add-device/complete/complete.api'
import type { ProductOption } from '@/pages/add-device/complete/complete.types'
import { fetchAllDeviceList } from '@/pages/device/device.api'
import { getErrorMessage } from '@/utils/api-error'
import type { SupportConsultDeviceItem } from './support-device-consult.types'
@@ -13,6 +15,7 @@ export function useSupportDeviceConsult() {
const keyword = ref('')
const devices = ref<SupportConsultDeviceItem[]>([])
const selectedDeviceId = ref('')
const productOptions = ref<ProductOption[]>([])
const filteredDevices = computed(() => {
const list = devices.value
@@ -26,9 +29,13 @@ export function useSupportDeviceConsult() {
async function loadDevices() {
loading.value = true
try {
const rows = await fetchAllDeviceList() ?? []
const [rows, products] = await Promise.all([
fetchAllDeviceList().then((list) => list ?? []),
fetchProductOptions().catch(() => [] as ProductOption[]),
])
productOptions.value = products
devices.value = rows
.map((item) => mapVoToConsultDevice(item))
.map((item) => mapVoToConsultDevice(item, products))
.filter((item): item is SupportConsultDeviceItem => Boolean(item))
if (!selectedDeviceId.value && devices.value.length) {
selectedDeviceId.value = devices.value[0].deviceId

View File

@@ -0,0 +1,51 @@
import { compactMacAddress } from '@/utils/bluetooth'
const STORAGE_KEY = 'czzj_ble_device_id_by_mac'
const memory = new Map<string, string>()
function macKey(mac: string): string {
return compactMacAddress(mac)
}
function readStorage(): Record<string, string> {
try {
const raw = uni.getStorageSync(STORAGE_KEY)
if (raw && typeof raw === 'object') return raw as Record<string, string>
} catch {
// ignore
}
return {}
}
function writeStorage(map: Record<string, string>) {
try {
uni.setStorageSync(STORAGE_KEY, map)
} catch {
// ignore
}
}
/** 记住 MAC → 系统 ble deviceId(尤其 iOS UUID),加速二次重连 */
export function rememberBleDeviceId(mac: string, bleDeviceId: string) {
const key = macKey(mac)
const id = bleDeviceId.trim()
if (!key || key.length !== 12 || !id) return
memory.set(key, id)
const stored = readStorage()
if (stored[key] === id) return
stored[key] = id
writeStorage(stored)
}
export function recallBleDeviceId(mac: string): string | undefined {
const key = macKey(mac)
if (!key) return undefined
const fromMem = memory.get(key)
if (fromMem) return fromMem
const fromStore = readStorage()[key]
if (fromStore) {
memory.set(key, fromStore)
return fromStore
}
return undefined
}

View File

@@ -244,15 +244,41 @@ function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/** 建立 BLE 连接;若设备已连接则视为成功 */
export async function ensureBleConnection(bleDeviceId: string): Promise<void> {
/** 指定 deviceId 是否已在系统已连接列表中 */
export async function isBleDeviceConnected(bleDeviceId: string): Promise<boolean> {
if (!bleDeviceId || typeof uni.getConnectedBluetoothDevices !== 'function') return false
try {
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
uni.getConnectedBluetoothDevices({
success: resolve,
fail: reject,
})
})
return (res.devices ?? []).some((item) => item.deviceId === bleDeviceId)
} catch {
return false
}
}
/**
* 建立 BLE 连接;已连接则直接返回,避免重复 createBLEConnection
*(部分机型对已连接设备再 create 会闪断,导致连上又断开的循环)
*/
export async function ensureBleConnection(
bleDeviceId: string,
options: { settleMs?: number } = {},
): Promise<void> {
if (await isBleDeviceConnected(bleDeviceId)) return
try {
await createBleConnection(bleDeviceId)
} catch (err) {
if (!isBleAlreadyConnectedError(err)) throw err
return
}
// Android / 微信小程序连接后 GATT 表需短暂就绪
await delay(400)
const settleMs = options.settleMs ?? 280
if (settleMs > 0) await delay(settleMs)
}
export function createBleConnection(bleDeviceId: string): Promise<void> {
@@ -305,13 +331,16 @@ export async function releaseBleDevice(bleDeviceId?: string): Promise<void> {
await closeBleConnection(bleDeviceId).catch(() => {})
}
/** 从系统已连接 BLE 列表中按 MAC 查找(GATT 已连接时扫描往往找不到设备) */
/** 从系统已连接 BLE 列表中按 MAC / 广播名 / 已知 deviceId 查找 */
export async function getConnectedBleDeviceByMac(
mac: string,
options: { name?: string; preferredBleId?: string } = {},
): Promise<UniApp.BluetoothDeviceInfo | null> {
if (typeof uni.getConnectedBluetoothDevices !== 'function') return null
const normalizedMac = normalizeMacAddress(mac)
if (!normalizedMac) return null
const targetName = options.name?.trim()
const preferredBleId = options.preferredBleId?.trim()
if (!normalizedMac && !targetName && !preferredBleId) return null
try {
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
@@ -321,7 +350,10 @@ export async function getConnectedBleDeviceByMac(
})
})
for (const device of res.devices ?? []) {
if (deviceMatchesMac(device, normalizedMac)) return device
if (preferredBleId && device.deviceId === preferredBleId) return device
if (normalizedMac && deviceMatchesMac(device, normalizedMac)) return device
// iOS deviceId 非 MAC,需靠标准广播名识别
if (targetName && deviceMatchesName(device, targetName)) return device
}
} catch {
// ignore
@@ -376,7 +408,12 @@ export async function scanForBleDeviceByMac(
matched = device
return true
}
if (!normalizedMac && targetName && deviceMatchesName(device, targetName)) {
// 有 MAC 时也按广播名匹配(iOS deviceId 是 UUID)
if (targetName && deviceMatchesNameStrict(device, targetName)) {
matched = device
return true
}
if (targetName && deviceMatchesName(device, targetName)) {
matched = device
return true
}
@@ -458,7 +495,7 @@ export async function scanBluetoothDevices(
return [...collected.values()]
}
/** 在扫描结果中匹配设备(有 MAC 时仅按 MAC 匹配) */
/** 在扫描结果中匹配设备(优先 MAC;iOS 无 MAC 命中时回退广播名) */
export function findDeviceInBleScan(
target: { mac?: string; name?: string },
scanned: UniApp.BluetoothDeviceInfo[],
@@ -471,7 +508,6 @@ export function findDeviceInBleScan(
for (const device of scanned) {
if (deviceMatchesMac(device, normalizedMac)) return device
}
return null
}
if (!targetName) return null

View File

@@ -104,11 +104,36 @@ export function decodeSocketMessageData(data: unknown): string {
return ''
}
/**
* 纠正开关机文案(后端推送/落库与实际事件相反)。
* 仅替换明确的开关机短语,其它通知原文展示。
*/
export function correctPowerNotifyText(text: string): string {
const value = text.trim()
if (!value) return value
if (value === '设备已关机') return '设备已开机'
if (value === '设备已开机') return '设备已关机'
if (value === '已关机') return '已开机'
if (value === '已开机') return '已关机'
if (/设备已关机/.test(value) && !/设备已开机/.test(value)) {
return value.replace(/设备已关机/g, '设备已开机')
}
if (/设备已开机/.test(value) && !/设备已关机/.test(value)) {
return value.replace(/设备已开机/g, '设备已关机')
}
return value
}
export function getMessagePushToastText(payload: MessagePushPayload): string | null {
const title = payload.title?.trim()
// 标题若是开关机文案也需纠正;设备名标题保持原样
if (title && /开机|关机/.test(title)) return correctPowerNotifyText(title)
if (title) return title
const content = payload.content?.trim()
if (content) return content.length > 30 ? `${content.slice(0, 30)}...` : content
if (content) {
const fixed = correctPowerNotifyText(content)
return fixed.length > 30 ? `${fixed.slice(0, 30)}...` : fixed
}
if (payload.messageId || payload.alertId) return '您有新消息'
return null
}

View File

@@ -234,13 +234,28 @@ function parseBatteryValue(value: string): number | undefined {
return undefined
}
/**
* 滤芯寿命:0-100 直接用;0-1000 为十分之一精度。
* 用 floor 而不是 round,避免 1000→999 仍显示 100%(嵌入式约 15 分钟掉一格时界面看起来不变)。
*/
function parseFilterLifeValue(value: string): number | undefined {
const matched = value.trim().match(/^(\d{1,4})$/)
if (!matched) return undefined
const raw = Number(matched[1])
if (!Number.isFinite(raw)) return undefined
if (raw <= 100) return clampPercent(raw)
if (raw <= 1000) return clampPercent(Math.floor(raw / 10))
return undefined
}
/** 解析单行 Notify,如 `Q;M=L;W=C;A=G` 或 `B=34;P=B` */
export function parseZ2NotifyLine(line: string): Partial<Z2DeviceState> {
const patch: Partial<Z2DeviceState> = {}
const segments = line.split(';').filter(Boolean)
for (const segment of segments) {
if (segment === 'Q') continue
// 指令回显(无数值)跳过
if (segment === 'Q' || segment === 'I' || segment === 'F') continue
const eqIndex = segment.indexOf('=')
if (eqIndex <= 0) continue
@@ -272,15 +287,26 @@ export function parseZ2NotifyLine(line: string): Partial<Z2DeviceState> {
if (Number.isFinite(tempState)) patch.tempState = tempState
break
}
case 'F':
patch.fan = mapFanCode(value)
case 'F': {
// F=L/M/H/S 为风速;F=数字 为滤芯寿命(部分固件)
const fan = mapFanCode(value)
if (fan != null) {
patch.fan = fan
} else {
const filterLife = parseFilterLifeValue(value)
if (filterLife != null) patch.filterLife = filterLife
}
break
}
case 'E':
patch.plasma = value === '1'
break
case 'I':
// 查询滤芯指令 I 的应答:I=xx
case 'FL':
case 'FILTER': {
const filterLife = parseBatteryValue(value)
case 'FILTER':
case 'LIFE': {
const filterLife = parseFilterLifeValue(value)
if (filterLife != null) patch.filterLife = filterLife
break
}
@@ -310,6 +336,15 @@ export function parseZ2NotifyPayload(lines: string[]): Z2DeviceState {
batteryFromMainLine = patch.battery
}
state = mergeZ2DeviceState(state, patch)
// 滤芯查询 I 可能只回裸数字,如 `98` / `980`
if (state.filterLife == null) {
const bare = record.trim().match(/^(\d{1,4})$/)
if (bare) {
const filterLife = parseFilterLifeValue(bare[1])
if (filterLife != null) state.filterLife = filterLife
}
}
}
}

View File

@@ -434,6 +434,11 @@ export async function queryZ2BleState(deviceId: string): Promise<Z2DeviceState>
return sendZ2BleCommand(deviceId, 'Q', { timeoutMs: 6000 })
}
/** 查询滤芯寿命(发送 I) */
export async function queryZ2BleFilterLife(deviceId: string): Promise<Z2DeviceState> {
return sendZ2BleCommand(deviceId, 'I', { timeoutMs: 4000 })
}
/** 蓝牙改名(Notify 回报 S 阶段 / R 结果 / C 字节数) */
export async function sendZ2BleRenameCommand(
deviceId: string,