feat:绑定设备和设备详情

This commit is contained in:
李伊帆
2026-10-10 11:11:44 +08:00
parent 179bd3b66c
commit d4b02745e1
64 changed files with 3526 additions and 221 deletions

View File

@@ -0,0 +1,115 @@
<template>
<view v-if="visible" class="filter-replace-dialog">
<view class="filter-replace-dialog__mask" @tap="onCancel" />
<view class="filter-replace-dialog__panel" @tap.stop>
<text class="filter-replace-dialog__title">提示</text>
<text class="filter-replace-dialog__message">确认已更换新滤芯?</text>
<view class="filter-replace-dialog__footer">
<view class="filter-replace-dialog__btn" @tap.stop="onCancel">
<text class="filter-replace-dialog__btn-text">取消</text>
</view>
<view class="filter-replace-dialog__divider-v" />
<view class="filter-replace-dialog__btn" @tap.stop="onConfirm">
<text class="filter-replace-dialog__btn-text filter-replace-dialog__btn-text--primary">
确定
</text>
</view>
</view>
</view>
</view>
</template>
<script setup lang="ts">
defineProps<{
visible: boolean
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
confirm: []
}>()
function onCancel() {
emit('update:visible', false)
}
function onConfirm() {
emit('confirm')
emit('update:visible', false)
}
</script>
<style lang="scss" scoped>
.filter-replace-dialog {
position: fixed;
inset: 0;
z-index: 500;
display: flex;
align-items: center;
justify-content: center;
}
.filter-replace-dialog__mask {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.55);
}
.filter-replace-dialog__panel {
position: relative;
width: 560rpx;
background: #fff;
border-radius: 24rpx;
overflow: hidden;
z-index: 1;
}
.filter-replace-dialog__title {
display: block;
padding: 48rpx 40rpx 24rpx;
font-size: 34rpx;
font-weight: 600;
color: $color-text;
text-align: center;
line-height: 1.3;
}
.filter-replace-dialog__message {
display: block;
padding: 0 40rpx 48rpx;
font-size: 30rpx;
color: $color-text-secondary;
text-align: center;
line-height: 1.5;
}
.filter-replace-dialog__footer {
display: flex;
align-items: stretch;
border-top: 1rpx solid #ebedf0;
}
.filter-replace-dialog__btn {
flex: 1;
height: 96rpx;
display: flex;
align-items: center;
justify-content: center;
}
.filter-replace-dialog__divider-v {
width: 1rpx;
background: #ebedf0;
}
.filter-replace-dialog__btn-text {
font-size: 32rpx;
color: $color-text;
line-height: 1;
}
.filter-replace-dialog__btn-text--primary {
color: #21c25e;
font-weight: 500;
}
</style>

View File

