This commit is contained in:
fuenmao
2026-11-11 16:12:02 +08:00
parent 20467ca479
commit db0c578890
23 changed files with 464 additions and 426 deletions
+69 -3
View File
@@ -23,7 +23,7 @@ const dashboardRecord = (name = '演示用户') => ({ user: { id: 1, displayName
profile: {}, hasCompletedAssessment: false, tcmResult: { hasCompleted: true, constitutionName: '平和质' } })
const deviceStatus = () => ({ connected: true, sceneDevices: { available: 3 } })
function environment(overrides = {}) {
function environment(overrides = {}, ib43Get) {
const disposed = [], toasts = [], navigations = [], tokenWrites = [], mounted = []
const router = { replace: location => navigations.push(location), push: location => navigations.push(location) }
const vue = { defineComponent: options => options, ref: value => ({ value }), reactive: value => value,
@@ -43,6 +43,7 @@ function environment(overrides = {}) {
const file = path.resolve(root, /\.(vue|ts)$/.test(relative) ? relative : relative + '.ts')
const normalized = file.replaceAll('\\', '/')
if (normalized.endsWith('services/health.ts')) return { healthApi }
if (normalized.endsWith('services/http.ts') && ib43Get) return { default: { get: ib43Get } }
if (normalized.endsWith('services/auth.ts')) return { saveTokens: (...args) => tokenWrites.push(args), clearTokens: () => tokenWrites.push('clear') }
if (file.endsWith('AppTabBar.vue')) return { default: {} }
if (file.endsWith('useDeviceScenes.ts')) return { useDeviceScenes: options => {
@@ -158,14 +159,79 @@ async function render(name, values = {}, routePath = '/dashboard') {
test('home renders a prominent scene, collapsed presets, a real profile entry and the required navigation order', async () => {
const record = { ...dashboardRecord(), bmi: 31.1, sceneConfig: { targetHumidity: 55, fanLevel: '1挡', lightBrightnessPercent: 50, lightColorTemperatureKelvin: 2700 } }
const html = await render('DashboardView', { loading: false, dashboard: record, homeAssistant: deviceStatus() })
for (const value of ['我的舒睡空间', '一键开启舒睡', '查看舒睡设备', '查看体质启动预设', '打开我的健康档案']) assert.ok(html.includes(value), value)
const html = await render('DashboardView', { loading: false, dashboard: record, homeAssistant: {
...deviceStatus(), scenePresets: [{ deviceName: '米家除湿机', entityId: 'humidifier.keep', action: '恒湿', detail: '目标 55%', available: true }],
} })
for (const value of ['我的舒睡空间', '一键开启舒睡', '查看舒睡设备', '睡眠数据', '查看体质启动预设', '打开我的健康档案']) assert.ok(html.includes(value), value)
assert.match(html, /<details class="startup-preset-details">/)
assert.match(html, /米家除湿机/)
assert.doesNotMatch(html, /助眠灯光|2700K/)
assert.ok(html.indexOf('首页</span>') < html.indexOf('中医四诊</span>'))
assert.ok(html.indexOf('中医四诊</span>') < html.indexOf('健康评估</span>'))
assert.ok(html.indexOf('健康评估</span>') < html.indexOf('我的</span>'))
})
const sleepBed = { id: 'left-bed', bedName: '卧室左侧', side: 'left', simulation: true, endedAtMs: null }
const rightBed = { id: 'right-bed', bedName: '卧室右侧', side: 'right', simulation: false, endedAtMs: null }
test('sleep data renders stale readings and missing fields separately, with the same time for UTC strings and history milliseconds', async () => {
const instant = Date.parse('2026-11-11T01:55:21Z')
const readings = {
heartRate: { value: 72, receivedAt: '2026-11-11 01:55:21', freshness: 'stale' },
respiration: { value: null, receivedAt: '2026-11-11 01:55:21', freshness: 'recent' },
snoring: { value: 0, receivedAt: '2026-11-11 01:55:21', freshness: 'stale' },
}
const html = await render('SleepDataView', {
bindingsLoading: false, beds: [sleepBed], bedId: sleepBed.id,
current: { bed: sleepBed, active: true, transport: 'connected', readings },
history: [{ id: '1', receivedAtMs: String(instant), readings }],
}, '/sleep-data')
assert.match(html, /模拟设备/)
assert.match(html, /数据服务已连接/)
assert.match(html, /数据已过期/)
assert.match(html, /暂无有效读数/)
assert.match(html, /暂无上报/)
assert.match(html, /未打鼾/)
assert.doesNotMatch(html, /离床/)
const { formatIb43Time } = await server.ssrLoadModule('/src/services/ib43.ts')
assert.equal(formatIb43Time(readings.heartRate.receivedAt), formatIb43Time(String(instant)))
const empty = await render('SleepDataView', { bindingsLoading: false }, '/sleep-data')
assert.match(empty, /暂无绑定床位/)
assert.doesNotMatch(empty, /最近读数|历史记录/)
})
test('sleep data discards late results from a previous bed and keeps the time range and cursor when paging', async () => {
const oldCurrent = deferred(), oldHistory = deferred(), historyRequests = []
const cursor = '9007199254740993'
const env = environment({}, async (url, options) => {
if (url.endsWith('/bindings')) return [sleepBed, rightBed]
if (url.includes('/left-bed/')) return url.endsWith('/current') ? oldCurrent.promise : oldHistory.promise
if (url.endsWith('/right-bed/current')) return { bed: rightBed, readings: {} }
if (url.endsWith('/right-bed/history')) {
historyRequests.push(options.params)
return options.params.beforeId == null ? { items: [{ id: 'right-1' }], nextBeforeId: cursor } :
{ items: [{ id: 'right-2' }], nextBeforeId: null }
}
throw new Error(`Unexpected request: ${url}`)
})
const page = env.page('SleepDataView')
await page.loadBindings()
assert.equal(page.bedId.value, 'left-bed')
page.bedId.value = 'right-bed'
page.loadBed()
await new Promise(resolve => setImmediate(resolve))
oldCurrent.resolve({ bed: sleepBed }); oldHistory.resolve({ items: [{ id: 'left-1' }] })
await new Promise(resolve => setImmediate(resolve))
assert.equal(page.current.value.bed.id, 'right-bed')
assert.equal(page.history.value[0].id, 'right-1')
await page.loadHistory(true)
assert.equal(historyRequests[1].beforeId, cursor)
assert.equal(historyRequests[1].fromMs, historyRequests[0].fromMs)
assert.equal(historyRequests[1].toMs, historyRequests[0].toMs)
assert.equal(page.history.value[1].id, 'right-2')
assert.equal(page.nextBeforeId.value, undefined)
})
test('error pages render retry controls without mistaken missing-assessment or device actions', async () => {
for (const [name, path] of [['DashboardView', '/dashboard'], ['ProfileView', '/profile']]) {
const html = await render(name, { loading: false, loadError: '测试连接失败' }, path)
+27 -33
View File
@@ -81,9 +81,9 @@ test('parameter conversion rejects junk and unavailable data; light zero and har
const { createDeviceParameterState, syncDeviceParameters } = env.load('devices/parameterRegistry')
const params = createDeviceParameterState()
syncDeviceParameters(params, { brightness: control('off'), color_temp: control('on', { color_temp_kelvin: 6500 }),
mattress_left_heating: control('4'), volume: control('on', { volume_level: .56 }), fragrance_auto_light: control('on') })
volume: control('on', { volume_level: .56 }), fragrance_auto_light: control('on') })
assert.equal(params.lightBrightness, 0); assert.equal(params.lightColorTemp, 5000)
assert.equal(params.mattressLeftHeating, 4); assert.equal(params.speakerVolume, 56)
assert.equal(params.speakerVolume, 56)
assert.equal(params.fragranceAutoLight, true)
syncDeviceParameters(params, { fragrance_auto_light: control('unavailable', {}, false), volume: control('on', { volume_level: 'NaN' }) })
assert.equal(params.fragranceAutoLight, true); assert.equal(params.speakerVolume, 56)
@@ -105,20 +105,6 @@ test('parameter availability is scoped to the actual device; missing numeric att
assert.equal(parameterIsAvailable(controls, 'brightness', lamp), false)
})
test('mattress per-user preferences remain separate from the one physically running side', () => {
const env = environment(), params = env.load('devices/parameterRegistry').createDeviceParameterState()
const user = env.vue.ref(1), hook = env.load('devices/mattress/useMattressPreferences').useMattressPreferences(params, user, () => 'mattress')
hook.syncModes({ mattress_left_mode: control('智能适配'), mattress_right_mode: control('无') })
assert.equal(params.mattressLeftMode, '智能适配'); assert.equal(params.mattressRightMode, '智能适配')
assert.equal(hook.mattressActiveSide.value, 'left')
hook.commitMode('left', '瑜伽助眠'); hook.commitMode('right', '智能腰托')
hook.syncModes({ mattress_left_mode: control('无'), mattress_right_mode: control('智能腰托') })
assert.equal(params.mattressLeftMode, '瑜伽助眠'); assert.equal(hook.mattressActiveSide.value, 'right')
hook.syncModes({ mattress_left_mode: control('智能适配'), mattress_right_mode: control('智能腰托') })
assert.equal(hook.mattressActiveSide.value, 'right')
user.value = 2; hook.syncModes({})
assert.equal(params.mattressLeftMode, '智能适配')
})
test('older transition response cannot replace newer volume; disposal cannot create a late timer', async () => {
const first = deferred(), second = deferred(); let reads = 0
@@ -223,20 +209,6 @@ test('navigation closes a pending parameter toast and prevents a late result fro
assert.equal(env.timeouts.size, 0)
})
test('mattress confirmation cannot act after leaving the page or switching to another mattress', async () => {
const confirmation = deferred(), env = environment({ confirmDialog: () => confirmation.promise })
const selected = env.vue.ref(device('mattress', 'Sleep', [], { deviceId: 'first' }))
let writes = 0
const hook = env.load('devices/mattress/useMattressControls').useMattressControls(selected,
async () => { writes++; return true }, async () => {}, () => {})
const request = hook.setMattressSelect('mattress_massage_right_part', { target: { value: '全身' } })
selected.value = undefined; confirmation.resolve(); await request
assert.equal(writes, 0)
selected.value = device('mattress', 'Sleep', [], { deviceId: 'first' })
env.dispose()
await hook.setMattressSelect('mattress_massage_right_part', { target: { value: '全身' } })
assert.equal(writes, 0)
})
const device = (moduleKey, category, entities = [], extra = {}) => ({
deviceId: 'device', name: '测试设备', manufacturer: '', model: '', moduleKey, category,
@@ -303,7 +275,10 @@ test('a failed new-light fade is not reported as success merely because the orig
{ entityId: 'light.primary', running: true, success: true, brightnessPercent: 1, mode: 'sleep' },
{ entityId: 'light.strip', running: true, success: true, brightnessPercent: 2, mode: 'sleep' },
] }
const env = environment({ lightTransitionStatus: async () => current })
const primary = standardLight('light.primary'); primary.moduleKey = 'lighting'
const strip = standardLight('light.strip'); strip.moduleKey = 'sleep-light-strip'
const env = environment({ lightTransitionStatus: async () => current,
homeAssistantStatus: async () => ({ connected: true, devices: [primary, strip] }) })
const hook = env.load('composables/useDeviceControl').useDeviceControl(); await hook.loadStatus()
current = { ...current, running: false, message: '原灯渐暗完成', lights: [
{ entityId: 'light.primary', running: false, success: true, mode: 'sleep', message: '原灯渐暗完成' },
@@ -316,6 +291,25 @@ test('a failed new-light fade is not reported as success merely because the orig
env.dispose()
})
test('an inventory without configured scene lights clears the previous fade and stops light requests', async () => {
const primary = standardLight('light.primary'); primary.moduleKey = 'lighting'
let devices = [primary], lightReads = 0
const env = environment({
homeAssistantStatus: async () => ({ connected: true, devices }),
lightTransitionStatus: async () => { lightReads++; return { running: true, brightnessPercent: 50, mode: 'sleep' } },
})
const hook = env.load('composables/useDeviceControl').useDeviceControl()
await hook.loadStatus()
assert.equal(lightReads, 1)
assert.equal(env.intervals.size, 1)
devices = []
await hook.loadStatus()
assert.equal(lightReads, 1)
assert.equal(hook.lightTransition.value, undefined)
assert.equal(env.intervals.size, 0)
env.dispose()
})
test('standard light capabilities are per entity, not per category or another lamps configured parameters', () => {
const { lightCapabilities } = environment().load('devices/lighting/capabilities')
const item = standardLight(), capability = lightCapabilities(item)
@@ -479,7 +473,7 @@ test('overview distinguishes a known off state from unavailable data and never a
assert.equal(deviceSummary(climate).canToggle, false)
})
test('overview separates fragrance from its nightlight and only uses mattress readings belonging to that device', () => {
test('overview separates fragrance from its nightlight and does not infer retired mattress controls', () => {
const { deviceSummary } = environment().load('devices/deviceSummary')
const fragrance = device('fragrance', 'Fragrance', [entity('switch.fragrance', 'switch', 'off'), entity('light.night', 'light', 'on')],
{ primaryControlEntityId: 'switch.fragrance' })
@@ -488,7 +482,7 @@ test('overview separates fragrance from its nightlight and only uses mattress re
const mattress = device('mattress', 'Sleep', [entity('select.massage', 'select', '全身')])
assert.equal(deviceSummary(mattress).canToggle, false)
assert.equal(deviceSummary(mattress, { controls: { mattress_massage_right_part: { ...control('全身'), entityId: 'foreign' } } }).statusText, '已连接')
assert.equal(deviceSummary(mattress, { controls: { mattress_massage_right_part: { ...control('全身'), entityId: 'select.massage' } } }).statusText, '右侧按摩中')
assert.equal(deviceSummary(mattress, { controls: { mattress_massage_right_part: { ...control('全身'), entityId: 'select.massage' } } }).statusText, '已连接')
assert.equal(deviceSummary(mattress, { controls: { mattress_massage_right_part: { ...control('unknown'), entityId: 'select.massage' } } }).statusText, '已连接')
})
+13 -16
View File
@@ -17,7 +17,6 @@ const { default: Overview } = await server.ssrLoadModule('/src/views/DeviceContr
const { default: Detail } = await server.ssrLoadModule('/src/views/DeviceDetailView.vue')
const { deviceControlKey } = await server.ssrLoadModule('/src/devices/controlContext.ts')
const { createDeviceParameterState, syncDeviceParameters } = await server.ssrLoadModule('/src/devices/parameterRegistry.ts')
const mattressParams = await server.ssrLoadModule('/src/devices/mattress/parameters.ts')
const { deviceDetailLocation } = await server.ssrLoadModule('/src/devices/deviceKinds.ts')
const { parameterIsAvailable, parameterHasReading } = await server.ssrLoadModule('/src/devices/parameterState.ts')
const { primaryDeviceEntity, reportedPower } = await server.ssrLoadModule('/src/devices/deviceSummary.ts')
@@ -31,7 +30,7 @@ const devices = [
device('lamp', '演示卧室灯', 'lighting', 'Lighting', [reading('light.room', 'light', 'on', { brightness: 128,
supported_color_modes: ['color_temp'], min_color_temp_kelvin: 2700, max_color_temp_kelvin: 6500,
color_temp_kelvin: 3000, supported_features: 4, effect_list: ['阅读', '助眠'], effect: '阅读' })], { primaryControlEntityId: 'light.room' }),
device('mattress', '演示智能床垫', 'mattress', 'Sleep'),
device('environment', '演示环境检测仪', 'environment', 'EnvironmentSensor'),
device('fragrance', '演示香氛机', 'fragrance', 'Fragrance', [reading('switch.fragrance', 'switch', 'off')], { primaryControlEntityId: 'switch.fragrance' }),
device('speaker', '演示音箱', 'audio', 'Media', [reading('media_player.room', 'media_player', 'idle', { volume_level: .7 })], { primaryControlEntityId: 'media_player.room' }),
]
@@ -50,8 +49,7 @@ async function render(location = '/device-control', overrides = {}) {
environment: { temperature: 25.6, humidity: 58.8 }, controlParameters: {} }),
musicTransition: ref({ running: true, hasVolume: true, volumePercent: 46 }), lightTransition: ref(),
sceneRunning: ref(), switchingDeviceId: ref(), settingParam: ref(), actionFeedback: ref(), currentOperationText: ref(''), lastUpdatedAt: ref(''),
localParams: createDeviceParameterState(), mattressComfort: ref(), mattressActiveSide: ref('left'),
...mattressParams,
localParams: createDeviceParameterState(),
isDeviceTurnedOn: value => Boolean(reportedPower(primaryDeviceEntity(value))),
isDeviceControlAvailable: value => primaryDeviceEntity(value)?.domain === 'climate' ? climateCapabilities(value).canToggle
: Boolean(value?.online && reportedPower(primaryDeviceEntity(value)) !== null &&
@@ -60,7 +58,7 @@ async function render(location = '/device-control', overrides = {}) {
hasParameterReading: (parameter, value) => parameterHasReading(context.haStatus.value?.controlParameters, parameter, value),
toggleDevice: unexpectedCommand, controlSpeaker: unexpectedCommand, applyParam: unexpectedCommand,
executeScene: unexpectedCommand, loadStatus: unexpectedCommand, controlLightTransition: unexpectedCommand,
setMattressMode: unexpectedCommand, setMattressSelect: unexpectedCommand, ...overrides,
...overrides,
}
await router.push(location); await router.isReady()
const app = createSSRApp({ render: () => h(RouterView) })
@@ -171,7 +169,7 @@ test('unbound devices in new categories remain generic and cannot borrow bound c
test('overview has compact tiles and room tabs without detailed sliders or mattress controls', async () => {
const { html } = await render()
assert.equal((html.match(/<article class="device-overview-tile/g) ?? []).length, 4)
for (const value of ['一键启动全屋舒睡模式', '一键关闭设备', '全屋', '睡眠空间', '音量 46%', '演示智能床垫']) assert.ok(html.includes(value), value)
for (const value of ['一键启动全屋舒睡模式', '一键关闭设备', '全屋', '睡眠空间', '音量 46%', '演示环境检测仪']) assert.ok(html.includes(value), value)
for (const value of ['左侧加热档位', '按摩力度', '灯光色温调节', 'van-slider']) assert.ok(!html.includes(value), value)
// 快捷开关与进入详情按钮是同级元素,不会发生嵌套按钮或点击开关误进详情。
for (const tile of html.match(/<article class="device-overview-tile[\s\S]*?<\/article>/g) ?? []) {
@@ -288,16 +286,15 @@ test('offline main light disables standard controls even when an auxiliary entit
test('configured scene light composes shared controls with its own fade and wake extensions', async () => {
const { html } = await render('/device-control/lamp')
for (const text of ['灯光亮度', '灯光色温调节', '灯光模式', '开始助眠渐暗', '晨起唤醒', '灯灭停止按摩']) assert.ok(html.includes(text), text)
for (const text of ['灯光亮度', '灯光色温调节', '灯光模式', '开始助眠渐暗', '晨起唤醒']) assert.ok(html.includes(text), text)
assert.equal((html.match(/<section class="device-card"/g) ?? []).length, 1)
assert.ok(!html.includes('不自动加入舒睡或唤醒场景'))
})
test('mattress detail retains full controls and never renders other devices or scene-wide actions', async () => {
test('retired mattress detail link has no controls', async () => {
const { html } = await render('/device-control/mattress')
assert.equal((html.match(/<section class="device-card"/g) ?? []).length, 1)
for (const value of ['演示智能床垫', '全部设备', '左侧加热档位', '右侧加热档位', '左侧承托模式', '右侧承托模式', '左肩软硬度', '右腿软硬度', '左侧按摩部位', '右侧按摩部位', '按摩力度']) assert.ok(html.includes(value), value)
for (const value of ['演示卧室灯', '演示香氛机', '一键启动全屋舒睡模式', 'device-overview-tile']) assert.ok(!html.includes(value), value)
assert.ok(html.includes('未找到这个设备'))
for (const value of ['左侧加热档位', '按摩力度', '左肩软硬度']) assert.ok(!html.includes(value), value)
})
test('fragrance detail retains separate nightlight and unavailable quick-release feedback', async () => {
@@ -330,13 +327,13 @@ test('missing, offline and disconnected devices display honest explanatory state
assert.ok((await render('/device-control/removed')).html.includes('未找到这个设备'))
const offline = { ...devices[1], online: false }
const snapshot = { connected: true, devices: [offline], summary: { totalDevices: 1, onlineDevices: 0 } }
const { html } = await render('/device-control/mattress', { haStatus: ref(snapshot) })
const { html } = await render('/device-control/environment', { haStatus: ref(snapshot) })
assert.ok(html.includes('设备回读显示离线'))
assert.ok(html.includes('右侧按摩部位'))
const disconnected = await render('/device-control/mattress', { haStatus: ref({ ...snapshot, connected: false, message: '连接失败' }) })
assert.ok(html.includes('温度'))
const disconnected = await render('/device-control/environment', { haStatus: ref({ ...snapshot, connected: false, message: '连接失败' }) })
assert.ok(disconnected.html.includes('暂时无法读取设备'))
assert.ok(!disconnected.html.includes('未找到这个设备'))
const loading = await render('/device-control/mattress', { haStatus: ref(), loading: ref(true) })
const loading = await render('/device-control/environment', { haStatus: ref(), loading: ref(true) })
assert.ok(loading.html.includes('正在读取设备详情'))
})
@@ -350,7 +347,7 @@ test('detail route safely round-trips unusual device IDs; unfinished constitutio
})
test('offline parameter details disable controls and do not present default values as current readings', async () => {
for (const item of [devices[0], devices[1], devices[2]]) {
for (const item of [devices[0], devices[2]]) {
const snapshot = { connected: true, devices: [{ ...item, online: false }], controlParameters: {} }
const { html } = await render(deviceDetailLocation(item.deviceId), { haStatus: ref(snapshot) })
const card = html.match(/<section class="device-card"[\s\S]*?<\/section>/)?.[0]
+1 -1
View File
@@ -13,7 +13,7 @@ const transition = computed(() => lightTransitionForDevice(props.device, lightTr
<template>
<StandardLightCard :device="device" category-label="卧室灯光"
:reported-brightness="transition?.running ? transition.brightnessPercent : undefined"
note="手动调节会停止当前渐变;本灯保留助眠、唤醒及灯灭停止按摩的专属联动。">
note="手动调节会停止当前渐变;本灯支持助眠渐暗和晨起唤醒。">
<template #before-controls>
<div class="light-mode-panel">
<div>
-155
View File
@@ -1,155 +0,0 @@
<script setup lang="ts">
import { toRefs } from 'vue'
import { Slider as VanSlider } from 'vant'
import type { HomeAssistantDiscoveredDevice } from '../../services/health'
import { useDeviceControlContext } from '../../devices/controlContext'
import { useDeviceCardState } from '../../devices/useDeviceCardState'
const props = defineProps<{ device: HomeAssistantDiscoveredDevice }>()
const { device: mattressDevice } = toRefs(props)
const { localParams, operationBusy, applyParam, mattressComfort, mattressActiveSide, mattressModeOptions, setMattressMode, setMattressSelect, mattressFirmnessOptions, mattressFirmnessZones, massagePartOptions } = useDeviceControlContext()
const state = useDeviceCardState(() => props.device)
</script>
<template>
<section class="device-card" v-if="mattressDevice">
<div class="device-head">
<div class="dev-info">
<span class="category-tag">智能承托与温控</span>
<h3>{{ mattressDevice.name }}</h3>
<span class="status-dot" :class="{ online: mattressDevice.online }">
{{ mattressDevice.online ? '设备在线' : '设备离线' }}
</span>
</div>
</div>
<div class="params-body">
<div class="mattress-recommendation">
<strong>室内温度与 BMI 床垫建议</strong>
<p>{{ mattressComfort?.heatingReason || '室温建议读取中' }}</p>
<p>{{ mattressComfort?.firmnessReason || 'BMI 建议读取中' }}</p>
<small v-if="mattressComfort?.indoorTemperatureAvailable">
当前室温 {{ mattressComfort.indoorTemperatureCelsius }}℃
</small>
<small>下次一键启动使用当前建议;下面显示设备读数,可手动覆盖。</small>
</div>
<!-- 左侧加热档位 -->
<div class="param-row">
<div class="param-header">
<span class="p-title">左侧加热档位</span>
<strong class="p-val">{{ state.display('mattress_left_heating', localParams.mattressLeftHeating, ' 档') }}</strong>
</div>
<VanSlider
v-model="localParams.mattressLeftHeating"
:min="0"
:max="4"
:step="1"
:disabled="operationBusy || !state.available('mattress_left_heating')"
active-color="#d66927"
@change="applyParam(mattressDevice.deviceId, 'mattress_left_heating', localParams.mattressLeftHeating)"
/>
<div class="slider-scale">
<span>0 关闭</span>
<span>2 舒适</span>
<span>4 强加热</span>
</div>
</div>
<!-- 右侧加热档位 -->
<div class="param-row">
<div class="param-header">
<span class="p-title">右侧加热档位</span>
<strong class="p-val">{{ state.display('mattress_right_heating', localParams.mattressRightHeating, ' 档') }}</strong>
</div>
<VanSlider
v-model="localParams.mattressRightHeating"
:min="0"
:max="4"
:step="1"
:disabled="operationBusy || !state.available('mattress_right_heating')"
active-color="#d66927"
@change="applyParam(mattressDevice.deviceId, 'mattress_right_heating', localParams.mattressRightHeating)"
/>
<div class="slider-scale">
<span>0 关闭</span>
<span>2 舒适</span>
<span>4 强加热</span>
</div>
</div>
<div class="param-row">
<p class="mattress-mode-note">
左右可分别预选模式,但共用气泵,同一时间仅最近启动的一侧实际运行;另一侧保留预选,处于待机状态。
</p>
</div>
<div class="param-row">
<span class="p-title">左侧承托模式 · {{ !state.readable('mattress_left_mode') ? '状态未确认(保留预选)' : mattressActiveSide === 'left' ? '运行中' : '预选待机' }}</span>
<div class="btn-group mattress-mode-buttons">
<button
v-for="mode in mattressModeOptions"
:key="`left-${mode}`"
:class="{ active: localParams.mattressLeftMode === mode, running: state.readable('mattress_left_mode') && mattressActiveSide === 'left' && localParams.mattressLeftMode === mode }"
:disabled="operationBusy || !state.available('mattress_left_mode')"
@click="setMattressMode('left', mode)"
>{{ mode }}</button>
</div>
</div>
<div class="param-row">
<span class="p-title">右侧承托模式 · {{ !state.readable('mattress_right_mode') ? '状态未确认(保留预选)' : mattressActiveSide === 'right' ? '运行中' : '预选待机' }}</span>
<div class="btn-group mattress-mode-buttons">
<button
v-for="mode in mattressModeOptions"
:key="`right-${mode}`"
:class="{ active: localParams.mattressRightMode === mode, running: state.readable('mattress_right_mode') && mattressActiveSide === 'right' && localParams.mattressRightMode === mode }"
:disabled="operationBusy || !state.available('mattress_right_mode')"
@click="setMattressMode('right', mode)"
>{{ mode }}</button>
</div>
</div>
<details class="mattress-advanced">
<summary>分区软硬度与按摩调节</summary>
<p class="mattress-mode-note">软硬度按左、右各 6 个部位独立设置;BMI 只给出演示起点,并非医学建议。选择按摩部位可能让床垫立即动作。</p>
<div v-for="zone in mattressFirmnessZones" :key="zone.key" class="mattress-select-row">
<label :for="`firmness-${zone.key}`">{{ zone.label }}软硬度</label>
<select :id="`firmness-${zone.key}`"
:value="state.readable(`mattress_firmness_${zone.key}`) ? localParams.mattressFirmness[zone.key] || '' : ''"
:disabled="operationBusy || !state.available(`mattress_firmness_${zone.key}`)"
@change="setMattressSelect(`mattress_firmness_${zone.key}`, $event)">
<option value="" disabled>状态未确认</option>
<option v-for="level in mattressFirmnessOptions" :key="level" :value="level">{{ level }}</option>
</select>
</div>
<div class="mattress-select-row">
<label for="massage-left-part">左侧按摩部位</label>
<select id="massage-left-part" :value="state.readable('mattress_massage_left_part') ? localParams.mattressMassageLeftPart : ''"
:disabled="operationBusy || !state.available('mattress_massage_left_part')"
@change="setMattressSelect('mattress_massage_left_part', $event)">
<option value="" disabled>状态未确认</option>
<option v-for="part in massagePartOptions" :key="part" :value="part">{{ part }}</option>
</select>
</div>
<div class="mattress-select-row">
<label for="massage-right-part">右侧按摩部位</label>
<select id="massage-right-part" :value="state.readable('mattress_massage_right_part') ? localParams.mattressMassageRightPart : ''"
:disabled="operationBusy || !state.available('mattress_massage_right_part')"
@change="setMattressSelect('mattress_massage_right_part', $event)">
<option value="" disabled>状态未确认</option>
<option v-for="part in massagePartOptions" :key="part" :value="part">{{ part }}</option>
</select>
</div>
<div class="mattress-select-row">
<label for="massage-level">按摩力度</label>
<select id="massage-level" :value="state.readable('mattress_massage_level') ? localParams.mattressMassageLevel : ''"
:disabled="operationBusy || !state.available('mattress_massage_level')"
@change="setMattressSelect('mattress_massage_level', $event)">
<option value="" disabled>状态未确认</option>
<option value="轻柔">轻柔</option>
<option value="强劲">强劲</option>
</select>
</div>
</details>
</div>
</section>
</template>
+9 -23
View File
@@ -2,11 +2,8 @@ import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant'
import { healthApi, type HomeAssistantDiscoveredDevice, type HomeAssistantStatus,
type MattressComfort, type TcmAssessmentResult } from '../services/health'
type TcmAssessmentResult } from '../services/health'
import { createDeviceParameterState, parameterLabels, syncDeviceParameters } from '../devices/parameterRegistry'
import { mattressFirmnessOptions, mattressModeOptions, mattressFirmnessZones, massagePartOptions } from '../devices/mattress/parameters'
import { useMattressPreferences } from '../devices/mattress/useMattressPreferences'
import { useMattressControls } from '../devices/mattress/useMattressControls'
import { useDeviceTransitions } from './useDeviceTransitions'
import { useDeviceScenes } from './useDeviceScenes'
import { parameterHasReading, parameterIsAvailable } from '../devices/parameterState'
@@ -15,24 +12,18 @@ import { climateCapabilities } from '../devices/climate/capabilities'
import { outletCapabilities } from '../devices/outlet/capabilities'
import { lightCapabilities } from '../devices/lighting/capabilities'
/** 页面公共交互;家具参数同步/左右预选/渐变轮询各有独立模块。 */
/** 页面公共交互;家具参数同步/渐变轮询各有独立模块。 */
export function useDeviceControl() {
const router = useRouter()
const loading = ref(true)
const haStatus = ref<HomeAssistantStatus>()
const tcmResult = ref<TcmAssessmentResult>()
const mattressComfort = ref<MattressComfort>()
const settingParam = ref<string | null>(null)
const switchingDeviceId = ref<string | null>(null)
const lastUpdatedAt = ref('')
const actionFeedback = ref<{ type: 'success' | 'fail'; message: string }>()
const lightActionBusy = ref(false)
const currentUserId = ref<number>()
const localParams = createDeviceParameterState()
const mattressDevice = computed(() => haStatus.value?.devices.find(device => device.moduleKey === 'mattress')
?? haStatus.value?.devices.find(device => device.moduleKey === undefined && device.category === 'Sleep'))
const { mattressActiveSide, syncModes, commitMode } =
useMattressPreferences(localParams, currentUserId, () => mattressDevice.value?.deviceId)
const { lightTransition, musicTransition, syncLightTransitionStatus, syncMusicTransitionStatus } =
useDeviceTransitions(localParams, async () => {
await loadStatus(false, true)
@@ -56,7 +47,6 @@ export function useDeviceControl() {
needsConstitution: () => { void router.push('/tcm-assessment') },
refresh: () => loadStatus(), refreshLater: () => loadStatus(false, true), feedback: setFeedback,
})
const { setMattressMode, setMattressSelect } = useMattressControls(mattressDevice, applyParam, loadStatus, commitMode)
function setFeedback(type: 'success' | 'fail', message: string) {
if (active) actionFeedback.value = { type, message }
}
@@ -106,14 +96,12 @@ const currentOperationText = computed(() => {
if (!active || sequence !== loadSequence) return
haStatus.value = status
if (dashboard) {
currentUserId.value = dashboard.user.id
tcmResult.value = dashboard.tcmResult
mattressComfort.value = dashboard.mattressComfort
}
const controls = status.controlParameters ?? {}
syncDeviceParameters(localParams, controls)
syncModes(controls)
await Promise.all([syncLightTransitionStatus().catch(() => undefined), syncMusicTransitionStatus().catch(() => undefined)])
const hasSceneLights = Boolean(status.devices?.some(device => device.category === 'Lighting' && device.moduleKey))
await Promise.all([syncLightTransitionStatus(hasSceneLights).catch(() => undefined), syncMusicTransitionStatus().catch(() => undefined)])
if (!active || sequence !== loadSequence) return
lastUpdatedAt.value = new Intl.DateTimeFormat('zh-CN', {
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
@@ -260,8 +248,7 @@ async function applyParam(deviceId: string, paramType: string, val: unknown, ent
const previousControls = haStatus.value?.controlParameters ?? {}
const key = `${deviceId}_${paramType}`
settingParam.value = key
const label = parameterLabels[paramType]
|| (paramType.startsWith('mattress_firmness_') ? '床垫分区软硬度' : '设备参数')
const label = parameterLabels[paramType] || '设备参数'
const loadingToast = operationToast(`正在设置${label}…`)
try {
const res = await healthApi.setParameter({
@@ -283,7 +270,6 @@ async function applyParam(deviceId: string, paramType: string, val: unknown, ent
if (!active) return false
const message = err instanceof Error ? err.message : `${label}设置失败`
syncDeviceParameters(localParams, previousControls)
syncModes(previousControls)
await loadStatus()
if (!active) return false
setFeedback('fail', message)
@@ -315,9 +301,9 @@ function handleBack() {
for (const toast of operationToasts) toast.close()
operationToasts.clear()
})
return { router, loading, haStatus, tcmResult, mattressComfort, sceneRunning, settingParam, switchingDeviceId,
return { router, loading, haStatus, tcmResult, sceneRunning, settingParam, switchingDeviceId,
lastUpdatedAt, actionFeedback, lightTransition, musicTransition, lightActionBusy, localParams, operationBusy,
currentOperationText, mattressActiveSide, mattressFirmnessOptions, mattressModeOptions, mattressFirmnessZones,
massagePartOptions, loadStatus, controlLightTransition, isDeviceTurnedOn, isDeviceControlAvailable, isParameterAvailable, hasParameterReading, toggleDevice, controlSpeaker,
applyParam, setMattressMode, setMattressSelect, executeScene, handleBack }
currentOperationText,
loadStatus, controlLightTransition, isDeviceTurnedOn, isDeviceControlAvailable, isParameterAvailable, hasParameterReading, toggleDevice, controlSpeaker,
applyParam, executeScene, handleBack }
}
+7 -1
View File
@@ -29,8 +29,14 @@ export function useDeviceTransitions(parameters: DeviceParameterState, onLightEn
try { await syncMusicTransitionStatus() } catch { /* 下个周期重试。 */ }
finally { musicPolling = false }
}
async function syncLightTransitionStatus() {
async function syncLightTransitionStatus(enabled = true) {
const sequence = ++lightSequence
if (!enabled) {
lightTransition.value = undefined
if (lightTimer) clearInterval(lightTimer)
lightTimer = undefined
return
}
const status = await healthApi.lightTransitionStatus()
if (!active || sequence !== lightSequence) return
lightTransition.value = status
+1 -2
View File
@@ -4,7 +4,6 @@ import DehumidifierCard from '../components/devices/DehumidifierCard.vue'
import LightingCard from '../components/devices/LightingCard.vue'
import AudioCard from '../components/devices/AudioCard.vue'
import FragranceCard from '../components/devices/FragranceCard.vue'
import MattressCard from '../components/devices/MattressCard.vue'
import EnvironmentCard from '../components/devices/EnvironmentCard.vue'
import ScaleCard from '../components/devices/ScaleCard.vue'
import GenericDeviceCard from '../components/devices/GenericDeviceCard.vue'
@@ -17,7 +16,7 @@ import { deviceModuleKey } from './deviceKinds'
/** 新增专属卡片只注册这里;主页面不增加家具分支。 */
const cards: Record<string, Component> = {
dehumidifier: DehumidifierCard, lighting: LightingCard, audio: AudioCard,
fragrance: FragranceCard, mattress: MattressCard, environment: EnvironmentCard,
fragrance: FragranceCard, environment: EnvironmentCard,
climate: ClimateCard, curtain: CurtainCard, outlet: OutletCard
}
export function deviceCardFor(device: HomeAssistantDiscoveredDevice): Component {
+1 -1
View File
@@ -2,7 +2,7 @@ import type { HomeAssistantDiscoveredDevice } from '../services/health'
const legacyCategories: Record<string, string> = {
EnvironmentControl: 'dehumidifier', Lighting: 'lighting', Media: 'audio',
Fragrance: 'fragrance', Sleep: 'mattress', EnvironmentSensor: 'environment',
Fragrance: 'fragrance', EnvironmentSensor: 'environment',
}
/** 新接口未绑定模块时不借用另一台同类设备的参数;仅兼容旧接口没有 moduleKey 的情况。 */
-11
View File
@@ -51,11 +51,6 @@ function metric(device: HomeAssistantDiscoveredDevice, key: string): number | un
function formatted(value: number | undefined, unit: string): string {
return value === undefined ? '' : `${Math.round(value * 10) / 10}${unit}`
}
function ownState(device: HomeAssistantDiscoveredDevice, input: SummaryInput, parameter: string): string | undefined {
const state = input.controls?.[parameter]
return state?.available && !['unknown', 'unavailable', ''].includes(state.state) &&
device.entities.some(entity => entity.entityId === state.entityId) ? state.state : undefined
}
function powerText(power: boolean | null, running = '运行中'): string {
return power === null ? '状态未确认' : power ? running : '已关闭'
}
@@ -95,12 +90,6 @@ const presenters: Record<string, Presenter> = {
fragrance(_device, _input, power) {
return { statusText: powerText(power, '香薰已开启'), metricText: '香薰与夜灯独立控制' }
},
mattress(device, input) {
const right = ownState(device, input, 'mattress_massage_right_part')
const left = ownState(device, input, 'mattress_massage_left_part')
return { statusText: right && right !== '无' ? '右侧按摩中' : left && left !== '无' ? '左侧按摩中' : '已连接',
metricText: '按摩 · 加热 · 承托' }
},
environment(device) {
const values = [formatted(metric(device, 'temperature'), '℃'), formatted(metric(device, 'humidity'), '%')].filter(Boolean)
return { statusText: '正在监测', metricText: values.join(' · ') || '查看环境指标' }
-36
View File
@@ -1,36 +0,0 @@
import { clamp, numberValue, type ParameterSnapshot } from '../parameterState'
export const mattressFirmnessOptions = ['最软', '很软', '稍软', '稍硬', '很硬', '最硬']
export const mattressModeOptions = ['无', '瑜伽助眠', '智能适配', '智能腰托']
export const massagePartOptions = ['无', '背部', '腰部', '牵引', '腿部', '全身']
export const mattressFirmnessZones = [
{ key: 'left_shoulder', label: '左肩' }, { key: 'right_shoulder', label: '右肩' },
{ key: 'left_back', label: '左背' }, { key: 'right_back', label: '右背' },
{ key: 'left_waist', label: '左腰' }, { key: 'right_waist', label: '右腰' },
{ key: 'left_lumbar', label: '左腰椎' }, { key: 'right_lumbar', label: '右腰椎' },
{ key: 'left_hip', label: '左臀' }, { key: 'right_hip', label: '右臀' },
{ key: 'left_leg', label: '左腿' }, { key: 'right_leg', label: '右腿' }
]
export const defaults = { mattressLeftHeating: 0, mattressRightHeating: 0, mattressLeftMode: '智能适配',
mattressRightMode: '智能适配', mattressFirmness: {} as Record<string, string>, mattressMassageLeftPart: '无',
mattressMassageRightPart: '无', mattressMassageLevel: '轻柔' }
export const labels = { mattress_left_heating: '床垫左侧加热', mattress_right_heating: '床垫右侧加热',
mattress_left_mode: '床垫左侧承托模式', mattress_right_mode: '床垫右侧承托模式',
mattress_massage_left_part: '左侧按摩部位', mattress_massage_right_part: '右侧按摩部位', mattress_massage_level: '按摩力度' }
export function sync(state: typeof defaults, controls: ParameterSnapshot) {
for (const [parameter, property] of [['mattress_left_heating', 'mattressLeftHeating'],
['mattress_right_heating', 'mattressRightHeating']] as const) {
const value = numberValue(controls[parameter]?.state)
if (controls[parameter]?.available && value !== undefined) state[property] = clamp(value, 0, 4)
}
for (const zone of mattressFirmnessZones) {
const control = controls['mattress_firmness_' + zone.key]
if (control?.available && mattressFirmnessOptions.includes(control.state)) state.mattressFirmness[zone.key] = control.state
}
for (const [parameter, property] of [['mattress_massage_left_part', 'mattressMassageLeftPart'],
['mattress_massage_right_part', 'mattressMassageRightPart']] as const) {
const control = controls[parameter]
if (control?.available && massagePartOptions.includes(control.state)) state[property] = control.state
}
const level = controls.mattress_massage_level
if (level?.available && ['轻柔', '强劲'].includes(level.state)) state.mattressMassageLevel = level.state
}
@@ -1,27 +0,0 @@
import { showConfirmDialog } from 'vant'
import { onUnmounted, type ComputedRef } from 'vue'
import type { HomeAssistantDiscoveredDevice } from '../../services/health'
export function useMattressControls(device: ComputedRef<HomeAssistantDiscoveredDevice | undefined>,
applyParam: (deviceId: string, parameter: string, value: unknown) => Promise<boolean>,
loadStatus: () => Promise<void>, commitMode: (side: 'left' | 'right', mode: string) => void) {
let active = true
onUnmounted(() => { active = false })
async function setMattressMode(side: 'left' | 'right', mode: string) {
if (!active || !device.value) return
if (await applyParam(device.value.deviceId, 'mattress_' + side + '_mode', mode) && active) commitMode(side, mode)
}
async function setMattressSelect(parameterType: string, event: Event) {
if (!active || !device.value) return
const deviceId = device.value.deviceId
const value = (event.target as HTMLSelectElement).value
if (parameterType.startsWith('mattress_massage_') && value !== '无') {
try { await showConfirmDialog({ title: '确认启动床垫按摩',
message: '按摩或牵引可能让床垫立即动作,请确认设备周围安全后继续。' }) }
catch { if (active) await loadStatus(); return }
}
// 确认框等待期间可能离开页面或设备被移除,不能向新的床垫误发命令。
if (active && device.value?.deviceId === deviceId) await applyParam(deviceId, parameterType, value)
}
return { setMattressMode, setMattressSelect }
}
@@ -1,47 +0,0 @@
import { ref, type Ref } from 'vue'
import type { DeviceParameterState } from '../parameterRegistry'
import type { ParameterSnapshot } from '../parameterState'
import { mattressModeOptions } from './parameters'
export function useMattressPreferences(localParams: DeviceParameterState,
currentUserId: Ref<number | undefined>, getDeviceId: () => string | undefined) {
const mattressActiveSide = ref<'left' | 'right' | null>(null)
function storageKey() {
const deviceId = getDeviceId()
return currentUserId.value && deviceId ? 'evergreen-mattress-modes-' + currentUserId.value + '-' + deviceId : undefined
}
function readPreference(): { left: string; right: string } | undefined {
const key = storageKey()
if (!key) return undefined
try {
const saved = JSON.parse(localStorage.getItem(key) || 'null')
return mattressModeOptions.includes(saved?.left) && mattressModeOptions.includes(saved?.right) ? saved : undefined
} catch { return undefined }
}
function savePreference() {
const key = storageKey()
if (!key) return
try { localStorage.setItem(key, JSON.stringify({ left: localParams.mattressLeftMode, right: localParams.mattressRightMode })) }
catch { /* 禁止存储时仅保留本次页面预选。 */ }
}
function syncModes(controls: ParameterSnapshot) {
const left = controls.mattress_left_mode?.available ? controls.mattress_left_mode.state : undefined
const right = controls.mattress_right_mode?.available ? controls.mattress_right_mode.state : undefined
const leftRunning = Boolean(left && mattressModeOptions.includes(left) && left !== '无')
const rightRunning = Boolean(right && mattressModeOptions.includes(right) && right !== '无')
// 双侧云缓存尚未同步时保留已确认的一侧,不把两侧预选当作两侧物理运行。
mattressActiveSide.value = leftRunning && rightRunning ? mattressActiveSide.value
: rightRunning ? 'right' : leftRunning ? 'left' : null
const preference = readPreference()
localParams.mattressLeftMode = mattressActiveSide.value === 'left' ? left! : preference?.left ?? '智能适配'
localParams.mattressRightMode = mattressActiveSide.value === 'right' ? right! : preference?.right ?? '智能适配'
}
function commitMode(side: 'left' | 'right', mode: string) {
if (side === 'left') localParams.mattressLeftMode = mode
else localParams.mattressRightMode = mode
if (mode !== '无') mattressActiveSide.value = side
else if (mattressActiveSide.value === side) mattressActiveSide.value = null
savePreference()
}
return { mattressActiveSide, syncModes, commitMode }
}
+3 -4
View File
@@ -3,22 +3,21 @@ import * as dehumidifier from './dehumidifier/parameters'
import * as lighting from './lighting/parameters'
import * as audio from './audio/parameters'
import * as fragrance from './fragrance/parameters'
import * as mattress from './mattress/parameters'
import * as climate from './climate/parameters'
import * as curtain from './curtain/parameters'
import type { ParameterSnapshot } from './parameterState'
export const parameterLabels: Record<string, string> = {
...dehumidifier.labels, ...lighting.labels, ...audio.labels, ...fragrance.labels, ...mattress.labels,
...dehumidifier.labels, ...lighting.labels, ...audio.labels, ...fragrance.labels,
...climate.labels, ...curtain.labels
}
export function createDeviceParameterState() {
return reactive({ ...dehumidifier.defaults, ...lighting.defaults, ...audio.defaults,
...fragrance.defaults, ...mattress.defaults, ...climate.defaults, ...curtain.defaults, mattressFirmness: {} as Record<string, string> })
...fragrance.defaults, ...climate.defaults, ...curtain.defaults })
}
export type DeviceParameterState = ReturnType<typeof createDeviceParameterState>
export function syncDeviceParameters(state: DeviceParameterState, controls: ParameterSnapshot) {
dehumidifier.sync(state, controls); lighting.sync(state, controls); audio.sync(state, controls)
fragrance.sync(state, controls); mattress.sync(state, controls)
fragrance.sync(state, controls)
climate.sync(state, controls); curtain.sync(state, controls)
}
+2
View File
@@ -7,6 +7,7 @@ import ProfileView from './views/ProfileView.vue'
import DeviceControlView from './views/DeviceControlView.vue'
import DeviceControlLayout from './views/DeviceControlLayout.vue'
import DeviceDetailView from './views/DeviceDetailView.vue'
import SleepDataView from './views/SleepDataView.vue'
import { hasToken } from './services/auth'
const router = createRouter({
@@ -17,6 +18,7 @@ const router = createRouter({
{ path: '/auth', component: AuthView, meta: { guest: true } },
{ path: '/onboarding', redirect: '/assessment' },
{ path: '/dashboard', component: DashboardView },
{ path: '/sleep-data', component: SleepDataView },
{ path: '/assessment', component: AssessmentView },
{ path: '/tcm-assessment', component: TcmAssessmentView },
{ path: '/profile', component: ProfileView },
+2 -18
View File
@@ -47,11 +47,6 @@ export type PersonalizedSceneConfig = {
enableUv: boolean
lightBrightnessPercent: number
lightColorTemperatureKelvin: number
mattressTargetTemp: number
mattressLeftFirmness: number
mattressRightFirmness: number
mattressHeatingLevel: number
mattressMode: string
enableFragrance: boolean
fragranceLevel: number
enableSpeakerSleepMode: boolean
@@ -97,24 +92,13 @@ export type Dashboard = {
bmiStatus?: string
sceneConfig?: PersonalizedSceneConfig
tcmResult?: TcmAssessmentResult
mattressComfort?: MattressComfort
environmentAdvice?: EnvironmentAdvice
}
export type MattressComfort = {
bmi?: number | null
firmness?: string | null
heatingLevel: number
isWinter: boolean
outdoorTemperatureCelsius?: number | null
feelsLikeCelsius?: number | null
weatherAvailable: boolean
weatherObservedAt?: string | null
weatherReason: string
firmnessReason: string
export type EnvironmentAdvice = {
indoorTemperatureCelsius?: number | null
indoorTemperatureAvailable: boolean
indoorTemperatureObservedAt?: string | null
heatingReason: string
climateAdvice?: ClimateAdvice
}
+65
View File
@@ -0,0 +1,65 @@
import http from './http'
export const ib43Metrics = [
{ key: 'heartRate', label: '心率' },
{ key: 'respiration', label: '呼吸' },
{ key: 'presence', label: '在床' },
{ key: 'snoring', label: '打鼾' },
] as const
export type Ib43Metric = typeof ib43Metrics[number]['key']
export type Ib43Bed = {
id: string
bedName: string
side: 'left' | 'right'
simulation: boolean
startedAtMs: number | string
endedAtMs?: number | string | null
}
type Ib43Reading = { value: number | null; receivedAt?: string | null }
export type Ib43Current = {
bed: Ib43Bed
transport: string
active: boolean
readings: Partial<Record<Ib43Metric, Ib43Reading & { freshness: 'recent' | 'stale' | 'unknown' }>>
}
export type Ib43HistoryItem = {
id: number | string
receivedAtMs: number | string
readings: Partial<Record<Ib43Metric, Ib43Reading>>
}
type Ib43History = { items: Ib43HistoryItem[]; nextBeforeId?: number | string | null }
export type Ib43HistoryQuery = { fromMs: number; toMs: number; beforeId?: number | string; take: number }
const bindingsUrl = '/api/health/ib43/bindings'
const bedUrl = (id: string) => `${bindingsUrl}/${encodeURIComponent(id)}`
export const ib43Api = {
bindings: () => http.get<never, Ib43Bed[]>(bindingsUrl),
current: (id: string) => http.get<never, Ib43Current>(`${bedUrl(id)}/current`),
history: (id: string, params: Ib43HistoryQuery) => http.get<never, Ib43History>(`${bedUrl(id)}/history`, { params }),
}
export function displayIb43Value(metric: Ib43Metric, value?: number | null) {
if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
if (metric === 'presence') return value === 1 ? '在床' : value === 0 ? '离床' : '—'
if (metric === 'snoring') return value === 1 ? '打鼾' : value === 0 ? '未打鼾' : '—'
return String(value)
}
const timeFormat = new Intl.DateTimeFormat('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
})
export function formatIb43Time(value?: number | string | null) {
if (value == null || value === '') return ''
// 最近读数的 UTC 时间经过 API 序列化后可能没有偏移;历史使用 Unix 毫秒。
const milliseconds = typeof value === 'number' || /^\d+$/.test(value) ? Number(value) : Date.parse(
/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(value) ? `${value.replace(' ', 'T')}Z` : value,
)
return Number.isFinite(new Date(milliseconds).getTime()) ? timeFormat.format(milliseconds) : ''
}
-35
View File
@@ -317,35 +317,6 @@
color: #8fa099;
}
.control-page .mattress-mode-note {
margin: 0;
padding: 9px 11px;
border-radius: 9px;
background: #fff7e8;
color: #8a6428;
font-size: 11px;
line-height: 1.55;
}
.control-page .mattress-recommendation {
padding: 12px;
border: 1px solid #cde3dc;
border-radius: 12px;
background: #f3faf7;
color: #174d40;
font-size: 12px;
line-height: 1.55;
}
.control-page .mattress-recommendation strong { font-size: 13px; }
.control-page .mattress-recommendation p { margin: 7px 0 0; }
.control-page .mattress-recommendation small { display: block; margin-top: 6px; color: #6a8479; }
.control-page .mattress-advanced { border-top: 1px solid #e8efea; padding-top: 12px; }
.control-page .mattress-advanced summary { cursor: pointer; color: #0c5045; font-weight: 700; font-size: 14px; }
.control-page .mattress-advanced .mattress-mode-note { margin: 12px 0; }
.control-page .mattress-select-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px 0; border-bottom: 1px solid #edf1ee; }
.control-page .mattress-select-row label { color: #556c64; font-size: 12px; }
.control-page .mattress-select-row select { width: 48%; min-height: 36px; border: 1px solid #d9e6de; border-radius: 9px; background: #fff; padding: 5px 8px; color: #174d40; font-size: 12px; }
.control-page .light-mode-panel {
padding: 12px;
border-radius: 12px;
@@ -453,12 +424,6 @@
font-weight: 700;
}
.control-page .mattress-mode-buttons button.active:not(.running) {
background: #e4f1ec;
color: #0c5045;
border-color: #87b9a7;
}
.control-page .btn-group button:disabled,
.control-page .mini-toggle:disabled {
opacity: 0.55;
+1 -1
View File
@@ -155,7 +155,7 @@ input, textarea { accent-color: var(--green); }
#app .tab-label { font-size: 11px; }
#app .control-page .control-content { padding: 16px; }
#app .control-page .param-row { padding-top: 17px; padding-bottom: 17px; }
#app .control-page :is(.p-tip, .scale-note, .mattress-mode-note) { font-size: 12px; line-height: 1.7; }
#app .control-page :is(.p-tip, .scale-note) { font-size: 12px; line-height: 1.7; }
#app .control-page .mini-toggle { min-height: 36px; }
#app .control-page .device-tile-power { width: 42px; height: 42px; }
#app .control-page .device-tile-category { width: calc(100% - 46px); }
+14 -9
View File
@@ -27,10 +27,9 @@ const sceneHint = computed(() => {
if (!dashboard.value?.tcmResult?.hasCompleted) return '完成中医四诊、生成体质倾向后,即可一键开启。'
if (!homeAssistant.value?.connected) return '设备连接暂时不可用,可进入设备总览检查并重试。'
if (sceneAvailable.value === 0) return '当前没有可用场景设备,请在设备总览检查连接。'
return `${sceneAvailable.value} 台场景设备可用 · 加热看室温,承托看 BMI`
return `${sceneAvailable.value} 台场景设备可用 · 根据室温调节空调`
})
const comfortReason = computed(() => [dashboard.value?.mattressComfort?.heatingReason || dashboard.value?.mattressComfort?.weatherReason,
dashboard.value?.mattressComfort?.firmnessReason].filter(Boolean).join(';'))
const comfortReason = computed(() => dashboard.value?.environmentAdvice?.climateAdvice?.reason || '')
async function load() {
const sequence = ++loadSequence, statusRequest = ++statusSequence
@@ -105,15 +104,21 @@ onUnmounted(() => { active = false; loadSequence++; statusSequence++ })
<strong>查看舒睡设备</strong><small>设备总览、快捷开关与完整参数</small>
</span></span><span class="arrow" aria-hidden="true">›</span>
</button>
<button class="detail-entry-bar" type="button" @click="router.push('/sleep-data')">
<span class="entry-left"><span class="entry-symbol" aria-hidden="true">☾</span><span>
<strong>睡眠数据</strong><small>最近读数与历史记录</small>
</span></span><span class="arrow" aria-hidden="true">›</span>
</button>
<details v-if="dashboard.tcmResult?.hasCompleted" class="startup-preset-details">
<summary>查看体质启动预设</summary>
<div class="startup-params-tags">
<div class="startup-param-badge"><span class="lbl">恒湿目标</span><strong>{{ dashboard.sceneConfig?.targetHumidity ?? '--' }}% · {{ dashboard.sceneConfig?.fanLevel || '待读取' }}</strong></div>
<div class="startup-param-badge"><span class="lbl">助眠灯光</span><strong>{{ dashboard.sceneConfig?.lightBrightnessPercent ?? '--' }}% 渐暗 · {{ dashboard.sceneConfig?.lightColorTemperatureKelvin ?? '--' }}K</strong></div>
<div class="startup-param-badge"><span class="lbl">体质音乐</span><strong>循环播放,50% 起每 5 秒降 1%</strong></div>
<div class="startup-param-badge"><span class="lbl">智能床垫</span><strong>{{ dashboard.mattressComfort?.heatingLevel ?? 0 }} 档加热 · {{ dashboard.mattressComfort?.firmness || '待填写 BMI' }}</strong></div>
<div v-if="homeAssistant?.scenePresets?.length" class="startup-params-tags">
<div v-for="preset in homeAssistant.scenePresets" :key="`${preset.entityId}-${preset.action}`" class="startup-param-badge">
<span class="lbl">{{ preset.deviceName }}</span><strong>{{ preset.detail || preset.action }}</strong>
<small v-if="!preset.available">{{ preset.availabilityMessage }}</small>
</div>
</div>
<p class="startup-card-desc">右侧全身轻柔按摩;灯灭后停止按摩。香型需人工更换。</p>
<p v-else class="startup-card-desc">暂无可显示的设备预设。</p>
<p class="startup-card-desc">香型需人工更换。</p>
<p v-if="dashboard.sceneConfig?.enableUv" class="startup-card-desc">除湿机预设开启 UV 消杀。</p>
<p v-if="comfortReason" class="startup-card-desc">{{ comfortReason }}</p>
</details>
+245
View File
@@ -0,0 +1,245 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import AppTabBar from '../components/AppTabBar.vue'
import { usePageRequest } from '../composables/usePageRequest'
import { displayIb43Value, formatIb43Time, ib43Api, ib43Metrics,
type Ib43Bed, type Ib43Current, type Ib43HistoryItem, type Ib43HistoryQuery } from '../services/ib43'
const beds = ref<Ib43Bed[]>([])
const bedId = ref('')
const selectedBed = computed(() => beds.value.find(bed => bed.id === bedId.value))
const current = ref<Ib43Current>()
const history = ref<Ib43HistoryItem[]>([])
const historyDays = ref(7)
const nextBeforeId = ref<number | string>()
const bindingsLoading = ref(true)
const currentLoading = ref(false)
const historyLoading = ref(false)
const bindingsError = ref('')
const currentError = ref('')
const historyError = ref('')
const bindingsRequest = usePageRequest()
const currentRequest = usePageRequest()
const historyRequest = usePageRequest()
let historyRange: Pick<Ib43HistoryQuery, 'fromMs' | 'toMs'>
let refreshTimer: ReturnType<typeof setInterval>
function message(error: unknown, fallback: string) {
return error instanceof Error && error.message ? error.message : fallback
}
function bedLabel(bed: Ib43Bed) {
const side = bed.side === 'left' ? '左侧' : '右侧'
const name = bed.bedName.endsWith(side) ? bed.bedName : `${bed.bedName} · ${side}`
return bed.endedAtMs == null ? name : `${name}(已解绑)`
}
const connectionLabel = computed(() => {
if (!current.value) return ''
if (!current.value.active) return '已解绑'
switch (current.value.transport) {
case 'connected': return '数据服务已连接'
case 'connecting': return '数据服务正在连接'
case 'disconnected': return '数据服务连接中断'
case 'disabled': return '数据采集未开启'
case 'unconfigured': return '设备未配置采集'
default: return '连接状态未知'
}
})
async function loadBindings() {
const requestId = bindingsRequest.begin()
currentRequest.begin()
historyRequest.begin()
bindingsLoading.value = true
bindingsError.value = ''
try {
const result = await ib43Api.bindings()
if (!bindingsRequest.isCurrent(requestId)) return
beds.value = result
bedId.value = result.find(bed => bed.id === bedId.value)?.id ??
result.find(bed => bed.endedAtMs == null)?.id ?? result[0]?.id ?? ''
if (bedId.value) loadBed()
} catch (error) {
if (bindingsRequest.isCurrent(requestId)) bindingsError.value = message(error, '暂时无法读取床位')
} finally {
if (bindingsRequest.isCurrent(requestId)) bindingsLoading.value = false
}
}
async function loadCurrent() {
const id = bedId.value
const requestId = currentRequest.begin()
currentLoading.value = true
currentError.value = ''
try {
const result = await ib43Api.current(id)
if (currentRequest.isCurrent(requestId)) current.value = result
} catch (error) {
if (currentRequest.isCurrent(requestId)) currentError.value = message(error, '暂时无法读取最近数据')
} finally {
if (currentRequest.isCurrent(requestId)) currentLoading.value = false
}
}
async function loadHistory(append = false) {
const id = bedId.value
const requestId = historyRequest.begin()
const beforeId = append ? nextBeforeId.value : undefined
if (!append) {
const toMs = Date.now() + 1
historyRange = { fromMs: toMs - historyDays.value * 86400000, toMs }
history.value = []
nextBeforeId.value = undefined
}
historyLoading.value = true
historyError.value = ''
try {
const result = await ib43Api.history(id, { ...historyRange, beforeId, take: 20 })
if (!historyRequest.isCurrent(requestId)) return
history.value = append ? [...history.value, ...result.items] : result.items
nextBeforeId.value = result.nextBeforeId ?? undefined
} catch (error) {
if (historyRequest.isCurrent(requestId)) historyError.value = message(error, '暂时无法读取历史记录')
} finally {
if (historyRequest.isCurrent(requestId)) historyLoading.value = false
}
}
function loadBed() {
current.value = undefined
void loadCurrent()
void loadHistory()
}
onMounted(() => {
void loadBindings()
refreshTimer = setInterval(() => {
if (!document.hidden && !bindingsLoading.value && !bindingsError.value && !currentLoading.value &&
selectedBed.value && selectedBed.value.endedAtMs == null) void loadCurrent()
}, 30000)
})
onUnmounted(() => clearInterval(refreshTimer))
</script>
<template>
<main class="page-shell sleep-data-page">
<header class="sleep-heading">
<div>
<RouterLink class="sleep-back" to="/dashboard">‹ 返回首页</RouterLink>
<h1>睡眠数据</h1>
</div>
<button class="sleep-button" type="button" :disabled="bindingsLoading" @click="loadBindings">刷新</button>
</header>
<section v-if="bindingsLoading" class="section-card page-load-state" role="status">
<span class="page-loading-mark" aria-hidden="true"></span><p>正在读取床位…</p>
</section>
<section v-else-if="bindingsError" class="section-card page-error-state" role="alert">
<h2>暂时无法读取床位</h2><p>{{ bindingsError }}</p>
<button class="retry-button" type="button" @click="loadBindings">重新加载</button>
</section>
<section v-else-if="!selectedBed" class="section-card page-load-state">
<h2>暂无绑定床位</h2><p>绑定床位后,这里会显示该侧的观测记录。</p>
</section>
<template v-else>
<section class="section-card sleep-bed" aria-label="当前床位">
<label v-if="beds.length > 1" for="sleep-bed">我的床位</label>
<span v-else class="sleep-muted">我的床位</span>
<select v-if="beds.length > 1" id="sleep-bed" v-model="bedId" @change="loadBed">
<option v-for="bed in beds" :key="bed.id" :value="bed.id">{{ bedLabel(bed) }}</option>
</select>
<strong v-else>{{ bedLabel(selectedBed) }}</strong>
<div class="sleep-bed-status">
<span v-if="selectedBed.simulation" class="sleep-chip">模拟设备</span>
<span v-if="connectionLabel">{{ connectionLabel }}</span>
</div>
</section>
<section class="section-card" aria-labelledby="sleep-current-title">
<div class="sleep-section-title"><h2 id="sleep-current-title">最近读数</h2></div>
<p v-if="currentLoading && !current" class="sleep-muted" role="status">正在读取最近读数…</p>
<div v-if="currentError" class="sleep-error" role="alert">
<p>{{ currentError }}</p>
<button class="sleep-button" type="button" :disabled="currentLoading" @click="loadCurrent">重试</button>
</div>
<dl v-if="current" class="sleep-metrics">
<div v-for="metric in ib43Metrics" :key="metric.key">
<dt>{{ metric.label }}</dt>
<dd class="sleep-metric-value">{{ displayIb43Value(metric.key, current.readings[metric.key]?.value) }}</dd>
<dd class="sleep-metric-meta">
<small>{{ formatIb43Time(current.readings[metric.key]?.receivedAt) || '暂无上报' }}</small>
<span v-if="current.readings[metric.key]?.freshness === 'stale'" class="sleep-chip stale">数据已过期</span>
<small v-else-if="current.readings[metric.key]?.receivedAt && current.readings[metric.key]?.value == null">暂无有效读数</small>
</dd>
</div>
</dl>
</section>
<section class="section-card" aria-labelledby="sleep-history-title">
<div class="sleep-section-title">
<h2 id="sleep-history-title">历史记录</h2>
<select v-model.number="historyDays" aria-label="历史时间范围" @change="loadHistory()">
<option :value="7">最近 7 天</option>
<option :value="1">最近 24 小时</option>
</select>
</div>
<p v-if="historyLoading && history.length === 0" class="sleep-muted" role="status">正在读取历史记录…</p>
<p v-else-if="!historyError && history.length === 0" class="sleep-muted">这段时间暂无记录。</p>
<ol v-if="history.length" class="sleep-history">
<li v-for="item in history" :key="item.id">
<time>{{ formatIb43Time(item.receivedAtMs) }}</time>
<dl>
<template v-for="metric in ib43Metrics" :key="metric.key">
<div v-if="item.readings[metric.key]">
<dt>{{ metric.label }}</dt>
<dd>{{ displayIb43Value(metric.key, item.readings[metric.key]?.value) }}</dd>
</div>
</template>
</dl>
</li>
</ol>
<div v-if="historyError" class="sleep-error" role="alert">
<p>{{ historyError }}</p>
<button class="sleep-button" type="button" @click="loadHistory(history.length > 0)">重试</button>
</div>
<button v-else-if="nextBeforeId != null" class="sleep-button sleep-more" type="button"
:disabled="historyLoading" @click="loadHistory(true)">{{ historyLoading ? '正在加载…' : '加载更多' }}</button>
</section>
</template>
<AppTabBar />
</main>
</template>
<style scoped>
.sleep-heading, .sleep-section-title { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.sleep-heading { margin-bottom: 18px; }
.sleep-heading h1 { margin: 5px 0 0; font-size: 26px; line-height: 1.3; }
.sleep-back { display: inline-flex; align-items: center; min-height: 40px; color: var(--green); font-size: 13px; text-decoration: none; }
.sleep-section-title { margin-bottom: 14px; }
.sleep-data-page h2 { margin: 0; font-size: 17px; }
.sleep-button, .sleep-data-page select { min-height: 44px; border: 1px solid #d9e5dc; border-radius: 12px; background: #f4f8f2; color: #0c5045; padding: 8px 12px; font: inherit; font-size: 13px; }
.sleep-button:disabled { opacity: .55; }
.sleep-bed { display: grid; gap: 8px; overflow-wrap: anywhere; }
.sleep-bed label, .sleep-bed-status, .sleep-muted, .sleep-metrics small { font-size: 13px; color: var(--muted-text); }
.sleep-bed-status { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
.sleep-chip { display: inline-block; width: fit-content; padding: 4px 8px; border-radius: 8px; background: #e9f2e9; color: #235e49; font-size: 12px; }
.sleep-chip.stale { background: #f9eedc; color: #795324; }
.sleep-metrics { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin: 0; }
.sleep-metrics > div { display: grid; align-content: start; gap: 5px; padding: 12px; border-radius: 13px; background: #f6f8f3; }
.sleep-metrics dt, .sleep-history dt { color: var(--muted-text); font-size: 13px; }
.sleep-metrics dd { margin: 0; }
.sleep-metric-value { font-size: 22px; font-weight: 700; }
.sleep-metric-meta { display: grid; gap: 5px; }
.sleep-metrics small, .sleep-history time { font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.sleep-history { list-style: none; padding: 0; margin: 0; }
.sleep-history li { border-top: 1px solid #edf0e8; padding: 12px 0; }
.sleep-history time { color: #315a4a; font-size: 13px; font-weight: 600; }
.sleep-history dl { display: flex; flex-wrap: wrap; gap: 8px 16px; margin: 8px 0 0; }
.sleep-history dl > div { display: flex; align-items: baseline; gap: 5px; }
.sleep-history dd { margin: 0; font-size: 14px; }
.sleep-more { width: 100%; margin-top: 8px; }
.sleep-error { color: #8b432f; font-size: 13px; padding: 8px 0; overflow-wrap: anywhere; }
.sleep-error p { margin: 0 0 8px; }
</style>
+2 -2
View File
@@ -168,9 +168,9 @@ async function submit() {
<p class="capability-note">香型需人工更换,体质音乐可由音箱自动播放,室温仅供参考;一键启动只下发当前已支持的设备参数。</p>
<div class="parameter-preview">
<span>一键启动预设</span>
<p>湿度 {{ result.sceneConfig.targetHumidity }}% · 灯光 {{ result.sceneConfig.lightColorTemperatureKelvin }}K</p>
<p>目标湿度 {{ result.sceneConfig.targetHumidity }}%</p>
<p>香氛{{ result.sceneConfig.enableFragrance ? '开启' : '关闭' }} · 体质音乐循环播放,从 50% 每 5 秒降 1% 至停止</p>
<p>床垫加热根据当前室温与体质建议区间决定;室温不可用时不自动加热。软硬度按健康档案 BMI 给出演示起点,可手动调整。</p>
<p>空调根据当前室温与体质建议区间决定制热或制冷;室温不可用时不自动开启,区间内保持当前运行状态。</p>
</div>
</section>
+2 -1
View File
@@ -6,7 +6,8 @@ export default defineConfig(({ mode }) => {
return {
plugins: [vue()],
server: {
port: 5173,
port: 5176,
strictPort: true,
proxy: {
'/api': {
target: env.VITE_API_BASE_URL || 'http://localhost:5005',