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

@@ -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,