@@ -0,0 +1,210 @@
<template>
<view v-if="visible" class="run-mode-explain-dialog">
<view class="run-mode-explain-dialog__mask" @tap="onClose" />
<view class="run-mode-explain-dialog__panel" @tap.stop>
<view class="run-mode-explain-dialog__header">
<text class="run-mode-explain-dialog__title">模式说明</text>
<view class="run-mode-explain-dialog__close" @tap.stop="onClose">
<text class="run-mode-explain-dialog__close-icon">×</text>
</view>
</view>
<scroll-view class="run-mode-explain-dialog__scroll" scroll-y>
<text class="run-mode-explain-dialog__intro">
该模式用于在停车断电场景下,兼顾消杀效果与电池寿命保护,规则如下:
</text>
<view class="run-mode-explain-dialog__card run-mode-explain-dialog__card--car">
<view class="run-mode-explain-dialog__card-head">
<text class="run-mode-explain-dialog__tag run-mode-explain-dialog__tag--car">车载</text>
<text class="run-mode-explain-dialog__card-title run-mode-explain-dialog__card-title--car">
USB 断电后电池消杀
</text>
</view>
<text class="run-mode-explain-dialog__card-desc run-mode-explain-dialog__card-desc--car">
USB 断电后,由电池继续供电消杀 5 分钟,随后自动关机。
</text>
</view>
<view class="run-mode-explain-dialog__card run-mode-explain-dialog__card--desk">
<view class="run-mode-explain-dialog__card-head">
<text class="run-mode-explain-dialog__tag run-mode-explain-dialog__tag--desk">桌面</text>
<text class="run-mode-explain-dialog__card-title run-mode-explain-dialog__card-title--desk">
低电量保护策略
</text>
</view>
<text class="run-mode-explain-dialog__card-desc run-mode-explain-dialog__card-desc--desk">
电量&lt;10%时停止消杀,仅保留基础净化。
</text>
<text
class="run-mode-explain-dialog__card-desc run-mode-explain-dialog__card-desc--desk run-mode-explain-dialog__card-desc--gap"
>
电量&lt;5%时整机锁关机,防止电池过放。
</text>
</view>
</scroll-view>
</view>
</view>
</template>
<script setup lang="ts">
defineProps<{
visible: boolean
}>()
const emit = defineEmits<{
'update:visible': [value: boolean]
}>()
function onClose() {
emit('update:visible', false)
}
</script>
<style lang="scss" scoped>
.run-mode-explain-dialog {
position: fixed;
inset: 0;
z-index: 500;
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 40rpx;
box-sizing: border-box;
}
.run-mode-explain-dialog__mask {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.55);
}
.run-mode-explain-dialog__panel {
position: relative;
z-index: 1;
width: 100%;
max-width: 640rpx;
max-height: 80vh;
background: #fff;
border-radius: 24rpx;
padding: 36rpx 32rpx 32rpx;
box-sizing: border-box;
overflow: hidden;
}
.run-mode-explain-dialog__header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 24rpx;
}
.run-mode-explain-dialog__title {
font-size: 34rpx;
font-weight: 600;
color: $color-text;
line-height: 1.3;
}
.run-mode-explain-dialog__close {
width: 56rpx;
height: 56rpx;
display: flex;
align-items: center;
justify-content: center;
}
.run-mode-explain-dialog__close-icon {
font-size: 44rpx;
line-height: 1;
color: #999;
font-weight: 300;
}
.run-mode-explain-dialog__scroll {
max-height: calc(80vh - 140rpx);
}
.run-mode-explain-dialog__intro {
display: block;
font-size: 28rpx;
color: $color-text-secondary;
line-height: 1.6;
margin-bottom: 28rpx;
}
.run-mode-explain-dialog__card {
border-radius: 16rpx;
padding: 24rpx;
margin-bottom: 20rpx;
border-width: 2rpx;
border-style: solid;
}
.run-mode-explain-dialog__card--car {
background: #f3fbf6;
border-color: #b8e8cc;
}
.run-mode-explain-dialog__card--desk {
background: #fffbf2;
border-color: #f0d9a8;
}
.run-mode-explain-dialog__card-head {
display: flex;
align-items: center;
gap: 12rpx;
margin-bottom: 16rpx;
flex-wrap: wrap;
}
.run-mode-explain-dialog__tag {
padding: 4rpx 14rpx;
border-radius: 8rpx;
font-size: 24rpx;
color: #fff;
line-height: 1.4;
font-weight: 500;
}
.run-mode-explain-dialog__tag--car {
background: #21c25e;
}
.run-mode-explain-dialog__tag--desk {
background: #e6a23c;
}
.run-mode-explain-dialog__card-title {
font-size: 28rpx;
font-weight: 600;
line-height: 1.4;
}
.run-mode-explain-dialog__card-title--car {
color: #21c25e;
}
.run-mode-explain-dialog__card-title--desk {
color: #c58a1a;
}
.run-mode-explain-dialog__card-desc {
display: block;
font-size: 26rpx;
line-height: 1.65;
}
.run-mode-explain-dialog__card-desc--car {
color: #2d9f5f;
}
.run-mode-explain-dialog__card-desc--desk {
color: #8a6a2e;
}
.run-mode-explain-dialog__card-desc--gap {
margin-top: 8rpx;
}
</style>

View File

@@ -0,0 +1,92 @@
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()
}
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,则尝试读取设备运行数据 */
export async function readRuntimeFromBle(
bleDeviceId: string,
): Promise<Partial<UpdateDeviceRuntimeBody>> {
if (!SERVICE_UUID || !RUNTIME_CHAR_UUID) return {}
if (typeof uni.readBLECharacteristicValue !== 'function') return {}
try {
const buffer = await readBleCharacteristic(bleDeviceId, SERVICE_UUID, RUNTIME_CHAR_UUID)
return parseRuntimePayload(buffer)
} catch {
return {}
}
}

View File

@@ -0,0 +1,24 @@
import { request } from '@/api/request'
import type {
AppDeviceRuntimeVo,
DeviceRuntimeQueryBody,
UpdateDeviceRuntimeBody,
} from './device-detail.types'
/** POST /app/device/runtime — 查询设备运行数据 */
export function fetchDeviceRuntime(data: DeviceRuntimeQueryBody) {
return request<AppDeviceRuntimeVo>({
url: '/app/device/runtime',
method: 'POST',
data,
})
}
/** POST /app/device/updateRuntime — 更新设备运行数据 */
export function updateDeviceRuntime(data: UpdateDeviceRuntimeBody) {
return request<void>({
url: '/app/device/updateRuntime',
method: 'POST',
data,
})
}

View File

