feat: add typed data and views with scoped device power
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
# 数据、设备与视图对象
|
||||
|
||||
本次提供可运行的对象基础和第一种电脑电源实现。六个正式名称为:**数据类型、数据实例、设备类型、设备实例、视图类型、视图实例**。
|
||||
|
||||
| 对象 | 含义 | 当前实现 |
|
||||
| --- | --- | --- |
|
||||
| 数据类型 | 可复用的数据结构、参数约束与运行信号契约 | `data_types`,内置 `computer-power`、`generic`,家庭自定义类型 |
|
||||
| 数据实例 | 某台设备自己的参数值与运行状态 | `dataInstance`,稳定编号与所属设备编号相同 |
|
||||
| 设备类型 | FB,组合关联的数据类型和功能实现 | `device_types`,`dataTypeId` 与已注册执行驱动 `fbType` |
|
||||
| 设备实例 | 某个家庭内的一台实际设备 | 既有 `devices`,保存 `typeId` 和参数 `properties` |
|
||||
| 视图类型 | 只依赖数据类型的呈现规则 | `view_types`;内置 `properties`、`power` 和自定义参数卡片 |
|
||||
| 视图实例 | 绑定数据实例的具名呈现对象 | `device_views`,独立编号、标题和修订号,同一数据实例可有多个 |
|
||||
|
||||
视图类型只依赖数据类型,与设备和设备类型完全独立。视图实例绑定 `dataInstanceId`。当前实现只接入设备提供的数据实例,尚未开放独立外部数据提供者;视图接口本身不依赖设备类型。绑定兼容性仅比较数据类型编号,不比较设备类型、执行驱动或设备的默认视图。
|
||||
|
||||
FB 就是设备类型。`computer.power.v1`、`manual.v1` 是设备类型所选择的**执行驱动**,不会再形成一个与设备类型并列的 FB 对象层。此版本不提供任意脚本、在线编程或任意布局代码。
|
||||
|
||||
## 数据结构与参数
|
||||
|
||||
数据类型公开结构:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "<16 位小写十六进制>",
|
||||
"name": "温度设备参数",
|
||||
"familyId": "<家庭编号>",
|
||||
"fields": [{"key":"TargetValue","label":"目标温度","type":"number","unit":"℃","default":20,"min":0,"max":100}],
|
||||
"signals": [],
|
||||
"builtin": false,
|
||||
"revision": 1
|
||||
}
|
||||
```
|
||||
|
||||
`fields` 只定义用户可编辑的实例参数。最多 24 项,标识匹配 `[A-Za-z][A-Za-z0-9_]{0,39}`;允许 PLC 风格大小写,但重名检查忽略大小写。参数标识、显示标签、单位分别最多 40、80、20 字符。类型名和视图标题最多 80 字符。
|
||||
|
||||
参数支持 `text`、`number`、`boolean`。文本最多 500 字符;布尔值必须为 JSON 布尔值;数字必须有限,拒绝字符串、布尔值、NaN、无穷和范围外值,不会静默截断工程数值。数字才允许 `min/max`。默认值缺省时分别是空文本、0、false,因此下限大于 0 的数值参数必须显式提供有效默认值。文本沿用平台文本校验,不接受控制字符。
|
||||
|
||||
内置 `computer-power` 的 `fields` 为空,`signals` 定义不可由用户改写的运行契约:
|
||||
|
||||
| 信号 | 数据类型 | 访问 |
|
||||
| --- | --- | --- |
|
||||
| RUN | 可空布尔 | 读取实测运行状态;未知不等于停止 |
|
||||
| OP | 枚举 0/1/2 | 经独立电源命令 API 写入,分别为空闲/开机/关机 |
|
||||
| BUSY | 布尔 | 读取操作处理中状态 |
|
||||
| RESULT | 文本 | 读取最近操作结果 |
|
||||
|
||||
RUN、OP、BUSY、RESULT,以及身份、运行时控制和凭据相关名称被保留,不能伪装成自定义参数。运行信号不写入 `properties`。`computer.power.v1` 仅兼容 `computer-power`;`manual.v1` 使用通用或家庭自定义数据类型。自定义电脑设备类型不会自动配置执行驱动、连接设备或取得电源权限,仍需独立服务器适配器配置和明确授权。
|
||||
|
||||
## 数据实例与修订
|
||||
|
||||
`DeviceTypes.instance(item)` 返回公开的类型信息和数据实例:
|
||||
|
||||
```json
|
||||
{
|
||||
"typeId":"<设备类型编号>",
|
||||
"fbType":"manual.v1",
|
||||
"viewTemplate":"properties",
|
||||
"typeName":"温度设备",
|
||||
"properties":{"TargetValue":20},
|
||||
"dataInstance":{
|
||||
"id":"<设备编号>",
|
||||
"deviceId":"<设备编号>",
|
||||
"dataTypeId":"<数据类型编号>",
|
||||
"values":{"TargetValue":20}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
每台设备只有一个稳定的数据实例身份。更改设备名、设备类型或视图不会复制它。此模块投影参数值;电脑运行信号由电源适配器按权限补入同一 `values`,保持电源模块为唯一运行状态来源。没有第二份运行状态数据库。
|
||||
|
||||
数据类型更新会先校验所有依赖设备实例。删除已用参数、缩小范围等操作如导致既有值失效,会返回 409;先调整实例值,或创建新的数据类型并显式重新绑定。兼容更新增加数据类型修订号,同时增加所有依赖设备类型修订号,避免旧绑定表单覆盖新结构。新增字段可使用已验证的默认值。设备类型改变数据类型时也检查已有实例的兼容性。
|
||||
|
||||
普通设备档案编辑通过 `preserve(data,old,user)` 保留类型和有效实例参数。显式绑定默认值会替换旧参数。旧记录没有类型时使用 `generic`;丢失或跨家庭的类型引用在公开显示时退回通用类型和空参数,编辑时须显式重新绑定。
|
||||
|
||||
## 接口契约
|
||||
|
||||
所有接口使用既有网页登录身份与当前家庭范围。内置定义只读。管理操作仅限当前家庭管理员;普通成员可以读取本家庭类型定义,视图和设备仍受区域权限限制。
|
||||
|
||||
| 接口 | 请求或响应 |
|
||||
| --- | --- |
|
||||
| `GET /api/data-types` | `{types,canManage}` |
|
||||
| `POST /api/data-types` | 扁平 `{action:"save",id?,name,fields,revision?}`;返回数据类型列表 |
|
||||
| `GET /api/device-types` | `{types,blocks,canManage}`;`blocks` 为兼容的执行驱动目录,类型含 `dataTypeId/dataTypeRevision` 和派生 `fields` |
|
||||
| `POST /api/device-types` 保存 | 扁平 `{action:"save",id?,name,dataTypeId,dataTypeRevision?,fbType,revision?}`;返回类型列表 |
|
||||
| `POST /api/device-types` 绑定 | `{action:"bind",deviceId,typeId,properties,typeRevision?,dataTypeRevision?}`;返回 `{device}` |
|
||||
| `GET /api/view-types` | `{types,canManage}`;视图类型结构 `{id,name,familyId,dataTypeId,renderer,builtin,revision}` |
|
||||
| `POST /api/view-types` | `{action:"save",id?,name,dataTypeId,dataTypeRevision?,renderer:"properties",revision?}`;返回视图类型列表 |
|
||||
| `GET /api/device-data?id=...` | `{instance:{id,dataTypeId,values,...}}`;按数据实例编号读取,执行家庭及区域授权检查 |
|
||||
| `GET /api/device-views?dataInstanceId=...` | `{items,canManage}`;省略数据实例过滤时返回当前可读取的视图 |
|
||||
| `POST /api/device-views` 保存 | `{action:"save",id?,dataInstanceId,viewTypeId,title,revision?}`;返回 `{view,items,canManage}` |
|
||||
| `POST /api/device-views` 删除 | `{action:"delete",id,revision}`;返回该设备的 `{ok:true,items,canManage}` |
|
||||
|
||||
新建修订号省略或为 0,保存后为 1。编辑和删除必须提供精确的当前修订号,冲突返回 409。类型绑定的修订字段提供额外的结构一致性检查。兼容旧客户端的设备类型 `fields` 请求会转为真实的数据类型,不建立第二份独立参数结构;新客户端应使用独立数据类型接口。
|
||||
|
||||
设备类型响应中的 `viewTemplate` 仅为旧客户端保留的派生显示提示,不参与视图注册或绑定。新客户端不提交该字段。视图组件通过数据实例读取实际值;同一数据实例的多个视图共享页面数据更新,不分别启动轮询。当前保存的视图只读,电脑控制操作由独立授权的电源面板执行。
|
||||
|
||||
跨家庭转移设备时,在同一数据库事务中删除原家庭对应的视图绑定,释放原家庭的视图名额。视图属于家庭的展示配置,不随设备迁移;新家庭可自行建立视图,其他设备和家庭的视图不受影响。
|
||||
|
||||
视图实例结构为 `{id,familyId,dataInstanceId,viewTypeId,title,revision}`。兼容输出 `deviceId` / `templateId` 指向相同编号;同时提交别名时必须一致。`viewTypeId` 指向视图类型,其 `dataTypeId` 必须匹配数据实例的数据类型。内置 `properties` 消费 `generic`,内置 `power` 消费 `computer-power`;自定义视图类型可消费任意可见数据类型,但只能使用安全的 `properties` 渲染器。电源渲染器仅供内置类型,不提供 HTML 或脚本。每个家庭最多 100 个视图实例。删除视图不删除设备、不改变数据实例、不授予控制权限。设备转移后旧家庭的视图无法读取;数据实例改绑为不同数据类型后,类型不匹配的旧视图不再展示。仅更换设备类型而保持数据类型不变,不影响视图。修改视图类型的数据类型引用时,也会校验所有已有视图实例,禁止使它们失配的变更。
|
||||
|
||||
## 集成和验证
|
||||
|
||||
`DeviceTypes(app).initialize()` 在 `HOUSEHOLDS.initialize()` 后调用,创建 `data_types`、`device_types`、`view_types`、`device_views` 四张 `id/body` 表。使用既有 SQLite 和可重入锁。库存保存调用 `preserve`;库存展示合入 `instance`;路由分别调用上表方法。此模块不修改设备名称、原有 `deviceType` 文本、网络配置、联系人或现有权限。
|
||||
|
||||
运行 `py -m unittest -v test_device_types`。测试复用真实内存 SQLite 和家庭角色,覆盖数据类型复用、默认值、数值范围、大小写命名、保留信号、凭据名称、结构修订、绑定/重新绑定、跨家庭拒绝、稳定数据实例、独立视图与区域读取;不连接真实设备,不执行电源操作。
|
||||
@@ -0,0 +1,42 @@
|
||||
# P15 managed asset implementation plan
|
||||
|
||||
Goal: existing household/device catalog gains a managed laptop with RUN/OP and phone tabs 位置 / 家庭 / 设备 / 沟通 / 我的. No generic remote shell.
|
||||
|
||||
Architecture: existing `devices` JSON objects hold the asset and metadata. New `device_power.py` holds runtime state, commands and explicit phone grants. A least-privilege Windows service polls HTTPS, accepts only signed shutdown commands, persists consumed IDs before execution and never listens on a network port. Server calls a fixed, forced-command SSH bridge on MT2500 for WOL. No credentials in catalog/UI.
|
||||
|
||||
User specification: delegated task from 日常操作, 2026-10-25. User approved existing smart-home integration and autonomous implementation. Retain existing pairing and consent; no automatic grants from a location-sharing token. P15 is the active development host, so real shutdown is deferred until work has ended.
|
||||
|
||||
## Interfaces (binding for all components)
|
||||
|
||||
### Phone API
|
||||
|
||||
POST `/api/phone/home` with existing phone pairing Bearer token. Actions:
|
||||
- `catalog`: response `{households:[{id,name,kind}],devices:[{id,source,name,deviceType,familyId,familyName,siteName,power:null|PowerState}],activeId:pairedFamilyId}`. Only explicitly granted devices; paired household name remains visible. Empty device list directs user to administrator; no implied control permission.
|
||||
- `command`: `{action,deviceId,op:1|2,requestId:32 lowercase hex,confirm:true}`; response `{power:PowerState}`. Shutdown requires explicit UI confirmation. UUID without hyphens creates requestId.
|
||||
- `status`: `{action,deviceId}` returns `{power:PowerState}`.
|
||||
|
||||
PowerState = `{run:0|1|null,op:0|1|2,state:'online'|'offline'|'unknown',checkedAt:unixSeconds,canStart:boolean,canShutdown:boolean,managed:boolean,last:{id,op,status,result,at}|null}`.
|
||||
`run=0` means confirmed unreachable through an available relay, not proof of physical shutdown. Unknown disables both actions. Command buttons follow `canStart/canShutdown`; status also validates server-side. OP always resets on terminal outcome/restart. RUN is sampled, never inferred from an OP request.
|
||||
|
||||
### Web API
|
||||
|
||||
GET `/api/device-power?id=...` authenticated in current household returns `{power:PowerState,grants:[{personId,view,control}],candidates:[{personId,name}],canManage:boolean}`. Only admins/managers get grants/candidates; ordinary authorized site readers see state only.
|
||||
POST `/api/device-power` current household, `{action:'command',deviceId,op,requestId,confirm:true}` or `{action:'grants',deviceId,grants:[{personId,view:true,control:boolean}]}`. Commands only manager or explicit per-person grant. Grant save only current household manager, admin may select active paired people across households; family managers only own-family members. Existing paired token alone grants no device access. Grants follow stable person identity but require valid current member pairing and expiry on every request.
|
||||
|
||||
### Windows agent protocol
|
||||
|
||||
POST `/api/device-power/agent` HTTPS `https://home.ucvl.cn`, <=16KiB.
|
||||
Envelope `{payload:base64(UTF8 JSON),signature:hex HMAC-SHA256(secretBytes,payload ASCII)}`. Config secret is base64 random32 bytes. Payload `{deviceId,bootId:32hex,nonce:32hex,at:unixSeconds,ready:boolean,ack:null|{id,status:'scheduled'|'failed'|'blocked',result:string}}`. At within60sec. Server nonce cache rejects duplicates. Poll every10sec. BootId fresh each process start.
|
||||
Response same envelope, payload `{nonce:<request nonce>,at:unixSeconds,command:null|{id:32hex,op:2,bootId,expires:unixSeconds}}`. Verify HMAC in constant time, matching nonce/bootId, timestamp window60sec and command expiry before action. No arbitrary command/path/args accepted. Server delivers only once per command; no reissue after timeout/restart. Agent persists consumed ID before shutdown. Acknowledge 'scheduled' before calling graceful shutdown (no forced application termination). Failed ACK prevents shutdown. Agent retains seen IDs bounded, never replays on restart. Agent service can run `--check`/`--self-test` without shutdown; installation must be explicit. `ready=false` while maintenance/installation safety lock exists. LocalService or dedicated service identity granted only shutdown privilege; no admin shell. Do not change RDP/Tailscale.
|
||||
|
||||
## Tasks and ownership
|
||||
|
||||
- [x] Backend (root): failing tests for RUN unknown/stale/online/offline, OP success/failure/timeouts/restart, duplicate requests, boot changes, replay/HMAC, household and phone grants. Implement module, routes, worker, metadata preservation. Existing tables reused. Bridge script only fixed status/wake operations.
|
||||
- [x] Android: update native layout/controller to five pages, old behavior keyed constants; new PhoneHomePanel calls API above. Bootstrap native look, household selection -> matching devices, explicit shutdown confirmation, no stale callbacks across pair/tab changes. Add isolated native fixture tests/preview modes; no real device calls in tests.
|
||||
- [x] Web: `DevicePowerPanel.vue` + pure model .mjs tests, integrate existing DeviceCollection and device details. Show only name/location/state/buttons/time/result for managed computer card. API authorization errors explicit, no cached permission fallback. Grant editor uses candidates from API. No credential fields.
|
||||
- [x] Windows: dedicated agent under `windows-power/`, .NET Framework compilation supported, self-tests for signatures/nonces/boot/expiry/duplicate journal/only OP2, install/uninstall docs/scripts; no machine mutations until root reviews.
|
||||
- [x] Integrate/review: all tests, signed APKs, preview 320dp and135% font, existing location/voice regression. Resolve test fixture old three-tab assumptions.
|
||||
- [ ] Production: inspect existing records first, online DB backup, idempotently create 优创青岛办 and P15, relay topology is parallel under172.16.1.1, not under MT2500 LAN. P15 LAN172.16.1.44/24 gateway172.16.1.1, TS100.82.249.65, MACs8C:3B:4A:17:BC:C4/9C:2D:CD:03:D9:24. MT2500 WAN172.16.1.163 TS100.66.203.38. Grant only verified requested owner identity, otherwise leave explicit admin grant UI. Restricted SSH key and pinned host key server-side. Agent installation on P15 with maintenance lock; dry-run validates chain without shutdown during work.
|
||||
- [ ] Release: V0.1.56/code12, existing signing/backup/deploy workflow, metadata/hash/download checks. State exactly what was physically tested. Real shutdown deferred because active host.
|
||||
|
||||
Review focus: stale state must be unknown; revoked or moved-device grants fail closed; timeout before delivery cannot execute later; service restart cannot replay; new permissions must not attach to everyone holding a location token. No formal production objects hardcoded into fixture data.
|
||||
Reference in New Issue
Block a user