feat:蓝牙绑定和在线客服

This commit is contained in:
李伊帆
2026-10-13 16:23:43 +08:00
parent d4b02745e1
commit e22ebd6bef
128 changed files with 10429 additions and 385 deletions

View File

@@ -1,92 +1,22 @@
import {
mapZ2StateToRuntimePatch,
type Z2AirQuality,
} from '@/utils/z2-ble-protocol'
import { queryZ2BleState } from '@/utils/z2-ble'
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
const SERVICE_UUID = (import.meta.env.VITE_BLE_SERVICE_UUID as string | undefined)?.trim()
const RUNTIME_CHAR_UUID = (import.meta.env.VITE_BLE_RUNTIME_CHARACTERISTIC_UUID as string | undefined)?.trim()
function normalizeUuid(value: string): string {
return value.replace(/-/g, '').toUpperCase()
export type BleRuntimePatch = Partial<UpdateDeviceRuntimeBody> & {
deviceBattery?: number
filterLife?: number
airQuality?: Z2AirQuality
}
function readBleCharacteristic(
deviceId: string,
serviceId: string,
characteristicId: string,
): Promise<ArrayBuffer> {
return new Promise((resolve, reject) => {
const targetService = normalizeUuid(serviceId)
const targetChar = normalizeUuid(characteristicId)
const timeout = setTimeout(() => {
cleanup()
reject(new Error('读取特征值超时'))
}, 5000)
const onValue = (res: UniApp.OnBLECharacteristicValueChangeCallbackResult) => {
if (res.deviceId !== deviceId) return
if (normalizeUuid(res.serviceId) !== targetService) return
if (normalizeUuid(res.characteristicId) !== targetChar) return
cleanup()
resolve(res.value as ArrayBuffer)
}
function cleanup() {
clearTimeout(timeout)
if (typeof uni.offBLECharacteristicValueChange === 'function') {
uni.offBLECharacteristicValueChange(onValue)
}
}
if (typeof uni.onBLECharacteristicValueChange !== 'function') {
reject(new Error('当前环境不支持读取蓝牙特征值'))
return
}
uni.onBLECharacteristicValueChange(onValue)
uni.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId,
success: () => {},
fail: (err) => {
cleanup()
reject(err)
},
})
})
}
function parseRuntimePayload(buffer: ArrayBuffer): Partial<UpdateDeviceRuntimeBody> {
try {
const bytes = new Uint8Array(buffer)
const text = String.fromCharCode(...bytes).trim()
if (!text) return {}
const data = JSON.parse(text) as Record<string, unknown>
const patch: Partial<UpdateDeviceRuntimeBody> = {}
if (data.runMode != null) patch.runMode = String(data.runMode)
if (data.fanLevel != null) patch.fanLevel = String(data.fanLevel)
if (data.tvoc != null) patch.tvoc = Number(data.tvoc)
if (data.powerMode != null) patch.powerMode = String(data.powerMode)
if (data.charging != null) patch.charging = String(data.charging)
if (data.filterTotalDays != null) patch.filterTotalDays = String(data.filterTotalDays)
if (data.filterRemainDays != null) patch.filterRemainDays = String(data.filterRemainDays)
if (data.parkingShutdown != null) patch.parkingShutdown = String(data.parkingShutdown)
return patch
} catch {
return {}
}
}
/** 若配置了 BLE 特征值 UUID,则尝试读取设备运行数据 */
/** 通过 Z2 BLE 协议查询设备运行数据 */
export async function readRuntimeFromBle(
bleDeviceId: string,
): Promise<Partial<UpdateDeviceRuntimeBody>> {
if (!SERVICE_UUID || !RUNTIME_CHAR_UUID) return {}
): Promise<BleRuntimePatch> {
if (typeof uni.readBLECharacteristicValue !== 'function') return {}
try {
const buffer = await readBleCharacteristic(bleDeviceId, SERVICE_UUID, RUNTIME_CHAR_UUID)
return parseRuntimePayload(buffer)
} catch {
return {}
}
const state = await queryZ2BleState(bleDeviceId)
return mapZ2StateToRuntimePatch(state)
}

View File