@@ -0,0 +1,400 @@
.device-detail-page {
min-height: 100vh;
background: #f5f6f8;
display: flex;
flex-direction: column;
}
.device-detail-hero {
position: relative;
z-index: 1;
flex-shrink: 0;
padding: 0 32rpx 56rpx;
overflow: hidden;
pointer-events: none;
}
.device-detail-hero__bar,
.device-detail-hero__status,
.device-detail-hero__metric-row,
.device-detail-hero__sync,
.device-detail-hero__settings,
.device-detail-hero__back {
pointer-events: auto;
}
.device-detail-hero__bg {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 0;
}
.device-detail-hero__bar {
position: relative;
z-index: 1;
height: 88rpx;
display: flex;
align-items: center;
}
.device-detail-hero__back {
width: 72rpx;
height: 88rpx;
display: flex;
align-items: center;
}
.device-detail-hero__back-icon {
font-size: 56rpx;
line-height: 1;
color: #fff;
font-weight: 300;
}
.device-detail-hero__title {
flex: 1;
text-align: center;
font-size: 34rpx;
font-weight: 600;
color: #fff;
}
.device-detail-hero__settings {
width: 72rpx;
height: 88rpx;
display: flex;
align-items: center;
justify-content: flex-end;
}
.device-detail-hero__settings-icon {
width: 40rpx;
height: 40rpx;
}
.device-detail-hero__status {
position: relative;
z-index: 1;
display: flex;
align-items: center;
justify-content: flex-start;
gap: 10rpx;
margin-top: 4rpx;
padding-left: 8rpx;
}
.device-detail-hero__status-dot {
width: 10rpx;
height: 10rpx;
border-radius: 50%;
background: #fff;
&--offline {
background: rgba(255, 255, 255, 0.55);
}
}
.device-detail-hero__status-text {
font-size: 24rpx;
color: rgba(255, 255, 255, 0.92);
}
.device-detail-hero__metric-row {
position: relative;
z-index: 1;
margin-top: 40rpx;
padding: 0 8rpx;
display: flex;
align-items: center;
justify-content: space-between;
}
.device-detail-hero__metric {
display: flex;
align-items: baseline;
gap: 10rpx;
}
.device-detail-hero__metric-value {
font-size: 96rpx;
font-weight: 700;
color: #fff;
line-height: 1;
letter-spacing: -2rpx;
}
.device-detail-hero__metric-unit {
font-size: 26rpx;
color: rgba(255, 255, 255, 0.92);
padding-bottom: 8rpx;
}
.device-detail-hero__quality {
width: 80rpx;
height: 80rpx;
border-radius: 50%;
background: rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.device-detail-hero__quality-text {
font-size: 36rpx;
font-weight: 700;
color: #fff;
}
.device-detail-hero__sync {
position: relative;
z-index: 1;
display: block;
margin-top: 24rpx;
padding-left: 8rpx;
text-align: left;
font-size: 22rpx;
color: rgba(255, 255, 255, 0.75);
}
.device-detail-page__scroll {
position: relative;
z-index: 2;
flex: 1;
height: 0;
margin-top: -40rpx;
}
.device-detail-panel {
padding: 0 24rpx calc(40rpx + env(safe-area-inset-bottom));
}
.device-detail-panel__dash {
height: 2rpx;
margin: 0 8rpx 24rpx;
border-top: 2rpx dashed rgba(255, 255, 255, 0.55);
}
.device-detail-card {
background: #fff;
border-radius: 32rpx;
padding: 36rpx 28rpx 32rpx;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
margin-bottom: 24rpx;
}
.device-detail-card__section {
margin-bottom: 32rpx;
}
.device-detail-card__head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 20rpx;
}
.device-detail-card__head-left {
display: flex;
align-items: center;
gap: 10rpx;
}
.device-detail-card__label {
font-size: 30rpx;
font-weight: 600;
color: $color-text;
}
.device-detail-card__head-icon-wrap {
width: 40rpx;
height: 40rpx;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.device-detail-card__head-icon {
width: 28rpx;
height: 28rpx;
}
.device-detail-mode-list {
display: flex;
gap: 16rpx;
}
.device-detail-mode-item {
flex: 1;
height: 80rpx;
border-radius: 16rpx;
background: #f3f4f6;
display: flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
}
.device-detail-mode-item--active {
background: linear-gradient(135deg, #3fd47f 0%, #21c25e 100%);
box-shadow: 0 6rpx 20rpx rgba(33, 194, 94, 0.28);
}
.device-detail-mode-item__text {
font-size: 26rpx;
color: #333;
}
.device-detail-mode-item--active .device-detail-mode-item__text {
color: #fff;
font-weight: 500;
}
.device-detail-fan-list {
display: flex;
gap: 16rpx;
}
.device-detail-fan-item {
flex: 1;
height: 80rpx;
border-radius: 16rpx;
background: #f3f4f6;
display: flex;
align-items: center;
justify-content: center;
}
.device-detail-fan-item--active {
background: linear-gradient(135deg, #3fd47f 0%, #21c25e 100%);
box-shadow: 0 6rpx 20rpx rgba(33, 194, 94, 0.28);
}
.device-detail-fan-item__text {
font-size: 28rpx;
color: #333;
font-weight: 500;
}
.device-detail-fan-item--active .device-detail-fan-item__text {
color: #fff;
}
.device-detail-card__power {
display: flex;
align-items: center;
justify-content: space-between;
padding-top: 4rpx;
}
.device-detail-card__power-label {
font-size: 28rpx;
color: $color-text;
}
.device-detail-card__power-value {
font-size: 28rpx;
font-weight: 600;
color: $color-primary;
}
.device-detail-stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 20rpx;
}
.device-detail-stat-card {
background: #fff;
border-radius: 28rpx;
padding: 28rpx 24rpx 24rpx;
box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
min-height: 300rpx;
display: flex;
flex-direction: column;
}
.device-detail-stat-card__head {
margin-bottom: 12rpx;
}
.device-detail-stat-card__title {
font-size: 28rpx;
font-weight: 600;
color: $color-text;
}
.device-detail-stat-card__value {
font-size: 52rpx;
font-weight: 700;
color: $color-text;
line-height: 1.1;
margin-bottom: 14rpx;
}
.device-detail-stat-card__track {
height: 10rpx;
border-radius: 5rpx;
background: #eef0f3;
overflow: hidden;
margin-bottom: 14rpx;
}
.device-detail-stat-card__fill {
height: 100%;
border-radius: 5rpx;
background: linear-gradient(90deg, #45d685 0%, #21c25e 100%);
}
.device-detail-stat-card__desc {
font-size: 22rpx;
color: $color-text-secondary;
line-height: 1.4;
margin-bottom: 16rpx;
}
.device-detail-stat-card__btn {
margin-top: auto;
height: 68rpx;
border-radius: 34rpx;
border: 2rpx solid #e8eaed;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
}
.device-detail-stat-card__btn--hover {
opacity: 0.85;
}
.device-detail-stat-card__btn--done {
border-color: #e8eaed;
background: #fff;
}
.device-detail-stat-card__btn-text {
font-size: 24rpx;
color: $color-text-secondary;
}
.device-detail-stat-card__btn--done .device-detail-stat-card__btn-text {
color: $color-text-secondary;
}
.device-detail-stat-card__tag {
margin-top: auto;
align-self: flex-start;
padding: 6rpx 18rpx;
border-radius: 20rpx;
background: #edf9f1;
}
.device-detail-stat-card__tag-text {
font-size: 22rpx;
color: $color-primary;
}

View File

@@ -0,0 +1,57 @@
/** POST /app/device/runtime 查询参数 */
export interface DeviceRuntimeQueryBody {
deviceId: number
}
/**
* POST /app/device/runtime 返回 data
* status: 0未激活 1在线 2离线
* runMode: 0自动 1车载 2桌面
* fanLevel: 0标准 1强力 2低档
* powerMode: 0USB 1电池
* parkingShutdown: 0关机 1开机
*/
export interface AppDeviceRuntimeVo {
deviceId?: number
deviceNo?: string
name?: string
status?: string
runMode?: string
fanLevel?: string
tvoc?: number
powerMode?: string
filterTotalDays?: string
filterRemainDays?: string
filterLife?: number
filterReplaceTime?: string
parkingShutdown?: string
}
/** POST /app/device/updateRuntime */
export interface UpdateDeviceRuntimeBody {
deviceId: number
runMode?: string
fanLevel?: string
status?: string
bluetoothConnected?: string
signalLevel?: string
charging?: string
tvoc?: number
powerMode?: string
filterTotalDays?: string
filterRemainDays?: string
parkingShutdown?: string
}
export interface DeviceDetailRouteQuery {
deviceId?: string
name?: string
locationName?: string
status?: string
bluetoothConnected?: string
charging?: string
mac?: string
}
export type RunMode = '0' | '1' | '2'
export type FanLevel = '0' | '1' | '2'

View File

@@ -0,0 +1,113 @@
import type { AppDeviceRuntimeVo, FanLevel, RunMode } from './device-detail.types'
export const RUN_MODE_OPTIONS = [
{ value: '0' as RunMode, label: '自动模式' },
{ value: '1' as RunMode, label: '车载模式' },
{ value: '2' as RunMode, label: '桌面模式' },
] as const
/** 自动模式下可选:标准 / 强力(对应 API fanLevel 0 / 1) */
export const AUTO_FAN_LEVEL_OPTIONS = [
{ value: '0' as FanLevel, label: '标准' },
{ value: '1' as FanLevel, label: '强力' },
] as const
export function isAutoRunMode(runMode?: string): boolean {
return runMode === '0'
}
/** 自动模式下 UI 仅展示标准/强力 */
export function normalizeAutoFanLevel(runMode?: string, fanLevel?: string): FanLevel {
const level = (fanLevel as FanLevel) || '0'
if (!isAutoRunMode(runMode)) return level
return level === '1' ? '1' : '0'
}
/** 状态:0未激活 1在线 2离线 */
export function isDeviceOnline(status?: string): boolean {
return status === '1'
}
/** 蓝牙连接状态:0未连接 1已连接 */
export function isBluetoothConnected(value?: string): boolean {
return value === '1'
}
export function formatConnectionText(options: {
status?: string
bluetoothConnected?: string
locationName: string
}): string {
const { status, bluetoothConnected, locationName } = options
if (status === '0') return `未激活 · ${locationName}`
if (status === '2' || !isDeviceOnline(status)) {
return `设备离线 · ${locationName}`
}
const btText = isBluetoothConnected(bluetoothConnected) ? '蓝牙已连接' : '蓝牙未连接'
return `${btText} · ${locationName}`
}
/** 供电模式:0USB 1电池 */
export function formatPowerMode(mode?: string): string {
if (mode === '1') return '电池供电模式'
return 'USB供电模式'
}
export function formatTvocValue(tvoc?: number): string {
if (tvoc == null) return '--'
return Number(tvoc).toFixed(1)
}
export function formatTvocLevel(tvoc?: number): string {
const value = tvoc ?? 0
if (value <= 0.3) return '优'
if (value <= 0.6) return '良'
return '差'
}
export function formatFilterRemainDays(runtime: AppDeviceRuntimeVo): string {
if (runtime.filterRemainDays) {
return `预计还可使用 ${runtime.filterRemainDays} 天`
}
const total = Number(runtime.filterTotalDays)
const life = runtime.filterLife ?? 0
if (total > 0 && life > 0) {
const remain = Math.round(total * life / 100)
return `预计还可使用 ${remain} 天`
}
return '预计还可使用 -- 天'
}
export function hasFilterReplaced(runtime: AppDeviceRuntimeVo): boolean {
return !!runtime.filterReplaceTime
}
export interface RuntimeViewState {
deviceName: string
runMode: RunMode
fanLevel: FanLevel
tvoc: number | null
powerMode: string
filterLife: number
filterRemainText: string
filterReplaced: boolean
isOnline: boolean
}
/** 将 /app/device/runtime 响应映射为详情页展示状态 */
export function mapRuntimeToView(
data: AppDeviceRuntimeVo,
fallbackName = '未命名设备',
): RuntimeViewState {
return {
deviceName: data.name || fallbackName,
runMode: (data.runMode as RunMode) || '0',
fanLevel: normalizeAutoFanLevel(data.runMode, data.fanLevel),
tvoc: data.tvoc ?? null,
powerMode: data.powerMode || '0',
filterLife: data.filterLife ?? 0,
filterRemainText: formatFilterRemainDays(data),
filterReplaced: hasFilterReplaced(data),
isOnline: isDeviceOnline(data.status),
}
}

View File

@@ -0,0 +1,206 @@
<template>
<view class="device-detail-page">
<view class="device-detail-hero" :style="{ paddingTop: statusBarHeight + 'px' }">
<image
class="device-detail-hero__bg"
:src="staticAssets.deviceDetailHeroBg"
mode="aspectFill"
/>
<view class="device-detail-hero__bar">
<view class="device-detail-hero__back" @tap="onBack">
<text class="device-detail-hero__back-icon">‹</text>
</view>
<text class="device-detail-hero__title">{{ deviceName }}</text>
<view class="device-detail-hero__settings" @tap="onSettings">
<image
class="device-detail-hero__settings-icon"
:src="staticAssets.iconDeviceDetailSettings"
mode="aspectFit"
/>
</view>
</view>
<view class="device-detail-hero__status">
<view
class="device-detail-hero__status-dot"
:class="{ 'device-detail-hero__status-dot--offline': !isOnline }"
/>
<text class="device-detail-hero__status-text">{{ connectionText }}</text>
</view>
<view class="device-detail-hero__metric-row">
<view class="device-detail-hero__metric">
<text class="device-detail-hero__metric-value">{{ tvocDisplay }}</text>
<text class="device-detail-hero__metric-unit">TVOC mg</text>
</view>
<view class="device-detail-hero__quality">
<text class="device-detail-hero__quality-text">{{ tvocLevel }}</text>
</view>
</view>
<text class="device-detail-hero__sync">{{ syncText }}</text>
</view>
<scroll-view class="device-detail-page__scroll" scroll-y>
<view class="device-detail-panel">
<view class="device-detail-panel__dash" aria-hidden="true" />
<view class="device-detail-card">
<view class="device-detail-card__section">
<view class="device-detail-card__head">
<view class="device-detail-card__head-left">
<text class="device-detail-card__label">运行模式</text>
<view class="device-detail-card__head-icon-wrap" @tap.stop="onOpenRunModeExplain">
<image
class="device-detail-card__head-icon"
:src="staticAssets.iconRunModeInfo"
mode="aspectFit"
/>
</view>
</view>
</view>
<view class="device-detail-mode-list">
<view
v-for="item in runModeOptions"
:key="item.value"
class="device-detail-mode-item"
:class="{ 'device-detail-mode-item--active': runMode === item.value }"
@tap="onSelectRunMode(item.value)"
>
<text class="device-detail-mode-item__text">{{ item.label }}</text>
</view>
</view>
</view>
<view v-if="showFanLevelControl" class="device-detail-card__section">
<view class="device-detail-card__head">
<view class="device-detail-card__head-left">
<text class="device-detail-card__label">风速档位</text>
</view>
</view>
<view class="device-detail-fan-list">
<view
v-for="item in fanLevelOptions"
:key="item.value"
class="device-detail-fan-item"
:class="{ 'device-detail-fan-item--active': fanLevel === item.value }"
@tap="onSelectFanLevel(item.value)"
>
<text class="device-detail-fan-item__text">{{ item.label }}</text>
</view>
</view>
</view>
<view class="device-detail-card__power">
<text class="device-detail-card__power-label">当前供电状态</text>
<text class="device-detail-card__power-value">{{ powerModeText }}</text>
</view>
</view>
<view class="device-detail-stats">
<view class="device-detail-stat-card">
<view class="device-detail-stat-card__head">
<text class="device-detail-stat-card__title">滤芯寿命</text>
</view>
<text class="device-detail-stat-card__value">{{ filterLife }}%</text>
<view class="device-detail-stat-card__track">
<view
class="device-detail-stat-card__fill"
:style="{ width: `${filterLife}%` }"
/>
</view>
<text class="device-detail-stat-card__desc">{{ filterRemainText }}</text>
<view
class="device-detail-stat-card__btn"
:class="{ 'device-detail-stat-card__btn--done': filterReplaced }"
hover-class="device-detail-stat-card__btn--hover"
@tap.stop="onFilterReplace"
>
<text class="device-detail-stat-card__btn-text" @tap.stop="onFilterReplace">
{{ filterReplaced ? '已换新滤芯' : '确认换新滤芯' }}
</text>
</view>
</view>
<view class="device-detail-stat-card">
<view class="device-detail-stat-card__head">
<text class="device-detail-stat-card__title">电量</text>
</view>
<text class="device-detail-stat-card__value">{{ batteryDisplay }}</text>
<view class="device-detail-stat-card__track">
<view
v-if="batteryLevel != null"
class="device-detail-stat-card__fill"
:style="{ width: `${batteryLevel}%` }"
/>
</view>
<view v-if="charging" class="device-detail-stat-card__tag">
<text class="device-detail-stat-card__tag-text">充电中</text>
</view>
</view>
</view>
</view>
</scroll-view>
<filter-replace-dialog
v-model:visible="filterReplaceDialogVisible"
@confirm="onConfirmFilterReplace"
/>
<run-mode-explain-dialog v-model:visible="runModeExplainVisible" />
</view>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { staticAssets } from '@/utils/static-assets'
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'
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight ?? 0)
const runModeExplainVisible = ref(false)
function onOpenRunModeExplain() {
runModeExplainVisible.value = true
}
const {
deviceName,
connectionText,
isOnline,
tvocDisplay,
tvocLevel,
syncText,
runMode,
fanLevel,
showFanLevelControl,
powerModeText,
filterLife,
filterRemainText,
filterReplaced,
filterReplaceDialogVisible,
batteryLevel,
batteryDisplay,
charging,
runModeOptions,
fanLevelOptions,
onSelectRunMode,
onSelectFanLevel,
onSettings,
onFilterReplace,
onConfirmFilterReplace,
} = useDeviceDetail()
function onBack() {
const pages = getCurrentPages()
if (pages.length > 1) {
uni.navigateBack()
} else {
uni.reLaunch({ url: '/pages/device/index' })
}
}
</script>
<style lang="scss" scoped>
@import './device-detail.scss';
</style>

View File

@@ -0,0 +1,185 @@
import { onUnload } from '@dcloudio/uni-app'
import { ref } from 'vue'
import {
BluetoothError,
closeBleConnection,
createBleConnection,
ensureBluetoothReady,
getBluetoothErrorMessage,
getDiscoveredBluetoothDevices,
isBluetoothApiSupported,
rssiToSignalLevel,
scanForBleDeviceByMac,
subscribeBleConnectionStateChange,
} from '@/utils/bluetooth'
import { updateDeviceRuntime } from './device-detail.api'
import { readRuntimeFromBle } 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
getMac: () => string | undefined
getRuntimePatch: () => Partial<UpdateDeviceRuntimeBody>
onBluetoothConnectedChange: (connected: boolean) => void
onSyncTextChange: (text: string) => void
onSynced?: () => void | Promise<void>
}
export function useDeviceBluetoothSync(context: DeviceBluetoothSyncContext) {
const syncing = ref(false)
const bleDeviceId = ref<string>()
let syncTimer: ReturnType<typeof setInterval> | undefined
let unsubscribeConnection: (() => void) | undefined
let active = false
function setSyncText(text: string) {
context.onSyncTextChange(text)
}
async function reportDisconnected() {
const deviceId = context.getDeviceId()
if (!deviceId) return
context.onBluetoothConnectedChange(false)
try {
await updateDeviceRuntime({
deviceId,
bluetoothConnected: '0',
signalLevel: '0',
})
} catch {
// 上报失败时保留本地状态
}
}
async function connectAndSync(): Promise<boolean> {
const deviceId = context.getDeviceId()
const mac = context.getMac()
if (!deviceId) return false
if (!isBluetoothApiSupported()) {
setSyncText('当前环境不支持蓝牙同步')
return false
}
if (!mac) {
setSyncText('缺少设备 MAC,无法蓝牙同步')
return false
}
if (syncing.value) return false
syncing.value = true
try {
setSyncText('正在连接蓝牙…')
await ensureBluetoothReady()
let targetBleId = bleDeviceId.value
let foundDevice: UniApp.BluetoothDeviceInfo | null = null
if (!targetBleId) {
foundDevice = await scanForBleDeviceByMac(mac, { timeoutMs: SCAN_TIMEOUT_MS })
if (!foundDevice) {
setSyncText('未找到设备,请确认已开机并靠近手机')
await reportDisconnected()
return false
}
targetBleId = foundDevice.deviceId
bleDeviceId.value = targetBleId
} else {
const discovered = await getDiscoveredBluetoothDevices()
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
}
context.onBluetoothConnectedChange(true)
const blePayload = await readRuntimeFromBle(targetBleId)
const runtimePatch = context.getRuntimePatch()
const signalLevel = rssiToSignalLevel(foundDevice?.RSSI)
await updateDeviceRuntime({
deviceId,
...runtimePatch,
...blePayload,
status: '1',
bluetoothConnected: '1',
signalLevel,
})
setSyncText('刚刚更新 · 数据实时同步中')
await context.onSynced?.()
return true
} catch (err) {
setSyncText(getBluetoothErrorMessage(err))
bleDeviceId.value = undefined
await reportDisconnected()
return false
} finally {
syncing.value = false
}
}
function startSyncLoop() {
if (active) return
active = true
unsubscribeConnection = subscribeBleConnectionStateChange((res) => {
if (!bleDeviceId.value || res.deviceId !== bleDeviceId.value) return
if (!res.connected) {
bleDeviceId.value = undefined
void reportDisconnected()
setSyncText('蓝牙已断开,正在尝试重连…')
}
})
void connectAndSync()
syncTimer = setInterval(() => {
void connectAndSync()
}, SYNC_INTERVAL_MS)
}
async function stopSync() {
active = false
if (syncTimer) {
clearInterval(syncTimer)
syncTimer = undefined
}
unsubscribeConnection?.()
unsubscribeConnection = undefined
const currentBleId = bleDeviceId.value
bleDeviceId.value = undefined
if (currentBleId) {
await closeBleConnection(currentBleId).catch(() => {})
await reportDisconnected()
}
}
onUnload(() => {
void stopSync()
})
return {
syncing,
startSyncLoop,
stopSync,
connectAndSync,
}
}

View File

@@ -0,0 +1,223 @@
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { getErrorMessage } from '@/utils/api-error'
import { fetchDeviceList } from '../device.api'
import { fetchDeviceRuntime, updateDeviceRuntime } from './device-detail.api'
import type { AppDeviceRuntimeVo, DeviceDetailRouteQuery, FanLevel, RunMode } from './device-detail.types'
import {
AUTO_FAN_LEVEL_OPTIONS,
formatConnectionText,
formatPowerMode,
formatTvocLevel,
formatTvocValue,
isAutoRunMode,
isBluetoothConnected,
mapRuntimeToView,
RUN_MODE_OPTIONS,
} from './device-detail.utils'
import { useDeviceBluetoothSync } from './use-device-bluetooth-sync'
export function useDeviceDetail() {
const deviceId = ref(0)
const deviceMac = ref<string>()
const deviceName = ref('')
const locationName = ref('客厅')
const deviceStatus = ref<string>()
const bluetoothConnected = ref(false)
const charging = ref(false)
const isOnline = ref(false)
const loading = ref(false)
const updating = ref(false)
const runMode = ref<RunMode>('0')
const fanLevel = ref<FanLevel>('0')
const tvoc = ref<number | null>(null)
const powerMode = ref('0')
const filterLife = ref(0)
const filterRemainText = ref('预计还可使用 -- 天')
const filterReplaced = ref(false)
const filterReplaceDialogVisible = ref(false)
const batteryLevel = ref<number | null>(null)
const syncText = ref('数据实时同步中')
const tvocDisplay = computed(() => formatTvocValue(tvoc.value ?? undefined))
const tvocLevel = computed(() => formatTvocLevel(tvoc.value ?? undefined))
const powerModeText = computed(() => formatPowerMode(powerMode.value))
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 : [],
)
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
powerMode.value = view.powerMode
filterLife.value = view.filterLife
filterRemainText.value = view.filterRemainText
filterReplaced.value = view.filterReplaced
isOnline.value = view.isOnline
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)
if (!device) return
if (device.mac) deviceMac.value = device.mac
bluetoothConnected.value = isBluetoothConnected(device.bluetoothConnected)
charging.value = device.charging === '1'
if (device.status !== undefined) deviceStatus.value = device.status
isOnline.value = device.status === '1'
} catch {
// 列表刷新失败时保留路由参数状态
}
}
async function loadRuntime() {
if (!deviceId.value) return
loading.value = true
try {
const [runtime] = await Promise.all([
fetchDeviceRuntime({ deviceId: deviceId.value }),
refreshDeviceMeta(),
])
applyRuntime(runtime)
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '加载设备数据失败'), icon: 'none' })
} finally {
loading.value = false
}
}
async function patchRuntime(patch: { runMode?: RunMode; fanLevel?: FanLevel }) {
if (!deviceId.value || updating.value) return
updating.value = true
try {
await updateDeviceRuntime({
deviceId: deviceId.value,
...patch,
})
const data = await fetchDeviceRuntime({ deviceId: deviceId.value })
applyRuntime(data)
await refreshDeviceMeta()
} catch (err) {
uni.showToast({ title: getErrorMessage(err, '设置失败'), icon: 'none' })
} finally {
updating.value = false
}
}
function onSelectRunMode(mode: RunMode) {
if (runMode.value === mode) return
void patchRuntime({ runMode: mode })
}
function onSelectFanLevel(level: FanLevel) {
if (!isAutoRunMode(runMode.value)) return
if (fanLevel.value === level) return
void patchRuntime({ fanLevel: level })
}
function onSettings() {
uni.showToast({ title: '设备设置功能开发中', icon: 'none' })
}
function onFilterReplace() {
if (filterReplaced.value) return
filterReplaceDialogVisible.value = true
}
function onConfirmFilterReplace() {
filterReplaced.value = true
uni.showToast({ title: '操作成功', icon: 'success' })
}
const { startSyncLoop } = useDeviceBluetoothSync({
getDeviceId: () => deviceId.value,
getMac: () => deviceMac.value,
getRuntimePatch: () => ({
runMode: runMode.value,
fanLevel: fanLevel.value,
tvoc: tvoc.value ?? undefined,
powerMode: powerMode.value,
charging: charging.value ? '1' : '0',
}),
onBluetoothConnectedChange: (connected) => {
bluetoothConnected.value = connected
if (connected) {
isOnline.value = true
deviceStatus.value = '1'
}
},
onSyncTextChange: (text) => {
syncText.value = text
},
onSynced: async () => {
await refreshDeviceMeta()
const data = await fetchDeviceRuntime({ deviceId: deviceId.value })
applyRuntime(data)
},
})
onLoad((query?: DeviceDetailRouteQuery) => {
deviceId.value = Number(query?.deviceId) || 0
if (query?.name) deviceName.value = decodeURIComponent(String(query.name))
if (query?.locationName) {
locationName.value = decodeURIComponent(String(query.locationName))
}
if (query?.status) {
deviceStatus.value = String(query.status)
isOnline.value = query.status === '1'
}
if (query?.mac) deviceMac.value = decodeURIComponent(String(query.mac))
bluetoothConnected.value = isBluetoothConnected(query?.bluetoothConnected)
charging.value = query?.charging === '1'
void loadRuntime().then(() => {
startSyncLoop()
})
})
return {
deviceName,
connectionText,
isOnline,
tvocDisplay,
tvocLevel,
syncText,
runMode,
fanLevel,
powerModeText,
filterLife,
filterRemainText,
filterReplaced,
filterReplaceDialogVisible,
batteryDisplay,
batteryLevel,
charging,
loading,
showFanLevelControl,
runModeOptions: RUN_MODE_OPTIONS,
fanLevelOptions,
onSelectRunMode,
onSelectFanLevel,
onSettings,
onFilterReplace,
onConfirmFilterReplace,
}
}