@@ -1,6 +1,6 @@
/** POST /app/device/runtime 查询参数 */
export interface DeviceRuntimeQueryBody {
deviceId: number
deviceId: string | number
}
/**
@@ -25,11 +25,12 @@ export interface AppDeviceRuntimeVo {
filterLife?: number
filterReplaceTime?: string
parkingShutdown?: string
deviceBattery?: number
}
/** POST /app/device/updateRuntime */
export interface UpdateDeviceRuntimeBody {
deviceId: number
deviceId: string | number
runMode?: string
fanLevel?: string
status?: string
@@ -38,6 +39,7 @@ export interface UpdateDeviceRuntimeBody {
charging?: string
tvoc?: number
powerMode?: string
deviceBattery?: number
filterTotalDays?: string
filterRemainDays?: string
parkingShutdown?: string
@@ -45,8 +47,12 @@ export interface UpdateDeviceRuntimeBody {
export interface DeviceDetailRouteQuery {
deviceId?: string
deviceNo?: string
name?: string
locationName?: string
locationId?: string
homeId?: string
model?: string
status?: string
bluetoothConnected?: string
charging?: string

View File

@@ -59,9 +59,9 @@ export function formatTvocValue(tvoc?: number): string {
}
export function formatTvocLevel(tvoc?: number): string {
const value = tvoc ?? 0
if (value <= 0.3) return '优'
if (value <= 0.6) return '良'
if (tvoc == null) return '--'
if (tvoc <= 0.3) return '优'
if (tvoc <= 0.6) return '良'
return '差'
}

View File

@@ -1,9 +1,8 @@
import { onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
BluetoothError,
closeBleConnection,
createBleConnection,
ensureBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getDiscoveredBluetoothDevices,
@@ -12,20 +11,24 @@ import {
scanForBleDeviceByMac,
subscribeBleConnectionStateChange,
} from '@/utils/bluetooth'
import { mapZ2StateToRuntimePatch } from '@/utils/z2-ble-protocol'
import { clearZ2BleHandleCache, sendZ2BleCommand } from '@/utils/z2-ble'
import { updateDeviceRuntime } from './device-detail.api'
import { readRuntimeFromBle } from './device-bluetooth-read'
import { readRuntimeFromBle, type BleRuntimePatch } from './device-bluetooth-read'
import type { UpdateDeviceRuntimeBody } from './device-detail.types'
const SYNC_INTERVAL_MS = 15000
const SCAN_TIMEOUT_MS = 15000
export interface DeviceBluetoothSyncContext {
getDeviceId: () => number
getDeviceId: () => string | number
getMac: () => string | undefined
getDeviceName?: () => string
getRuntimePatch: () => Partial<UpdateDeviceRuntimeBody>
onBluetoothConnectedChange: (connected: boolean) => void
onSyncTextChange: (text: string) => void
onSynced?: () => void | Promise<void>
onBleRuntimeRead?: (patch: BleRuntimePatch) => void
}
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
@@ -39,7 +42,7 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
context.onSyncTextChange(text)
}
async function reportDisconnected() {
async function reportBleDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
@@ -54,6 +57,22 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
}
}
async function reportDeviceOffline() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try {
await updateDeviceRuntime({
deviceId,
status: '2',
bluetoothConnected: '0',
signalLevel: '0',
})
} catch {
// 上报失败时保留本地状态
}
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
@@ -72,18 +91,24 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
if (syncing.value) return false
syncing.value = true
let connected = false
let targetBleId = bleDeviceId.value
try {
setSyncText('正在连接蓝牙…')
await ensureBluetoothReady()
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
if (!targetBleId) {
foundDevice = await scanForBleDeviceByMac(mac, { timeoutMs: SCAN_TIMEOUT_MS })
const deviceName = context.getDeviceName?.()
foundDevice = await scanForBleDeviceByMac(mac ?? '', {
timeoutMs: SCAN_TIMEOUT_MS,
name: deviceName,
})
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDisconnected()
await reportDeviceOffline()
return false
}
targetBleId = foundDevice.deviceId
@@ -93,22 +118,16 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
foundDevice = discovered.find((item) => item.deviceId === targetBleId) ?? null
}
try {
await createBleConnection(targetBleId)
} catch (err) {
const btErr = err as BluetoothError
if (btErr.errCode !== 10010) throw err
}
if (!targetBleId) {
setSyncText('蓝牙连接异常,请重试')
await reportDisconnected()
return false
}
await ensureBleConnection(targetBleId)
connected = true
context.onBluetoothConnectedChange(true)
setSyncText('正在同步设备数据…')
const blePayload = await readRuntimeFromBle(targetBleId)
if (Object.keys(blePayload).length) {
context.onBleRuntimeRead?.(blePayload)
}
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
@@ -121,28 +140,58 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
signalLevel,
})
setSyncText('刚刚更新 · 数据实时同步中')
if (!Object.keys(blePayload).length) {
setSyncText('蓝牙已连接,等待设备上报数据…')
} else {
setSyncText('刚刚更新 · 数据实时同步中')
}
await context.onSynced?.()
return true
} catch (err) {
setSyncText(getBluetoothErrorMessage(err))
bleDeviceId.value = undefined
await reportDisconnected()
if (!connected) {
bleDeviceId.value = undefined
clearZ2BleHandleCache(targetBleId)
await reportDeviceOffline()
}
return false
} finally {
syncing.value = false
}
}
async function sendBleCommand(command: string): Promise<boolean> {
if (!bleDeviceId.value) {
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
}
}
function startSyncLoop() {
if (active) return
if (!isBluetoothApiSupported()) {
setSyncText('云端数据已加载 · 实时同步请使用 App 或微信小程序')
return
}
active = true
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
bleDeviceId.value = undefined
void reportDisconnected()
void reportBleDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
}
})
@@ -167,8 +216,9 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
bleDeviceId.value = undefined
if (currentBleId) {
clearZ2BleHandleCache(currentBleId)
await closeBleConnection(currentBleId).catch(() => {})
await reportDisconnected()
await reportBleDisconnected()
}
}
@@ -181,5 +231,6 @@ export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
startSyncLoop,
stopSync,
connectAndSync,
sendBleCommand,
}
}

View File

@@ -1,6 +1,8 @@
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { fetchRoomList } from '@/api/location'
import { getErrorMessage } from '@/utils/api-error'
import { parseDeviceId, parseId, sameId } from '@/utils/device-id'
import { fetchDeviceList } from '../device.api'
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
@@ -15,13 +17,27 @@ import {
mapRuntimeToView,
RUN_MODE_OPTIONS,
} from './device-detail.utils'
import {
airQualityToLabel,
airQualityToTvoc,
clampPercent,
encodeFanLevelBleCommand,
encodeRunModeBleCommand,
type Z2AirQuality,
Z2_BLE_CMD,
} from '@/utils/z2-ble-protocol'
import type { BleRuntimePatch } from './device-bluetooth-read'
import { useDeviceBluetoothSync } from './use-device-bluetooth-sync'
export function useDeviceDetail() {
const deviceId = ref(0)
const deviceId = ref('')
const deviceNo = ref('')
const deviceMac = ref<string>()
const deviceName = ref('')
const locationName = ref('客厅')
const locationId = ref('')
const homeId = ref('')
const productModel = ref('CZ-Z2023')
const deviceStatus = ref<string>()
const bluetoothConnected = ref(false)
const charging = ref(false)
@@ -32,6 +48,7 @@ export function useDeviceDetail() {
const runMode = ref<RunMode>('0')
const fanLevel = ref<FanLevel>('0')
const tvoc = ref<number | null>(null)
const airQuality = ref<Z2AirQuality>()
const powerMode = ref('0')
const filterLife = ref(0)
const filterRemainText = ref('预计还可使用 -- 天')
@@ -41,7 +58,10 @@ export function useDeviceDetail() {
const syncText = ref('数据实时同步中')
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
const tvocLevel = computed(() => formatTvocLevel(tvoc.value ?? undefined))
const tvocLevel = computed(() => {
if (airQuality.value) return airQualityToLabel(airQuality.value)
return formatTvocLevel(tvoc.value ?? undefined)
})
const powerModeText = computed(() => formatPowerMode(powerMode.value))
const batteryDisplay = computed(() =>
batteryLevel.value != null ? `${batteryLevel.value}%` : '--',
@@ -58,28 +78,54 @@ export function useDeviceDetail() {
showFanLevelControl.value ? AUTO_FAN_LEVEL_OPTIONS : [],
)
function applyBleRuntime(patch: BleRuntimePatch) {
if (patch.runMode != null) runMode.value = patch.runMode as RunMode
if (patch.fanLevel != null) fanLevel.value = patch.fanLevel as FanLevel
if (patch.airQuality != null) {
airQuality.value = patch.airQuality
tvoc.value = airQualityToTvoc(patch.airQuality) ?? tvoc.value
} else if (patch.tvoc != null) {
tvoc.value = patch.tvoc
}
if (patch.powerMode != null) powerMode.value = patch.powerMode
if (patch.filterLife != null) filterLife.value = patch.filterLife
if (patch.deviceBattery != null) batteryLevel.value = clampPercent(patch.deviceBattery)
if (patch.charging != null) charging.value = patch.charging === '1'
}
function applyRuntime(data: AppDeviceRuntimeVo) {
const view = mapRuntimeToView(data, deviceName.value)
deviceName.value = view.deviceName
runMode.value = view.runMode
fanLevel.value = view.fanLevel
tvoc.value = view.tvoc
if (view.tvoc != null) tvoc.value = view.tvoc
powerMode.value = view.powerMode
filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText
filterReplaced.value = view.filterReplaced
isOnline.value = view.isOnline
if (data.deviceBattery != null) batteryLevel.value = clampPercent(data.deviceBattery)
if (data.status !== undefined) deviceStatus.value = data.status
syncText.value = '刚刚更新 · 数据实时同步中'
}
async function refreshDeviceMeta() {
if (!deviceId.value) return
try {
const list = await fetchDeviceList()
const device = list?.find((item) => item.deviceId === deviceId.value)
const device = list?.find((item) => String(item.deviceId) === deviceId.value)
if (!device) return
if (device.deviceId != null) deviceId.value = String(device.deviceId)
if (device.deviceNo) deviceNo.value = device.deviceNo
if (device.mac) deviceMac.value = device.mac
const parsedLocationId = parseId(device.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
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
}
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
charging.value = device.charging === '1'
if (device.status !== undefined) deviceStatus.value = device.status
@@ -109,6 +155,14 @@ export function useDeviceDetail() {
if (!deviceId.value || updating.value) return
updating.value = true
try {
const bleCmd = patch.runMode != null
? encodeRunModeBleCommand(patch.runMode)
: patch.fanLevel != null
? encodeFanLevelBleCommand(patch.fanLevel)
: undefined
if (bleCmd) {
await sendBleCommand(bleCmd)
}
await updateDeviceRuntime({
deviceId: deviceId.value,
...patch,
@@ -135,7 +189,21 @@ export function useDeviceDetail() {
}
function onSettings() {
uni.showToast({ title: '设备设置功能开发中', icon: 'none' })
if (!deviceId.value) {
uni.showToast({ title: '设备信息不完整', icon: 'none' })
return
}
const q = [
`deviceId=${deviceId.value}`,
...(deviceNo.value ? [`deviceNo=${encodeURIComponent(deviceNo.value)}`] : []),
`name=${encodeURIComponent(deviceName.value)}`,
`locationName=${encodeURIComponent(locationName.value)}`,
...(locationId.value ? [`locationId=${locationId.value}`] : []),
...(homeId.value ? [`homeId=${homeId.value}`] : []),
`model=${encodeURIComponent(productModel.value)}`,
`bluetoothConnected=${bluetoothConnected.value ? '1' : '0'}`,
].join('&')
uni.navigateTo({ url: `/pages/device/settings/index?${q}` })
}
function onFilterReplace() {
@@ -143,18 +211,20 @@ export function useDeviceDetail() {
filterReplaceDialogVisible.value = true
}
function onConfirmFilterReplace() {
async function onConfirmFilterReplace() {
await sendBleCommand(Z2_BLE_CMD.FILTER_RESET)
filterReplaced.value = true
uni.showToast({ title: '操作成功', icon: 'success' })
}
const { startSyncLoop } = useDeviceBluetoothSync({
const { startSyncLoop, sendBleCommand } = useDeviceBluetoothSync({
getDeviceId: () => deviceId.value,
getMac: () => deviceMac.value,
getDeviceName: () => deviceName.value,
getRuntimePatch: () => ({
runMode: runMode.value,
fanLevel: fanLevel.value,
tvoc: tvoc.value ?? undefined,
tvoc: tvoc.value ?? (airQuality.value ? airQualityToTvoc(airQuality.value) : undefined),
powerMode: powerMode.value,
charging: charging.value ? '1' : '0',
}),
@@ -168,19 +238,29 @@ export function useDeviceDetail() {
onSyncTextChange: (text) => {
syncText.value = text
},
onBleRuntimeRead: (patch) => {
applyBleRuntime(patch)
},
onSynced: async () => {
await refreshDeviceMeta()
const data = await fetchDeviceRuntime({ deviceId: deviceId.value })
applyRuntime(data)
},
})
onLoad((query?: DeviceDetailRouteQuery) => {
deviceId.value = Number(query?.deviceId) || 0
deviceId.value = parseDeviceId(query?.deviceId)
if (query?.deviceNo) {
deviceNo.value = decodeURIComponent(String(query.deviceNo))
}
if (query?.name) deviceName.value = decodeURIComponent(String(query.name))
if (query?.locationName) {
locationName.value = decodeURIComponent(String(query.locationName))
}
const parsedLocationId = parseId(query?.locationId)
if (parsedLocationId) locationId.value = parsedLocationId
const parsedHomeId = parseId(query?.homeId)
if (parsedHomeId) homeId.value = parsedHomeId
if (query?.model) productModel.value = decodeURIComponent(String(query.model))
if (query?.status) {
deviceStatus.value = String(query.status)
isOnline.value = query.status === '1'