@camstack/core 0.1.13 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js +220 -0
- package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.js.map +1 -0
- package/dist/builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs +9 -0
- package/dist/builtins/addon-pages-aggregator/index.js +222 -0
- package/dist/builtins/addon-pages-aggregator/index.js.map +1 -0
- package/dist/builtins/addon-pages-aggregator/index.mjs +9 -0
- package/dist/builtins/addon-pages-aggregator/index.mjs.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js +200 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.js.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs +9 -0
- package/dist/builtins/addon-widgets-aggregator/addon-widgets-aggregator.addon.mjs.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/index.js +202 -0
- package/dist/builtins/addon-widgets-aggregator/index.js.map +1 -0
- package/dist/builtins/addon-widgets-aggregator/index.mjs +9 -0
- package/dist/builtins/addon-widgets-aggregator/index.mjs.map +1 -0
- package/dist/builtins/alerts/alerts.addon.js +443 -0
- package/dist/builtins/alerts/alerts.addon.js.map +1 -0
- package/dist/builtins/alerts/alerts.addon.mjs +9 -0
- package/dist/builtins/alerts/alerts.addon.mjs.map +1 -0
- package/dist/builtins/alerts/index.js +443 -0
- package/dist/builtins/alerts/index.js.map +1 -0
- package/dist/builtins/alerts/index.mjs +8 -0
- package/dist/builtins/alerts/index.mjs.map +1 -0
- package/dist/builtins/console-logging/index.js +242 -0
- package/dist/builtins/console-logging/index.js.map +1 -0
- package/dist/builtins/console-logging/index.mjs +11 -0
- package/dist/builtins/console-logging/index.mjs.map +1 -0
- package/dist/builtins/device-manager/device-manager.addon.js +2155 -0
- package/dist/builtins/device-manager/device-manager.addon.js.map +1 -0
- package/dist/builtins/device-manager/device-manager.addon.mjs +9 -0
- package/dist/builtins/device-manager/device-manager.addon.mjs.map +1 -0
- package/dist/builtins/device-manager/index.js +2157 -0
- package/dist/builtins/device-manager/index.js.map +1 -0
- package/dist/builtins/device-manager/index.mjs +10 -0
- package/dist/builtins/device-manager/index.mjs.map +1 -0
- package/dist/builtins/hub-forwarder/index.js +297 -0
- package/dist/builtins/hub-forwarder/index.js.map +1 -0
- package/dist/builtins/hub-forwarder/index.mjs +11 -0
- package/dist/builtins/hub-forwarder/index.mjs.map +1 -0
- package/dist/builtins/local-auth/index.js +623 -0
- package/dist/builtins/local-auth/index.js.map +1 -0
- package/dist/builtins/local-auth/index.mjs +8 -0
- package/dist/builtins/local-auth/index.mjs.map +1 -0
- package/dist/builtins/local-auth/local-auth.addon.js +623 -0
- package/dist/builtins/local-auth/local-auth.addon.js.map +1 -0
- package/dist/builtins/local-auth/local-auth.addon.mjs +9 -0
- package/dist/builtins/local-auth/local-auth.addon.mjs.map +1 -0
- package/dist/builtins/local-backup/index.js +53 -68
- package/dist/builtins/local-backup/index.js.map +1 -1
- package/dist/builtins/local-backup/index.mjs +1 -1
- package/dist/builtins/native-metrics/native-metrics.addon.js +898 -0
- package/dist/builtins/native-metrics/native-metrics.addon.js.map +1 -0
- package/dist/builtins/native-metrics/native-metrics.addon.mjs +7 -0
- package/dist/builtins/native-metrics/native-metrics.addon.mjs.map +1 -0
- package/dist/builtins/snapshot/index.js +504 -0
- package/dist/builtins/snapshot/index.js.map +1 -0
- package/dist/builtins/snapshot/index.mjs +477 -0
- package/dist/builtins/snapshot/index.mjs.map +1 -0
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js +16 -166
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.js.map +1 -1
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.mjs +1 -1
- package/dist/builtins/sqlite-storage/index.js +554 -621
- package/dist/builtins/sqlite-storage/index.js.map +1 -1
- package/dist/builtins/sqlite-storage/index.mjs +9 -11
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js +368 -130
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.js.map +1 -1
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.mjs +1 -1
- package/dist/builtins/system-config/index.js +189 -0
- package/dist/builtins/system-config/index.js.map +1 -0
- package/dist/builtins/system-config/index.mjs +10 -0
- package/dist/builtins/system-config/index.mjs.map +1 -0
- package/dist/builtins/system-config/system-config.addon.js +187 -0
- package/dist/builtins/system-config/system-config.addon.js.map +1 -0
- package/dist/builtins/system-config/system-config.addon.mjs +9 -0
- package/dist/builtins/system-config/system-config.addon.mjs.map +1 -0
- package/dist/builtins/winston-logging/index.js +185 -65
- package/dist/builtins/winston-logging/index.js.map +1 -1
- package/dist/builtins/winston-logging/index.mjs +2 -1
- package/dist/chunk-2CIYKDRN.mjs +1 -0
- package/dist/chunk-2CIYKDRN.mjs.map +1 -0
- package/dist/chunk-2F76X6NL.mjs +136 -0
- package/dist/chunk-2F76X6NL.mjs.map +1 -0
- package/dist/chunk-2QUFBZ7M.mjs +1 -0
- package/dist/chunk-2QUFBZ7M.mjs.map +1 -0
- package/dist/chunk-3BK2Y7GY.mjs +593 -0
- package/dist/chunk-3BK2Y7GY.mjs.map +1 -0
- package/dist/chunk-4OOHFJHT.mjs +421 -0
- package/dist/chunk-4OOHFJHT.mjs.map +1 -0
- package/dist/chunk-4XHB7IHT.mjs +809 -0
- package/dist/chunk-4XHB7IHT.mjs.map +1 -0
- package/dist/{chunk-2F3XZYRW.mjs → chunk-6M2HSSTQ.mjs} +16 -7
- package/dist/chunk-6M2HSSTQ.mjs.map +1 -0
- package/dist/{chunk-SO4LROOT.mjs → chunk-7FI7SQS7.mjs} +54 -69
- package/dist/chunk-7FI7SQS7.mjs.map +1 -0
- package/dist/chunk-ED57RCQE.mjs +171 -0
- package/dist/chunk-ED57RCQE.mjs.map +1 -0
- package/dist/chunk-FZN56HGQ.mjs +626 -0
- package/dist/chunk-FZN56HGQ.mjs.map +1 -0
- package/dist/chunk-GL4OOB25.mjs +51 -0
- package/dist/chunk-GL4OOB25.mjs.map +1 -0
- package/dist/chunk-KDG2NTDB.mjs +137 -0
- package/dist/chunk-KDG2NTDB.mjs.map +1 -0
- package/dist/chunk-NRBQWBDM.mjs +191 -0
- package/dist/chunk-NRBQWBDM.mjs.map +1 -0
- package/dist/chunk-O4V246GG.mjs +2137 -0
- package/dist/chunk-O4V246GG.mjs.map +1 -0
- package/dist/chunk-QT57H266.mjs +163 -0
- package/dist/chunk-QT57H266.mjs.map +1 -0
- package/dist/chunk-QX4RH25I.mjs +141 -0
- package/dist/chunk-QX4RH25I.mjs.map +1 -0
- package/dist/chunk-TB562PZX.mjs +86 -0
- package/dist/chunk-TB562PZX.mjs.map +1 -0
- package/dist/chunk-TDYPZXK5.mjs +1 -0
- package/dist/chunk-TDYPZXK5.mjs.map +1 -0
- package/dist/chunk-UJI4LN5P.mjs +36 -0
- package/dist/chunk-UJI4LN5P.mjs.map +1 -0
- package/dist/chunk-W6RTHQGP.mjs +1 -0
- package/dist/chunk-W6RTHQGP.mjs.map +1 -0
- package/dist/chunk-ZELBCPDC.mjs +369 -0
- package/dist/chunk-ZELBCPDC.mjs.map +1 -0
- package/dist/index.d.mts +1103 -544
- package/dist/index.d.ts +1103 -544
- package/dist/index.js +7032 -6033
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +568 -2226
- package/dist/index.mjs.map +1 -1
- package/dist/resource-monitor-UZUGPIAU.mjs +9 -0
- package/dist/resource-monitor-UZUGPIAU.mjs.map +1 -0
- package/dist/storage-location-manager-HFNB3PCS.mjs +7 -0
- package/dist/storage-location-manager-HFNB3PCS.mjs.map +1 -0
- package/package.json +123 -2
- package/dist/builtins/local-backup/index.d.mts +0 -42
- package/dist/builtins/local-backup/index.d.ts +0 -42
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.mts +0 -2
- package/dist/builtins/sqlite-storage/filesystem-storage.addon.d.ts +0 -2
- package/dist/builtins/sqlite-storage/index.d.mts +0 -4
- package/dist/builtins/sqlite-storage/index.d.ts +0 -4
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.mts +0 -2
- package/dist/builtins/sqlite-storage/sqlite-settings.addon.d.ts +0 -2
- package/dist/builtins/winston-logging/index.d.mts +0 -30
- package/dist/builtins/winston-logging/index.d.ts +0 -30
- package/dist/chunk-2F3XZYRW.mjs.map +0 -1
- package/dist/chunk-LQFPAEQF.mjs +0 -147
- package/dist/chunk-LQFPAEQF.mjs.map +0 -1
- package/dist/chunk-R3DIIBBX.mjs +0 -532
- package/dist/chunk-R3DIIBBX.mjs.map +0 -1
- package/dist/chunk-SMNR44VG.mjs +0 -386
- package/dist/chunk-SMNR44VG.mjs.map +0 -1
- package/dist/chunk-SO4LROOT.mjs.map +0 -1
- package/dist/chunk-SPA4JBKN.mjs +0 -175
- package/dist/chunk-SPA4JBKN.mjs.map +0 -1
- package/dist/dist-3BY63UQ5.mjs +0 -2151
- package/dist/dist-3BY63UQ5.mjs.map +0 -1
- package/dist/filesystem-storage.addon-C42r589X.d.mts +0 -57
- package/dist/filesystem-storage.addon-C42r589X.d.ts +0 -57
- package/dist/sql-schema-CKz78rId.d.mts +0 -97
- package/dist/sql-schema-CKz78rId.d.ts +0 -97
- package/dist/sqlite-settings.addon-KwG-uKMP.d.mts +0 -79
- package/dist/sqlite-settings.addon-KwG-uKMP.d.ts +0 -79
- package/dist/storage-location-manager-KKDQNAKA.mjs +0 -7
- /package/dist/{storage-location-manager-KKDQNAKA.mjs.map → builtins/addon-pages-aggregator/addon-pages-aggregator.addon.mjs.map} +0 -0
|
@@ -0,0 +1,2137 @@
|
|
|
1
|
+
// src/builtins/device-manager/device-manager.addon.ts
|
|
2
|
+
import { randomUUID } from "crypto";
|
|
3
|
+
import {
|
|
4
|
+
EventCategory,
|
|
5
|
+
BaseAddon,
|
|
6
|
+
DeviceType,
|
|
7
|
+
DeviceFeature,
|
|
8
|
+
errMsg
|
|
9
|
+
} from "@camstack/types";
|
|
10
|
+
|
|
11
|
+
// src/builtins/device-manager/device-event-propagator.ts
|
|
12
|
+
var MAX_CHAIN_DEPTH = 16;
|
|
13
|
+
var DeviceEventPropagator = class {
|
|
14
|
+
constructor(opts) {
|
|
15
|
+
this.opts = opts;
|
|
16
|
+
}
|
|
17
|
+
opts;
|
|
18
|
+
unsubscribe = null;
|
|
19
|
+
start() {
|
|
20
|
+
if (this.unsubscribe) return;
|
|
21
|
+
const unsub = this.opts.eventBus.subscribe({}, (ev) => this.handle(ev));
|
|
22
|
+
this.unsubscribe = unsub;
|
|
23
|
+
}
|
|
24
|
+
stop() {
|
|
25
|
+
if (!this.unsubscribe) return;
|
|
26
|
+
this.unsubscribe();
|
|
27
|
+
this.unsubscribe = null;
|
|
28
|
+
}
|
|
29
|
+
/** Exposed for tests — lets them inject events without the full bus. */
|
|
30
|
+
handle(ev) {
|
|
31
|
+
if (ev.via !== void 0) return;
|
|
32
|
+
if (ev.source.type !== "device") return;
|
|
33
|
+
const rawId = ev.source.id;
|
|
34
|
+
const deviceId = typeof rawId === "number" ? rawId : Number(rawId);
|
|
35
|
+
if (!Number.isFinite(deviceId)) return;
|
|
36
|
+
const chain = this.resolveParentChain(deviceId);
|
|
37
|
+
if (chain.length === 0) return;
|
|
38
|
+
const origin = ev.source;
|
|
39
|
+
const via = [origin];
|
|
40
|
+
for (const ancestorId of chain) {
|
|
41
|
+
const reEmission = {
|
|
42
|
+
...ev,
|
|
43
|
+
source: { type: "device", id: ancestorId },
|
|
44
|
+
via: [...via]
|
|
45
|
+
};
|
|
46
|
+
this.opts.eventBus.emit(reEmission);
|
|
47
|
+
via.push({ type: "device", id: ancestorId });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
resolveParentChain(deviceId) {
|
|
51
|
+
const chain = [];
|
|
52
|
+
const seen = /* @__PURE__ */ new Set([deviceId]);
|
|
53
|
+
let current = this.opts.getParentOf(deviceId);
|
|
54
|
+
while (current != null) {
|
|
55
|
+
if (seen.has(current)) {
|
|
56
|
+
this.opts.logger.warn(
|
|
57
|
+
"device-event-propagator: cycle detected in parent chain \u2014 aborting propagation",
|
|
58
|
+
{ tags: { deviceId }, meta: { cycleAt: current, chainSoFar: [...chain] } }
|
|
59
|
+
);
|
|
60
|
+
return chain;
|
|
61
|
+
}
|
|
62
|
+
seen.add(current);
|
|
63
|
+
chain.push(current);
|
|
64
|
+
if (chain.length >= MAX_CHAIN_DEPTH) {
|
|
65
|
+
this.opts.logger.warn(
|
|
66
|
+
"device-event-propagator: chain depth limit hit \u2014 truncating",
|
|
67
|
+
{ tags: { deviceId }, meta: { depth: chain.length, max: MAX_CHAIN_DEPTH } }
|
|
68
|
+
);
|
|
69
|
+
break;
|
|
70
|
+
}
|
|
71
|
+
current = this.opts.getParentOf(current);
|
|
72
|
+
}
|
|
73
|
+
return chain;
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
// src/builtins/device-manager/device-manager.addon.ts
|
|
78
|
+
import { CAP_NAMES_WITH_STATUS } from "@camstack/types";
|
|
79
|
+
import { WELL_KNOWN_TAB_MAP } from "@camstack/types";
|
|
80
|
+
import { deviceManagerCapability, deviceStateCapability } from "@camstack/types";
|
|
81
|
+
function shallowEqual(a, b) {
|
|
82
|
+
const ak = Object.keys(a);
|
|
83
|
+
const bk = Object.keys(b);
|
|
84
|
+
if (ak.length !== bk.length) return false;
|
|
85
|
+
for (const k of ak) {
|
|
86
|
+
if (a[k] !== b[k]) return false;
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
function deviceKey(addonId, stableId) {
|
|
91
|
+
return `${addonId}:${stableId}`;
|
|
92
|
+
}
|
|
93
|
+
function isCameraDevice(device) {
|
|
94
|
+
return "getStreamSources" in device && typeof device.getStreamSources === "function";
|
|
95
|
+
}
|
|
96
|
+
var DEVICE_FEATURE_VALUES = new Set(Object.values(DeviceFeature));
|
|
97
|
+
function persistedFeatures(features) {
|
|
98
|
+
if (!features) return [];
|
|
99
|
+
const out = [];
|
|
100
|
+
for (const f of features) {
|
|
101
|
+
if (DEVICE_FEATURE_VALUES.has(f)) out.push(f);
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
function toDeviceInfo(addonId, device, metadata = null, metaRow = null) {
|
|
106
|
+
const configValues = {};
|
|
107
|
+
for (const entry of device.config.entries()) {
|
|
108
|
+
configValues[entry.key] = entry.value;
|
|
109
|
+
}
|
|
110
|
+
const name = metaRow?.name ?? device.name;
|
|
111
|
+
const location = metaRow?.location !== void 0 ? metaRow.location : device.location;
|
|
112
|
+
const disabled = metaRow?.disabled ?? device.disabled;
|
|
113
|
+
return {
|
|
114
|
+
// Progressive system-wide id — bound on the live `IDevice` at
|
|
115
|
+
// construction time (see `DeviceContext.id` / `BaseDevice.id`). The
|
|
116
|
+
// hub allocates via `allocateDeviceId` BEFORE the device is
|
|
117
|
+
// instantiated, so every live device exposes one.
|
|
118
|
+
id: device.id,
|
|
119
|
+
stableId: device.stableId,
|
|
120
|
+
addonId,
|
|
121
|
+
type: device.type,
|
|
122
|
+
name,
|
|
123
|
+
location,
|
|
124
|
+
disabled,
|
|
125
|
+
parentDeviceId: device.parentDeviceId,
|
|
126
|
+
// `role` is set by the provider on accessory children (synthesized
|
|
127
|
+
// via `getAccessoryChildren()` — Reolink siren/floodlight/PIR,
|
|
128
|
+
// Hikvision supplemental light/siren). Top-level devices and
|
|
129
|
+
// first-class hub-adopted children leave it `undefined`. Surfacing
|
|
130
|
+
// it on `DeviceInfo` lets the UI distinguish accessory rows from
|
|
131
|
+
// adopted-camera rows without re-deriving the heuristic from the
|
|
132
|
+
// provider's `deviceClasses` map.
|
|
133
|
+
role: device.role ?? null,
|
|
134
|
+
online: device.online,
|
|
135
|
+
features: [...device.features],
|
|
136
|
+
isCamera: isCameraDevice(device),
|
|
137
|
+
config: configValues,
|
|
138
|
+
metadata
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function resolveDeviceById(registry, deviceId) {
|
|
142
|
+
const device = registry.getById(deviceId);
|
|
143
|
+
if (!device) return null;
|
|
144
|
+
const addonId = registry.getAddonId(deviceId);
|
|
145
|
+
if (!addonId) return null;
|
|
146
|
+
return { addonId, device };
|
|
147
|
+
}
|
|
148
|
+
function tagContribution(contribution, capName, addonId, kind) {
|
|
149
|
+
const source = kind === "settings" ? "settings" : "live";
|
|
150
|
+
return {
|
|
151
|
+
...contribution.tabs ? { tabs: [...contribution.tabs] } : {},
|
|
152
|
+
sections: contribution.sections.map((section) => ({
|
|
153
|
+
...section,
|
|
154
|
+
fields: section.fields.map((field) => tagField(field, capName, addonId, source, kind))
|
|
155
|
+
}))
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function isFieldRecord(value) {
|
|
159
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
160
|
+
}
|
|
161
|
+
function toWireShape(input) {
|
|
162
|
+
const out = {
|
|
163
|
+
sections: input.sections.map((s) => ({
|
|
164
|
+
id: s.id,
|
|
165
|
+
title: s.title,
|
|
166
|
+
...s.description !== void 0 ? { description: s.description } : {},
|
|
167
|
+
...s.style !== void 0 ? { style: s.style } : {},
|
|
168
|
+
...s.defaultCollapsed !== void 0 ? { defaultCollapsed: s.defaultCollapsed } : {},
|
|
169
|
+
...s.columns !== void 0 ? { columns: s.columns } : {},
|
|
170
|
+
...s.tab !== void 0 ? { tab: s.tab } : {},
|
|
171
|
+
// `location: 'top-tab'` hoists the section into a discovered top-
|
|
172
|
+
// level device tab in DeviceDetail. Forgetting to forward it here
|
|
173
|
+
// strips the marker before the client sees it, so the tab never
|
|
174
|
+
// shows up — see `DeviceDetail.tsx` aggregate-driven tab discovery.
|
|
175
|
+
...s.location !== void 0 ? { location: s.location } : {},
|
|
176
|
+
...s.order !== void 0 ? { order: s.order } : {},
|
|
177
|
+
fields: [...s.fields]
|
|
178
|
+
}))
|
|
179
|
+
};
|
|
180
|
+
if (input.tabs) out.tabs = [...input.tabs];
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
function tagField(field, capName, addonId, source, kind) {
|
|
184
|
+
if (!isFieldRecord(field)) return field;
|
|
185
|
+
const f = field;
|
|
186
|
+
const structuralTypes = /* @__PURE__ */ new Set(["separator", "info", "button"]);
|
|
187
|
+
if (typeof f.type === "string" && structuralTypes.has(f.type)) return field;
|
|
188
|
+
const tagged = { ...f, source };
|
|
189
|
+
if (kind === "live" || f.readonlyField === true) {
|
|
190
|
+
tagged.readonlyField = true;
|
|
191
|
+
} else {
|
|
192
|
+
tagged.writerCapName = capName;
|
|
193
|
+
tagged.writerAddonId = addonId;
|
|
194
|
+
}
|
|
195
|
+
if (f.type === "group") {
|
|
196
|
+
const children = Array.isArray(f.fields) ? f.fields : [];
|
|
197
|
+
if (children.length > 0) {
|
|
198
|
+
tagged.fields = children.map((child) => tagField(child, capName, addonId, source, kind));
|
|
199
|
+
}
|
|
200
|
+
} else if (f.type === "sub-tabs") {
|
|
201
|
+
const rawTabs = Array.isArray(f.tabs) ? f.tabs : [];
|
|
202
|
+
if (rawTabs.length > 0) {
|
|
203
|
+
tagged.tabs = rawTabs.map((tab) => {
|
|
204
|
+
if (!isFieldRecord(tab)) return tab;
|
|
205
|
+
const tabChildren = Array.isArray(tab.fields) ? tab.fields : [];
|
|
206
|
+
return {
|
|
207
|
+
...tab,
|
|
208
|
+
fields: tabChildren.map((child) => tagField(child, capName, addonId, source, kind))
|
|
209
|
+
};
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return tagged;
|
|
214
|
+
}
|
|
215
|
+
function mergeAggregates(parts) {
|
|
216
|
+
const tabDecls = /* @__PURE__ */ new Map();
|
|
217
|
+
const sections = [];
|
|
218
|
+
for (const part of parts) {
|
|
219
|
+
if (part.tabs) {
|
|
220
|
+
for (const t of part.tabs) {
|
|
221
|
+
if (!tabDecls.has(t.id)) tabDecls.set(t.id, t);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const s of part.sections) {
|
|
225
|
+
sections.push(s);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
for (const s of sections) {
|
|
229
|
+
const tabId = s.tab ?? "general";
|
|
230
|
+
if (tabDecls.has(tabId)) continue;
|
|
231
|
+
const known = WELL_KNOWN_TAB_MAP[tabId];
|
|
232
|
+
if (known) {
|
|
233
|
+
tabDecls.set(tabId, { id: known.id, label: known.label, icon: known.icon, order: known.order });
|
|
234
|
+
} else {
|
|
235
|
+
tabDecls.set(tabId, { id: tabId, label: tabId, icon: "wrench", order: 100 });
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
sections.sort((a, b) => {
|
|
239
|
+
const tabA = a.tab ?? "general";
|
|
240
|
+
const tabB = b.tab ?? "general";
|
|
241
|
+
if (tabA !== tabB) {
|
|
242
|
+
const orderA = tabDecls.get(tabA)?.order ?? 100;
|
|
243
|
+
const orderB = tabDecls.get(tabB)?.order ?? 100;
|
|
244
|
+
if (orderA !== orderB) return orderA - orderB;
|
|
245
|
+
return tabA.localeCompare(tabB);
|
|
246
|
+
}
|
|
247
|
+
return (a.order ?? 0) - (b.order ?? 0);
|
|
248
|
+
});
|
|
249
|
+
const sortedTabs = [...tabDecls.values()].sort((a, b) => (a.order ?? 100) - (b.order ?? 100));
|
|
250
|
+
const out = { sections };
|
|
251
|
+
if (sortedTabs.length > 0) out.tabs = sortedTabs;
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
var DeviceManagerAddon = class _DeviceManagerAddon extends BaseAddon {
|
|
255
|
+
constructor() {
|
|
256
|
+
super({});
|
|
257
|
+
}
|
|
258
|
+
/** Shorthand for the kernel-injected capability registry. */
|
|
259
|
+
get capabilityRegistry() {
|
|
260
|
+
return this.ctx.kernel.capabilityRegistry;
|
|
261
|
+
}
|
|
262
|
+
/**
|
|
263
|
+
* Parent-chain event propagator. Started in `onInitialize` once the
|
|
264
|
+
* hub's `deviceRegistry` is available; listens to every device-sourced
|
|
265
|
+
* event and re-emits a copy on each ancestor scope with `via[]`
|
|
266
|
+
* populated. Stopped in `onShutdown`.
|
|
267
|
+
*/
|
|
268
|
+
propagator = null;
|
|
269
|
+
/**
|
|
270
|
+
* Hub-side mirror of every device's cap-keyed runtime state.
|
|
271
|
+
* Populated whenever any caller writes via `deviceState.setCapSlice`
|
|
272
|
+
* (the canonical cross-layer write entrypoint) and on first load
|
|
273
|
+
* via `loadRuntimeState`. Cross-process consumers reach the mirror
|
|
274
|
+
* through the `deviceState` cap router; per-cap event subscribers
|
|
275
|
+
* (e.g. `battery.onStatusChanged`) get the same data via
|
|
276
|
+
* cap-specific events still emitted by the owning device.
|
|
277
|
+
*
|
|
278
|
+
* Key: deviceId. Value: per-cap slice map. Empty by default —
|
|
279
|
+
* slices show up as `setCapSlice` calls trickle in.
|
|
280
|
+
*/
|
|
281
|
+
stateMirror = /* @__PURE__ */ new Map();
|
|
282
|
+
/**
|
|
283
|
+
* Per-device disk-write debouncer for runtime-state. `setCapSlice`
|
|
284
|
+
* updates the in-memory mirror synchronously and emits the change
|
|
285
|
+
* event immediately, but the disk write is coalesced — frequent
|
|
286
|
+
* back-to-back writes (motion phase transitions, battery pushes,
|
|
287
|
+
* etc.) collapse to one `writeDeviceRuntimeState` per
|
|
288
|
+
* `RUNTIME_STATE_DEBOUNCE_MS` window. `flushRuntimeStateWrites`
|
|
289
|
+
* awaits any in-flight write + scheduled flush so shutdown is
|
|
290
|
+
* lossless.
|
|
291
|
+
*/
|
|
292
|
+
runtimeStateDebounce = /* @__PURE__ */ new Map();
|
|
293
|
+
static RUNTIME_STATE_DEBOUNCE_MS = 1e3;
|
|
294
|
+
/**
|
|
295
|
+
* Cross-process native-provider cache: deviceId (numeric) → capName → { addonId, nodeId }.
|
|
296
|
+
* Kept in sync with `device.bindings-changed` events emitted by forked
|
|
297
|
+
* workers. Union'd into `getBindings` so hub-side consumers see every
|
|
298
|
+
* native cap regardless of which process owns the IDevice. No persistence
|
|
299
|
+
* — entries re-register when the worker restarts. Purged on
|
|
300
|
+
* `$node.disconnected` to avoid stale routing after a worker crash.
|
|
301
|
+
*/
|
|
302
|
+
remoteNativeCaps = /* @__PURE__ */ new Map();
|
|
303
|
+
/** Wait for a device-provider by addonId, returning null on timeout. */
|
|
304
|
+
async waitDeviceProvider(addonId, timeoutMs = 5e3) {
|
|
305
|
+
const provider = await this.capabilityRegistry?.waitForProvider("device-provider", addonId, timeoutMs);
|
|
306
|
+
return provider ? provider : null;
|
|
307
|
+
}
|
|
308
|
+
/** Require a device-provider by addonId — throws if not found. */
|
|
309
|
+
async requireDeviceProvider(addonId) {
|
|
310
|
+
const dp = await this.waitDeviceProvider(addonId);
|
|
311
|
+
if (!dp) {
|
|
312
|
+
throw new Error(`Device provider "${addonId}" not found or not registered`);
|
|
313
|
+
}
|
|
314
|
+
return dp;
|
|
315
|
+
}
|
|
316
|
+
// ── Binding store (persisted wrapper activation) ───────────────────────────
|
|
317
|
+
//
|
|
318
|
+
// These methods are public so the device-manager capability router can
|
|
319
|
+
// expose them as cap methods. They read/write through
|
|
320
|
+
// ctx.settings.readAddonStore/writeAddonStore — the same persistence channel
|
|
321
|
+
// the rest of the addon uses.
|
|
322
|
+
async readBindingsStore() {
|
|
323
|
+
const raw = await this.ctx.settings.readAddonStore();
|
|
324
|
+
return { deviceBindings: raw.deviceBindings ?? {} };
|
|
325
|
+
}
|
|
326
|
+
async writeBindingsStore(next) {
|
|
327
|
+
await this.ctx.settings.writeAddonStore({ deviceBindings: next.deviceBindings });
|
|
328
|
+
}
|
|
329
|
+
resolveWrapperNodeId(_wrapperAddonId) {
|
|
330
|
+
return "hub";
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Active discovery of native caps registered on a worker node.
|
|
334
|
+
* Called from the `$node.connected` handler to recover from lost
|
|
335
|
+
* `DeviceBindingsChanged` broadcasts after worker restart.
|
|
336
|
+
*
|
|
337
|
+
* Iterates the broker's service registry, picks
|
|
338
|
+
* `<addonId>.native-provider.<capName>` services owned by the
|
|
339
|
+
* connected node, calls each service's `$listDeviceIds` action to
|
|
340
|
+
* fetch the deviceIds the worker has registered that cap on, then
|
|
341
|
+
* writes entries into `remoteNativeCaps`.
|
|
342
|
+
*
|
|
343
|
+
* Best-effort: per-service failures are logged and swallowed so a
|
|
344
|
+
* single bad service doesn't abort the whole rebuild.
|
|
345
|
+
*/
|
|
346
|
+
async discoverWorkerNativeCaps(connectedNodeId, _connectedAddonId) {
|
|
347
|
+
const cluster = this.ctx.kernel.cluster;
|
|
348
|
+
if (!cluster) return;
|
|
349
|
+
const broker = cluster.broker;
|
|
350
|
+
const services = broker.registry?.getServiceList?.({ onlyAvailable: true, withActions: false }) ?? [];
|
|
351
|
+
const NATIVE_INFIX = ".native-provider.";
|
|
352
|
+
const matched = services.filter(
|
|
353
|
+
(s) => s.nodeID === connectedNodeId && s.name.includes(NATIVE_INFIX)
|
|
354
|
+
);
|
|
355
|
+
if (matched.length === 0) return;
|
|
356
|
+
for (const svc of matched) {
|
|
357
|
+
const idx = svc.name.indexOf(NATIVE_INFIX);
|
|
358
|
+
if (idx <= 0) continue;
|
|
359
|
+
const addonId = svc.name.slice(0, idx);
|
|
360
|
+
const capName = svc.name.slice(idx + NATIVE_INFIX.length);
|
|
361
|
+
if (!addonId || !capName) continue;
|
|
362
|
+
try {
|
|
363
|
+
const action = `${svc.name}.$listDeviceIds`;
|
|
364
|
+
const deviceIds = await broker.call?.(action, {}, { nodeID: connectedNodeId });
|
|
365
|
+
if (!deviceIds || deviceIds.length === 0) continue;
|
|
366
|
+
for (const deviceId of deviceIds) {
|
|
367
|
+
if (this.capabilityRegistry?.getNativeAddonId(capName, deviceId)) continue;
|
|
368
|
+
let perDevice = this.remoteNativeCaps.get(deviceId);
|
|
369
|
+
if (!perDevice) {
|
|
370
|
+
perDevice = /* @__PURE__ */ new Map();
|
|
371
|
+
this.remoteNativeCaps.set(deviceId, perDevice);
|
|
372
|
+
}
|
|
373
|
+
perDevice.set(capName, { addonId, nodeId: connectedNodeId });
|
|
374
|
+
}
|
|
375
|
+
this.ctx.logger.debug("worker native-cap discovered", {
|
|
376
|
+
meta: { nodeId: connectedNodeId, addonId, capName, deviceIds }
|
|
377
|
+
});
|
|
378
|
+
} catch (err) {
|
|
379
|
+
this.ctx.logger.debug("worker native-cap $listDeviceIds failed", {
|
|
380
|
+
meta: { service: svc.name, nodeId: connectedNodeId, error: errMsg(err) }
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
this.ctx.logger.info("worker native-cap discovery completed", {
|
|
385
|
+
meta: { nodeId: connectedNodeId, services: matched.length }
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
async getBindings(input) {
|
|
389
|
+
const storeKey = String(input.deviceId);
|
|
390
|
+
const store = await this.readBindingsStore();
|
|
391
|
+
const perDevice = store.deviceBindings[storeKey] ?? {};
|
|
392
|
+
const entries = [];
|
|
393
|
+
const seenCaps = /* @__PURE__ */ new Set();
|
|
394
|
+
for (const [capName, { wrapperAddonId }] of Object.entries(perDevice)) {
|
|
395
|
+
const hubLocalNative = this.capabilityRegistry?.getNativeAddonId(capName, input.deviceId) ?? null;
|
|
396
|
+
const remoteNative = this.remoteNativeCaps.get(input.deviceId)?.get(capName) ?? null;
|
|
397
|
+
const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
|
|
398
|
+
const nativeNodeId = hubLocalNative ? this.ctx.kernel.localNodeId ?? "hub" : remoteNative?.nodeId ?? (this.ctx.kernel.localNodeId ?? "hub");
|
|
399
|
+
if (wrapperAddonId === null && !nativeAddonId) {
|
|
400
|
+
seenCaps.add(capName);
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
entries.push({
|
|
404
|
+
capName,
|
|
405
|
+
kind: wrapperAddonId ? "wrapped" : "native",
|
|
406
|
+
providerAddonId: wrapperAddonId ?? nativeAddonId,
|
|
407
|
+
providerNodeId: wrapperAddonId ? this.resolveWrapperNodeId(wrapperAddonId) : nativeNodeId,
|
|
408
|
+
nativeAddonId
|
|
409
|
+
});
|
|
410
|
+
seenCaps.add(capName);
|
|
411
|
+
}
|
|
412
|
+
const remote = this.remoteNativeCaps.get(input.deviceId);
|
|
413
|
+
if (this.capabilityRegistry) {
|
|
414
|
+
for (const capName of this.capabilityRegistry.getCapsWithDefaultWrapper()) {
|
|
415
|
+
if (seenCaps.has(capName)) continue;
|
|
416
|
+
const defaultWrapperAddonId = this.capabilityRegistry.getDefaultWrapperForCap(capName);
|
|
417
|
+
if (!defaultWrapperAddonId) continue;
|
|
418
|
+
const hubLocalNative = this.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? null;
|
|
419
|
+
const remoteNative = remote?.get(capName) ?? null;
|
|
420
|
+
const nativeAddonId = hubLocalNative ?? remoteNative?.addonId ?? "";
|
|
421
|
+
entries.push({
|
|
422
|
+
capName,
|
|
423
|
+
kind: "wrapped",
|
|
424
|
+
providerAddonId: defaultWrapperAddonId,
|
|
425
|
+
providerNodeId: this.resolveWrapperNodeId(defaultWrapperAddonId),
|
|
426
|
+
nativeAddonId
|
|
427
|
+
});
|
|
428
|
+
seenCaps.add(capName);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
if (this.capabilityRegistry) {
|
|
432
|
+
for (const capName of this.capabilityRegistry.getNativeCapsForDevice(input.deviceId)) {
|
|
433
|
+
if (seenCaps.has(capName)) continue;
|
|
434
|
+
const nativeAddonId = this.capabilityRegistry.getNativeAddonId(capName, input.deviceId) ?? "";
|
|
435
|
+
entries.push({
|
|
436
|
+
capName,
|
|
437
|
+
kind: "native",
|
|
438
|
+
providerAddonId: nativeAddonId,
|
|
439
|
+
providerNodeId: this.ctx.kernel.localNodeId ?? "hub",
|
|
440
|
+
nativeAddonId
|
|
441
|
+
});
|
|
442
|
+
seenCaps.add(capName);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (remote) {
|
|
446
|
+
for (const [capName, info] of remote) {
|
|
447
|
+
if (seenCaps.has(capName)) continue;
|
|
448
|
+
entries.push({
|
|
449
|
+
capName,
|
|
450
|
+
kind: "native",
|
|
451
|
+
providerAddonId: info.addonId,
|
|
452
|
+
providerNodeId: info.nodeId,
|
|
453
|
+
nativeAddonId: info.addonId
|
|
454
|
+
});
|
|
455
|
+
seenCaps.add(capName);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
return { deviceId: input.deviceId, entries };
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Whole-fleet binding dump. Iterates every device known to the
|
|
462
|
+
* deviceRegistry and reuses the per-device `getBindings` resolver
|
|
463
|
+
* for each — same routing rules, single round-trip. Used by
|
|
464
|
+
* `SystemManager.init()` for warm-boot.
|
|
465
|
+
*
|
|
466
|
+
* Bindings change rarely (wrapper toggle, device add/remove) so
|
|
467
|
+
* clients invalidate via the existing
|
|
468
|
+
* `capability.binding-changed` event rather than re-fetching this
|
|
469
|
+
* payload periodically.
|
|
470
|
+
*/
|
|
471
|
+
async getAllBindings() {
|
|
472
|
+
const hubRegistry = this.ctx.kernel?.deviceRegistry;
|
|
473
|
+
if (!hubRegistry) return [];
|
|
474
|
+
const out = [];
|
|
475
|
+
for (const device of hubRegistry.getAll()) {
|
|
476
|
+
out.push(await this.getBindings({ deviceId: device.id }));
|
|
477
|
+
}
|
|
478
|
+
return out;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Resolve a numeric deviceId to a stableId via persisted meta.
|
|
482
|
+
* Used only by the device-identity section of the device-details
|
|
483
|
+
* aggregator (see `buildBaseDeviceSection`) to surface the stableId as
|
|
484
|
+
* a readonly display field. All runtime/registry lookups are keyed by
|
|
485
|
+
* numeric deviceId; this helper is display-only.
|
|
486
|
+
*/
|
|
487
|
+
async lookupPersistedStableId(deviceId) {
|
|
488
|
+
const store = await this.ctx.settings.readAddonStore();
|
|
489
|
+
const meta = store.deviceMeta ?? {};
|
|
490
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
491
|
+
if (m.id === deviceId) {
|
|
492
|
+
const sep = key.indexOf(":");
|
|
493
|
+
if (sep < 0) continue;
|
|
494
|
+
return key.slice(sep + 1);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
return void 0;
|
|
498
|
+
}
|
|
499
|
+
// ── Device-details aggregator ──────────────────────────────────────────────
|
|
500
|
+
//
|
|
501
|
+
// Walks the bindings for `deviceId` (native + wrapped), picks every
|
|
502
|
+
// provider whose cap declares `exposesDeviceSettings: true`, and asks
|
|
503
|
+
// each for its per-device contribution. Contributions are concatenated
|
|
504
|
+
// into a single `ConfigUISchemaWithValues`; editable fields are tagged
|
|
505
|
+
// with `writerCapName` + `writerAddonId` so `updateDeviceField` can
|
|
506
|
+
// route the mutation back to the exact provider that produced them.
|
|
507
|
+
//
|
|
508
|
+
// `kind` selects settings vs live-info. The two aggregators share the
|
|
509
|
+
// enumeration + tagging pipeline; only the method invoked on each
|
|
510
|
+
// contributing provider differs.
|
|
511
|
+
async getDeviceAggregate(deviceId, kind) {
|
|
512
|
+
const registry = this.capabilityRegistry;
|
|
513
|
+
if (!registry) {
|
|
514
|
+
this.ctx.logger.debug("capability registry unavailable \u2014 aggregate empty", { meta: { kind } });
|
|
515
|
+
return null;
|
|
516
|
+
}
|
|
517
|
+
const method = kind === "settings" ? "getDeviceSettingsContribution" : "getDeviceLiveContribution";
|
|
518
|
+
const contributors = [];
|
|
519
|
+
for (const info of registry.listCapabilities()) {
|
|
520
|
+
const def = registry.getDefinition(info.name);
|
|
521
|
+
if (!def?.exposesDeviceSettings) continue;
|
|
522
|
+
const seen = /* @__PURE__ */ new Set();
|
|
523
|
+
const sorted = [...info.providers].sort((a, b) => a.length - b.length);
|
|
524
|
+
for (const addonId of sorted) {
|
|
525
|
+
if (addonId.includes("::native-")) continue;
|
|
526
|
+
const baseId = addonId.includes("@") ? addonId.slice(0, addonId.indexOf("@")) : addonId;
|
|
527
|
+
if (seen.has(baseId)) continue;
|
|
528
|
+
seen.add(baseId);
|
|
529
|
+
contributors.push({ capName: info.name, addonId });
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const results = await Promise.all(contributors.map(async ({ capName, addonId }) => {
|
|
533
|
+
const provider = registry.getProviderByAddon(capName, addonId);
|
|
534
|
+
if (!provider) {
|
|
535
|
+
throw new Error(
|
|
536
|
+
`[device-manager] capability "${capName}" lists provider "${addonId}" but getProviderByAddon returned null \u2014 registry inconsistency`
|
|
537
|
+
);
|
|
538
|
+
}
|
|
539
|
+
try {
|
|
540
|
+
const contribution = await provider[method]({ deviceId });
|
|
541
|
+
if (!contribution) return null;
|
|
542
|
+
return {
|
|
543
|
+
capName,
|
|
544
|
+
addonId,
|
|
545
|
+
contribution: tagContribution(toWireShape(contribution), capName, addonId, kind)
|
|
546
|
+
};
|
|
547
|
+
} catch (err) {
|
|
548
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
549
|
+
this.ctx.logger.warn("contribution method failed", { tags: { deviceId, addonId }, meta: { capName, method, error: msg } });
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
}));
|
|
553
|
+
const base = kind === "settings" ? await this.buildBaseDeviceSection(deviceId) : null;
|
|
554
|
+
const parts = [
|
|
555
|
+
...base ? [tagContribution(base, "device-manager", "device-manager", kind)] : [],
|
|
556
|
+
...results.filter((r) => r !== null).map((r) => r.contribution)
|
|
557
|
+
];
|
|
558
|
+
if (parts.length === 0) return null;
|
|
559
|
+
return mergeAggregates(parts);
|
|
560
|
+
}
|
|
561
|
+
/**
|
|
562
|
+
* Build the device-manager's own contribution to the aggregator — the
|
|
563
|
+
* device identity (id, stableId, addonId, type, online) + the
|
|
564
|
+
* driver-specific config exposed by the device class via
|
|
565
|
+
* `zodEntriesToConfigUI`.
|
|
566
|
+
*
|
|
567
|
+
* Two paths, deliberately symmetric with `getSettingsSchema`:
|
|
568
|
+
*
|
|
569
|
+
* - Hub-local: device's IDevice instance lives in this process'
|
|
570
|
+
* DeviceRegistry, we read config + schema directly by reference.
|
|
571
|
+
* - Cross-process: device lives in a forked worker (RtspCamera on
|
|
572
|
+
* provider-rtsp, ONVIF on provider-onvif, …). We ask the worker's
|
|
573
|
+
* `device-ops.getSettingsSchema` native provider for a wire-
|
|
574
|
+
* serializable ConfigUISchema and merge it in under the same
|
|
575
|
+
* "Driver Config" section, so the UI sees the same shape regardless
|
|
576
|
+
* of where the IDevice physically runs.
|
|
577
|
+
*
|
|
578
|
+
* Returns `null` only when the device genuinely doesn't exist anywhere
|
|
579
|
+
* (no hub-local, no persisted ownership, no device-ops native). The
|
|
580
|
+
* aggregator falls back to contributor sections only in that case.
|
|
581
|
+
*/
|
|
582
|
+
async buildBaseDeviceSection(deviceId) {
|
|
583
|
+
const hubRegistry = this.ctx.kernel?.deviceRegistry;
|
|
584
|
+
const hubLocal = hubRegistry ? resolveDeviceById(hubRegistry, deviceId) : null;
|
|
585
|
+
const stableId = hubLocal?.device.stableId ?? await this.lookupPersistedStableId(deviceId);
|
|
586
|
+
const nativeOwner = this.resolveNativeDeviceOwner(deviceId);
|
|
587
|
+
const addonId = hubLocal?.addonId ?? nativeOwner?.addonId ?? null;
|
|
588
|
+
if (!hubLocal && !nativeOwner) return null;
|
|
589
|
+
const identityFields = [
|
|
590
|
+
{
|
|
591
|
+
type: "text",
|
|
592
|
+
key: "_deviceId",
|
|
593
|
+
label: "Device ID",
|
|
594
|
+
readonlyField: true,
|
|
595
|
+
value: String(deviceId)
|
|
596
|
+
},
|
|
597
|
+
{
|
|
598
|
+
type: "text",
|
|
599
|
+
key: "_stableId",
|
|
600
|
+
label: "Stable ID",
|
|
601
|
+
readonlyField: true,
|
|
602
|
+
value: stableId ?? ""
|
|
603
|
+
},
|
|
604
|
+
{
|
|
605
|
+
type: "text",
|
|
606
|
+
key: "_addonId",
|
|
607
|
+
label: "Driver",
|
|
608
|
+
readonlyField: true,
|
|
609
|
+
value: addonId ?? "unknown"
|
|
610
|
+
},
|
|
611
|
+
...hubLocal ? [
|
|
612
|
+
{
|
|
613
|
+
type: "text",
|
|
614
|
+
key: "_type",
|
|
615
|
+
label: "Type",
|
|
616
|
+
readonlyField: true,
|
|
617
|
+
value: hubLocal.device.type
|
|
618
|
+
},
|
|
619
|
+
{
|
|
620
|
+
type: "text",
|
|
621
|
+
key: "_online",
|
|
622
|
+
label: "Online",
|
|
623
|
+
readonlyField: true,
|
|
624
|
+
value: hubLocal.device.online ? "yes" : "no"
|
|
625
|
+
}
|
|
626
|
+
] : []
|
|
627
|
+
];
|
|
628
|
+
const sections = [
|
|
629
|
+
{
|
|
630
|
+
id: "device-identity",
|
|
631
|
+
title: "Identity",
|
|
632
|
+
tab: "general",
|
|
633
|
+
order: 0,
|
|
634
|
+
fields: identityFields
|
|
635
|
+
}
|
|
636
|
+
];
|
|
637
|
+
const driverSchema = await this.resolveDriverConfigSchema(deviceId, hubLocal);
|
|
638
|
+
if (driverSchema) {
|
|
639
|
+
for (const section of driverSchema.sections) {
|
|
640
|
+
sections.push({
|
|
641
|
+
id: section.id,
|
|
642
|
+
title: section.title,
|
|
643
|
+
tab: section.tab ?? "general",
|
|
644
|
+
order: section.order ?? 1,
|
|
645
|
+
fields: [...section.fields],
|
|
646
|
+
...section.description !== void 0 ? { description: section.description } : {},
|
|
647
|
+
...section.columns !== void 0 ? { columns: section.columns } : {}
|
|
648
|
+
});
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return {
|
|
652
|
+
sections,
|
|
653
|
+
...driverSchema?.tabs ? { tabs: [...driverSchema.tabs] } : {}
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Lookup the native owner for `device-ops` on `deviceId` — the native-cap
|
|
658
|
+
* registry (hub-local and remote) is keyed by numeric id.
|
|
659
|
+
*/
|
|
660
|
+
resolveNativeDeviceOwner(deviceId) {
|
|
661
|
+
const local = this.capabilityRegistry?.getNativeAddonId("device-ops", deviceId) ?? null;
|
|
662
|
+
if (local) return { addonId: local, nodeId: this.ctx.kernel.localNodeId ?? "hub" };
|
|
663
|
+
const remote = this.remoteNativeCaps.get(deviceId)?.get("device-ops") ?? null;
|
|
664
|
+
return remote ? { addonId: remote.addonId, nodeId: remote.nodeId } : null;
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Aggregate `status` across every registered cap for a device.
|
|
668
|
+
*
|
|
669
|
+
* Walks the supplied cap list (or `CAP_NAMES_WITH_STATUS` when
|
|
670
|
+
* omitted), looks up a native provider per cap via the capability
|
|
671
|
+
* registry, calls `provider.getStatus({ deviceId })`, and validates
|
|
672
|
+
* the return against the cap's own `status.schema`. Validation
|
|
673
|
+
* failures log a warning and yield `null` for that cap so the
|
|
674
|
+
* overall aggregate stays usable — a single misbehaving provider
|
|
675
|
+
* must not blank out a device's entire status view.
|
|
676
|
+
*
|
|
677
|
+
* Returned shape is `Record<capName, unknown | null>`; the client-
|
|
678
|
+
* side hook tightens this to `CapStatusTypeMap` via the generated
|
|
679
|
+
* `cap-status-types.ts`.
|
|
680
|
+
*/
|
|
681
|
+
async getDeviceStatusAggregate(input) {
|
|
682
|
+
const capNames = input.caps ?? CAP_NAMES_WITH_STATUS;
|
|
683
|
+
const registry = this.capabilityRegistry;
|
|
684
|
+
const out = {};
|
|
685
|
+
if (!registry) {
|
|
686
|
+
for (const name of capNames) out[name] = null;
|
|
687
|
+
return out;
|
|
688
|
+
}
|
|
689
|
+
await Promise.all(capNames.map(async (capName) => {
|
|
690
|
+
try {
|
|
691
|
+
const def = registry.getDefinition(capName);
|
|
692
|
+
if (!def?.status) {
|
|
693
|
+
out[capName] = null;
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const provider = registry.getNativeProvider(capName, input.deviceId);
|
|
697
|
+
if (!provider || typeof provider.getStatus !== "function") {
|
|
698
|
+
out[capName] = null;
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
const raw = await provider.getStatus({ deviceId: input.deviceId });
|
|
702
|
+
if (raw == null) {
|
|
703
|
+
out[capName] = null;
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
const parsed = def.status.schema.safeParse(raw);
|
|
707
|
+
if (!parsed.success) {
|
|
708
|
+
this.ctx.logger.warn("getDeviceStatusAggregate: provider returned invalid status, dropping", {
|
|
709
|
+
tags: { deviceId: input.deviceId },
|
|
710
|
+
meta: { capName, issues: parsed.error.issues.slice(0, 3) }
|
|
711
|
+
});
|
|
712
|
+
out[capName] = null;
|
|
713
|
+
return;
|
|
714
|
+
}
|
|
715
|
+
out[capName] = parsed.data;
|
|
716
|
+
} catch (err) {
|
|
717
|
+
this.ctx.logger.warn("getDeviceStatusAggregate: provider threw, dropping", {
|
|
718
|
+
tags: { deviceId: input.deviceId },
|
|
719
|
+
meta: { capName, error: errMsg(err) }
|
|
720
|
+
});
|
|
721
|
+
out[capName] = null;
|
|
722
|
+
}
|
|
723
|
+
}));
|
|
724
|
+
return out;
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Return the driver-specific device-settings contribution. Hub-local
|
|
728
|
+
* devices call `getSettingsUISchema()` directly; forked-worker devices
|
|
729
|
+
* go through the `device-ops.getSettingsSchema` cap method on the
|
|
730
|
+
* numeric-id-keyed native registry.
|
|
731
|
+
*/
|
|
732
|
+
async resolveDriverConfigSchema(deviceId, hubLocal) {
|
|
733
|
+
if (hubLocal) {
|
|
734
|
+
const schema = hubLocal.device.getSettingsUISchema();
|
|
735
|
+
return schema.sections.length === 0 ? null : toWireShape(schema);
|
|
736
|
+
}
|
|
737
|
+
const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
|
|
738
|
+
if (!ops) return null;
|
|
739
|
+
try {
|
|
740
|
+
const schema = await ops.getSettingsSchema({ deviceId });
|
|
741
|
+
if (!schema) return null;
|
|
742
|
+
const wire = schema;
|
|
743
|
+
return wire.sections.length === 0 ? null : toWireShape(wire);
|
|
744
|
+
} catch (err) {
|
|
745
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
746
|
+
this.ctx.logger.warn("cross-process getSettingsSchema failed", { tags: { deviceId }, meta: { error: msg } });
|
|
747
|
+
return null;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
async updateDeviceField(input) {
|
|
751
|
+
if (input.writerCapName === "device-manager") {
|
|
752
|
+
const hubRegistry = this.ctx.kernel?.deviceRegistry;
|
|
753
|
+
const found = hubRegistry ? resolveDeviceById(hubRegistry, input.deviceId) : null;
|
|
754
|
+
if (found) {
|
|
755
|
+
await found.device.applySettingsPatch({ [input.key]: input.value });
|
|
756
|
+
return { success: true };
|
|
757
|
+
}
|
|
758
|
+
const ops = this.capabilityRegistry?.getNativeProvider("device-ops", input.deviceId);
|
|
759
|
+
if (!ops) {
|
|
760
|
+
throw new Error(`[device-manager] device "${input.deviceId}" not found (no hub-local entry, no device-ops native provider)`);
|
|
761
|
+
}
|
|
762
|
+
await ops.setConfig({ deviceId: input.deviceId, values: { [input.key]: input.value } });
|
|
763
|
+
return { success: true };
|
|
764
|
+
}
|
|
765
|
+
const registry = this.capabilityRegistry;
|
|
766
|
+
if (!registry) {
|
|
767
|
+
throw new Error("[device-manager] updateDeviceField requires capability registry \u2014 unavailable on this node");
|
|
768
|
+
}
|
|
769
|
+
const def = registry.getDefinition(input.writerCapName);
|
|
770
|
+
if (!def?.exposesDeviceSettings) {
|
|
771
|
+
throw new Error(`[device-manager] cap "${input.writerCapName}" does not expose device settings`);
|
|
772
|
+
}
|
|
773
|
+
const provider = registry.getProviderByAddon(input.writerCapName, input.writerAddonId);
|
|
774
|
+
if (!provider) {
|
|
775
|
+
throw new Error(`[device-manager] provider "${input.writerAddonId}" not registered for cap "${input.writerCapName}"`);
|
|
776
|
+
}
|
|
777
|
+
await provider.applyDeviceSettingsPatch({
|
|
778
|
+
deviceId: input.deviceId,
|
|
779
|
+
patch: { [input.key]: input.value }
|
|
780
|
+
});
|
|
781
|
+
return { success: true };
|
|
782
|
+
}
|
|
783
|
+
/**
|
|
784
|
+
* Batched counterpart of `updateDeviceField`. Groups changes by
|
|
785
|
+
* `(writerCapName, writerAddonId)` so each contributor receives a
|
|
786
|
+
* single `applyDeviceSettingsPatch` with all of its updates merged —
|
|
787
|
+
* avoids N round-trips for simultaneous edits in the same save.
|
|
788
|
+
*
|
|
789
|
+
* Per-provider failures are captured in the `failures[]` output so the
|
|
790
|
+
* admin UI can highlight which sections didn't persist; a failure on
|
|
791
|
+
* one provider does NOT abort the others.
|
|
792
|
+
*/
|
|
793
|
+
async updateDeviceFieldsBatch(input) {
|
|
794
|
+
const groups = /* @__PURE__ */ new Map();
|
|
795
|
+
for (const change of input.changes) {
|
|
796
|
+
const key = `${change.writerCapName}::${change.writerAddonId}`;
|
|
797
|
+
const existing = groups.get(key);
|
|
798
|
+
if (existing) {
|
|
799
|
+
existing.patch[change.key] = change.value;
|
|
800
|
+
} else {
|
|
801
|
+
groups.set(key, {
|
|
802
|
+
writerCapName: change.writerCapName,
|
|
803
|
+
writerAddonId: change.writerAddonId,
|
|
804
|
+
patch: { [change.key]: change.value }
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
const failures = [];
|
|
809
|
+
for (const group of groups.values()) {
|
|
810
|
+
try {
|
|
811
|
+
await this.applyGroupPatch(input.deviceId, group);
|
|
812
|
+
} catch (err) {
|
|
813
|
+
failures.push({
|
|
814
|
+
writerCapName: group.writerCapName,
|
|
815
|
+
writerAddonId: group.writerAddonId,
|
|
816
|
+
error: err instanceof Error ? err.message : String(err)
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return { success: true, failures };
|
|
821
|
+
}
|
|
822
|
+
/** Apply a single grouped patch to the appropriate provider. Mirrors
|
|
823
|
+
* `updateDeviceField` routing (special-case device-manager, else
|
|
824
|
+
* registry lookup). Used by `updateDeviceFieldsBatch`. */
|
|
825
|
+
async applyGroupPatch(deviceId, group) {
|
|
826
|
+
if (group.writerCapName === "device-manager") {
|
|
827
|
+
const hubRegistry = this.ctx.kernel?.deviceRegistry;
|
|
828
|
+
const found = hubRegistry ? resolveDeviceById(hubRegistry, deviceId) : null;
|
|
829
|
+
if (found) {
|
|
830
|
+
await found.device.applySettingsPatch(group.patch);
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
|
|
834
|
+
if (!ops) {
|
|
835
|
+
throw new Error(`[device-manager] device "${deviceId}" not found (no hub-local entry, no device-ops native provider)`);
|
|
836
|
+
}
|
|
837
|
+
await ops.setConfig({ deviceId, values: group.patch });
|
|
838
|
+
return;
|
|
839
|
+
}
|
|
840
|
+
const registry = this.capabilityRegistry;
|
|
841
|
+
if (!registry) throw new Error("[device-manager] capability registry unavailable");
|
|
842
|
+
const def = registry.getDefinition(group.writerCapName);
|
|
843
|
+
if (!def?.exposesDeviceSettings) {
|
|
844
|
+
throw new Error(`[device-manager] cap "${group.writerCapName}" does not expose device settings`);
|
|
845
|
+
}
|
|
846
|
+
const provider = registry.getProviderByAddon(group.writerCapName, group.writerAddonId);
|
|
847
|
+
if (!provider) {
|
|
848
|
+
throw new Error(`[device-manager] provider "${group.writerAddonId}" not registered for cap "${group.writerCapName}"`);
|
|
849
|
+
}
|
|
850
|
+
await provider.applyDeviceSettingsPatch({ deviceId, patch: group.patch });
|
|
851
|
+
}
|
|
852
|
+
async listWrappersForCap(input) {
|
|
853
|
+
return [...this.capabilityRegistry?.getWrappersForCap(input.capName) ?? []];
|
|
854
|
+
}
|
|
855
|
+
async listBindableCapsForDeviceType(input) {
|
|
856
|
+
const registry = this.capabilityRegistry;
|
|
857
|
+
if (!registry) return [];
|
|
858
|
+
const capNames = registry.listDeviceScopedCapsForType(input.deviceType);
|
|
859
|
+
return capNames.map((capName) => ({
|
|
860
|
+
capName,
|
|
861
|
+
wrappers: [...registry.getWrappersForCap(capName)]
|
|
862
|
+
}));
|
|
863
|
+
}
|
|
864
|
+
async setWrapperActive(input) {
|
|
865
|
+
const storeKey = String(input.deviceId);
|
|
866
|
+
const store = await this.readBindingsStore();
|
|
867
|
+
const perDevice = { ...store.deviceBindings[storeKey] ?? {} };
|
|
868
|
+
if (input.active) {
|
|
869
|
+
perDevice[input.capName] = { wrapperAddonId: input.wrapperAddonId };
|
|
870
|
+
} else {
|
|
871
|
+
perDevice[input.capName] = { wrapperAddonId: null };
|
|
872
|
+
}
|
|
873
|
+
const nextDeviceBindings = Object.keys(perDevice).length > 0 ? { ...store.deviceBindings, [storeKey]: perDevice } : (() => {
|
|
874
|
+
const { [storeKey]: _drop, ...rest } = store.deviceBindings;
|
|
875
|
+
return rest;
|
|
876
|
+
})();
|
|
877
|
+
await this.writeBindingsStore({ deviceBindings: nextDeviceBindings });
|
|
878
|
+
this.ctx.eventBus.emit({
|
|
879
|
+
id: randomUUID(),
|
|
880
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
881
|
+
source: { type: "addon", id: this.ctx.id },
|
|
882
|
+
category: EventCategory.DeviceBindingsChanged,
|
|
883
|
+
data: {
|
|
884
|
+
deviceId: input.deviceId,
|
|
885
|
+
capName: input.capName,
|
|
886
|
+
reason: input.active ? "wrapper-activated" : "wrapper-deactivated",
|
|
887
|
+
addonId: input.wrapperAddonId,
|
|
888
|
+
nodeId: this.resolveWrapperNodeId(input.wrapperAddonId)
|
|
889
|
+
}
|
|
890
|
+
});
|
|
891
|
+
}
|
|
892
|
+
async onInitialize() {
|
|
893
|
+
const settings = this.ctx.settings;
|
|
894
|
+
if (!settings) {
|
|
895
|
+
this.ctx.logger.warn("ctx.settings not available \u2014 device persistence unavailable");
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
const registry = this.ctx.kernel.deviceRegistry ?? null;
|
|
899
|
+
if (!registry) {
|
|
900
|
+
this.ctx.logger.warn("device-registry not available \u2014 live operations will use persisted data only");
|
|
901
|
+
}
|
|
902
|
+
const localNodeId = this.ctx.kernel.localNodeId ?? "hub";
|
|
903
|
+
this.ctx.eventBus.subscribe(
|
|
904
|
+
{ category: EventCategory.DeviceBindingsChanged },
|
|
905
|
+
(event) => {
|
|
906
|
+
const { deviceId, capName, reason, addonId, nodeId } = event.data;
|
|
907
|
+
if (nodeId === localNodeId) return;
|
|
908
|
+
if (reason === "native-registered") {
|
|
909
|
+
let perDevice = this.remoteNativeCaps.get(deviceId);
|
|
910
|
+
if (!perDevice) {
|
|
911
|
+
perDevice = /* @__PURE__ */ new Map();
|
|
912
|
+
this.remoteNativeCaps.set(deviceId, perDevice);
|
|
913
|
+
}
|
|
914
|
+
perDevice.set(capName, { addonId, nodeId });
|
|
915
|
+
} else if (reason === "native-unregistered") {
|
|
916
|
+
const perDevice = this.remoteNativeCaps.get(deviceId);
|
|
917
|
+
if (!perDevice) return;
|
|
918
|
+
perDevice.delete(capName);
|
|
919
|
+
if (perDevice.size === 0) this.remoteNativeCaps.delete(deviceId);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
);
|
|
923
|
+
const cluster = this.ctx.kernel.cluster;
|
|
924
|
+
if (cluster) {
|
|
925
|
+
cluster.broker.localBus.on("$node.disconnected", (payload) => {
|
|
926
|
+
const gone = payload.node.id;
|
|
927
|
+
const emptyDevices = [];
|
|
928
|
+
for (const [deviceId, perDevice] of this.remoteNativeCaps) {
|
|
929
|
+
const toDelete = [];
|
|
930
|
+
for (const [capName, entry] of perDevice) {
|
|
931
|
+
if (entry.nodeId === gone) toDelete.push(capName);
|
|
932
|
+
}
|
|
933
|
+
for (const capName of toDelete) perDevice.delete(capName);
|
|
934
|
+
if (perDevice.size === 0) emptyDevices.push(deviceId);
|
|
935
|
+
}
|
|
936
|
+
for (const deviceId of emptyDevices) this.remoteNativeCaps.delete(deviceId);
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
const requireDeviceOps = (deviceId) => {
|
|
940
|
+
const ops = this.capabilityRegistry?.getNativeProvider("device-ops", deviceId);
|
|
941
|
+
if (!ops) {
|
|
942
|
+
throw new Error(`[device-manager] device-ops native provider not found for '${deviceId}'`);
|
|
943
|
+
}
|
|
944
|
+
return ops;
|
|
945
|
+
};
|
|
946
|
+
const readStore = async () => {
|
|
947
|
+
return await settings.readAddonStore();
|
|
948
|
+
};
|
|
949
|
+
const readIndex = async () => {
|
|
950
|
+
const store = await readStore();
|
|
951
|
+
return store.deviceIndex ?? {};
|
|
952
|
+
};
|
|
953
|
+
const readMeta = async () => {
|
|
954
|
+
const store = await readStore();
|
|
955
|
+
return store.deviceMeta ?? {};
|
|
956
|
+
};
|
|
957
|
+
const readMetadataMap = async () => {
|
|
958
|
+
const store = await readStore();
|
|
959
|
+
return store.deviceMetadata ?? {};
|
|
960
|
+
};
|
|
961
|
+
let metaWriteChain = Promise.resolve();
|
|
962
|
+
const withMetaWriteLock = async (fn) => {
|
|
963
|
+
const previous = metaWriteChain;
|
|
964
|
+
let release = () => {
|
|
965
|
+
};
|
|
966
|
+
const next = new Promise((resolve) => {
|
|
967
|
+
release = resolve;
|
|
968
|
+
});
|
|
969
|
+
metaWriteChain = next;
|
|
970
|
+
try {
|
|
971
|
+
await previous.catch(() => {
|
|
972
|
+
});
|
|
973
|
+
return await fn();
|
|
974
|
+
} finally {
|
|
975
|
+
release();
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
const resolvePersistedById = async (deviceId) => {
|
|
979
|
+
const meta = await readMeta();
|
|
980
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
981
|
+
if (m.id === deviceId) {
|
|
982
|
+
const sep = key.indexOf(":");
|
|
983
|
+
if (sep < 0) continue;
|
|
984
|
+
return { addonId: key.slice(0, sep), stableId: key.slice(sep + 1), meta: m };
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return null;
|
|
988
|
+
};
|
|
989
|
+
const idToAddonId = /* @__PURE__ */ new Map();
|
|
990
|
+
{
|
|
991
|
+
const meta = await readMeta();
|
|
992
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
993
|
+
const sep = key.indexOf(":");
|
|
994
|
+
if (sep < 0) continue;
|
|
995
|
+
idToAddonId.set(m.id, key.slice(0, sep));
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (cluster) {
|
|
999
|
+
cluster.broker.localBus.on("$node.connected", (payload) => {
|
|
1000
|
+
const connectedNodeId = payload.node.id;
|
|
1001
|
+
const lastSlash = connectedNodeId.lastIndexOf("/");
|
|
1002
|
+
if (lastSlash < 0) return;
|
|
1003
|
+
const connectedAddonId = connectedNodeId.slice(lastSlash + 1);
|
|
1004
|
+
if (connectedAddonId.length === 0) return;
|
|
1005
|
+
for (const [deviceId, ownerAddonId] of idToAddonId) {
|
|
1006
|
+
if (ownerAddonId !== connectedAddonId) continue;
|
|
1007
|
+
if (this.capabilityRegistry?.getNativeAddonId("device-ops", deviceId)) continue;
|
|
1008
|
+
let perDevice = this.remoteNativeCaps.get(deviceId);
|
|
1009
|
+
if (!perDevice) {
|
|
1010
|
+
perDevice = /* @__PURE__ */ new Map();
|
|
1011
|
+
this.remoteNativeCaps.set(deviceId, perDevice);
|
|
1012
|
+
}
|
|
1013
|
+
if (!perDevice.has("device-ops")) {
|
|
1014
|
+
perDevice.set("device-ops", { addonId: connectedAddonId, nodeId: connectedNodeId });
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
setTimeout(() => {
|
|
1018
|
+
this.discoverWorkerNativeCaps(connectedNodeId, connectedAddonId).catch((err) => {
|
|
1019
|
+
this.ctx.logger.warn("worker native-cap discovery failed", {
|
|
1020
|
+
meta: { nodeId: connectedNodeId, addonId: connectedAddonId, error: errMsg(err) }
|
|
1021
|
+
});
|
|
1022
|
+
});
|
|
1023
|
+
}, 500);
|
|
1024
|
+
});
|
|
1025
|
+
}
|
|
1026
|
+
const allocateNextDeviceId = async () => {
|
|
1027
|
+
const store = await readStore();
|
|
1028
|
+
const current = store.nextDeviceId ?? 1;
|
|
1029
|
+
await settings.writeAddonStore({ nextDeviceId: current + 1 });
|
|
1030
|
+
return current;
|
|
1031
|
+
};
|
|
1032
|
+
const provider = {
|
|
1033
|
+
/** Sync ownership lookup backing persistence fallbacks (e.g. remove()
|
|
1034
|
+
* when the owning worker is offline). Ownership is keyed by numeric
|
|
1035
|
+
* deviceId → owning addonId as recorded in the persisted meta. NOT
|
|
1036
|
+
* a native-cap lookup: an addon can own a device without registering
|
|
1037
|
+
* every possible cap natively (e.g. RtspCamera without snapshotUrl
|
|
1038
|
+
* doesn't register the snapshot cap). Use
|
|
1039
|
+
* `resolveNativeCapOwnerSync` for cap-resolution paths.
|
|
1040
|
+
*/
|
|
1041
|
+
resolveDeviceOwnerSync: (deviceId) => {
|
|
1042
|
+
return idToAddonId.get(deviceId) ?? null;
|
|
1043
|
+
},
|
|
1044
|
+
/** Sync lookup for the addon that registered a native provider for
|
|
1045
|
+
* `(capName, deviceId)`. Backs `CapabilityRegistry`'s native fallback
|
|
1046
|
+
* so the hub only synthesizes a cross-process proxy when the cap is
|
|
1047
|
+
* actually published — never on speculative device ownership.
|
|
1048
|
+
*
|
|
1049
|
+
* Consults hub-local registrations first (in-process natives),
|
|
1050
|
+
* then the `remoteNativeCaps` map populated from
|
|
1051
|
+
* `DeviceBindingsChanged` events emitted by forked-worker
|
|
1052
|
+
* `registerNativeCap` calls. Both are generic: any addon that hosts
|
|
1053
|
+
* devices and registers caps via the standard context API shows up
|
|
1054
|
+
* here without per-addon branching.
|
|
1055
|
+
*/
|
|
1056
|
+
resolveNativeCapOwnerSync: (capName, deviceId) => {
|
|
1057
|
+
const localAddonId = this.capabilityRegistry?.getNativeAddonId(capName, deviceId) ?? null;
|
|
1058
|
+
if (localAddonId) {
|
|
1059
|
+
return { addonId: localAddonId, nodeId: this.ctx.kernel.localNodeId ?? "hub" };
|
|
1060
|
+
}
|
|
1061
|
+
const remote = this.remoteNativeCaps.get(deviceId)?.get(capName) ?? null;
|
|
1062
|
+
if (remote) return { addonId: remote.addonId, nodeId: remote.nodeId };
|
|
1063
|
+
return null;
|
|
1064
|
+
},
|
|
1065
|
+
// ── Persistence ────────────────────────────────────────────────────────
|
|
1066
|
+
/** Idempotent numeric-id reservation. Callers invoke this before
|
|
1067
|
+
* constructing the owning `IDevice` so `DeviceContext.id` is bound
|
|
1068
|
+
* at construction time. A repeat call for the same `(addonId,
|
|
1069
|
+
* stableId)` returns the already-persisted id — same physical
|
|
1070
|
+
* device reconnecting after a driver restart keeps its original
|
|
1071
|
+
* number. Fresh pairs burn one slot from the monotonic
|
|
1072
|
+
* `nextDeviceId` counter and seed a meta placeholder so the
|
|
1073
|
+
* `deviceMeta` → `id` invariant holds even before
|
|
1074
|
+
* `registerDevice` completes. */
|
|
1075
|
+
allocateDeviceId: async (input) => {
|
|
1076
|
+
const { addonId, stableId } = input;
|
|
1077
|
+
const key = deviceKey(addonId, stableId);
|
|
1078
|
+
return await withMetaWriteLock(async () => {
|
|
1079
|
+
const meta = await readMeta();
|
|
1080
|
+
const existing = meta[key];
|
|
1081
|
+
if (existing) return { id: existing.id };
|
|
1082
|
+
const id = await allocateNextDeviceId();
|
|
1083
|
+
await settings.writeAddonStore({
|
|
1084
|
+
deviceMeta: {
|
|
1085
|
+
...meta,
|
|
1086
|
+
[key]: {
|
|
1087
|
+
type: "generic",
|
|
1088
|
+
name: stableId,
|
|
1089
|
+
location: null,
|
|
1090
|
+
disabled: false,
|
|
1091
|
+
parentDeviceId: null,
|
|
1092
|
+
id
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
});
|
|
1096
|
+
return { id };
|
|
1097
|
+
});
|
|
1098
|
+
},
|
|
1099
|
+
registerDevice: async (input) => {
|
|
1100
|
+
const { addonId, stableId, id, type, name, parentDeviceId, features, config } = input;
|
|
1101
|
+
const key = deviceKey(addonId, stableId);
|
|
1102
|
+
const featuresArr = Array.isArray(features) ? [...features] : [];
|
|
1103
|
+
const { isFirstRegistration } = await withMetaWriteLock(async () => {
|
|
1104
|
+
const index = await readIndex();
|
|
1105
|
+
const existing = index[addonId] ?? [];
|
|
1106
|
+
const wasInIndex = existing.includes(stableId);
|
|
1107
|
+
if (!wasInIndex) {
|
|
1108
|
+
await settings.writeAddonStore({
|
|
1109
|
+
deviceIndex: { ...index, [addonId]: [...existing, stableId] }
|
|
1110
|
+
});
|
|
1111
|
+
}
|
|
1112
|
+
const meta = await readMeta();
|
|
1113
|
+
const existingMeta = meta[key];
|
|
1114
|
+
const isFirst = !existingMeta || !wasInIndex;
|
|
1115
|
+
await settings.writeAddonStore({
|
|
1116
|
+
deviceMeta: {
|
|
1117
|
+
...meta,
|
|
1118
|
+
[key]: {
|
|
1119
|
+
type,
|
|
1120
|
+
// Prefer the persisted name (set by `setName` pre-construct)
|
|
1121
|
+
// over the construction-time fallback. Only when the meta
|
|
1122
|
+
// row literally still carries `name === stableId` (the
|
|
1123
|
+
// placeholder seeded by `allocateDeviceId`) do we fall
|
|
1124
|
+
// back to the action arg.
|
|
1125
|
+
name: existingMeta && existingMeta.name !== stableId ? existingMeta.name : name,
|
|
1126
|
+
location: existingMeta?.location ?? null,
|
|
1127
|
+
disabled: existingMeta?.disabled ?? false,
|
|
1128
|
+
parentDeviceId,
|
|
1129
|
+
id,
|
|
1130
|
+
features: featuresArr
|
|
1131
|
+
}
|
|
1132
|
+
}
|
|
1133
|
+
});
|
|
1134
|
+
return { isFirstRegistration: isFirst };
|
|
1135
|
+
});
|
|
1136
|
+
if (Object.keys(config).length > 0) {
|
|
1137
|
+
await settings.writeDeviceStore(id, config);
|
|
1138
|
+
}
|
|
1139
|
+
idToAddonId.set(id, addonId);
|
|
1140
|
+
if (isFirstRegistration) {
|
|
1141
|
+
this.ctx.eventBus.emit({
|
|
1142
|
+
id: randomUUID(),
|
|
1143
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1144
|
+
source: { type: "device", id },
|
|
1145
|
+
category: EventCategory.DeviceRegistered,
|
|
1146
|
+
data: {
|
|
1147
|
+
deviceId: id,
|
|
1148
|
+
name: name.length > 0 ? name : stableId,
|
|
1149
|
+
providerId: addonId,
|
|
1150
|
+
parentDeviceId: parentDeviceId ?? null
|
|
1151
|
+
}
|
|
1152
|
+
});
|
|
1153
|
+
} else {
|
|
1154
|
+
this.ctx.eventBus.emit({
|
|
1155
|
+
id: randomUUID(),
|
|
1156
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1157
|
+
source: { type: "device", id },
|
|
1158
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1159
|
+
data: {
|
|
1160
|
+
deviceId: id,
|
|
1161
|
+
name: name.length > 0 ? name : stableId,
|
|
1162
|
+
providerId: addonId,
|
|
1163
|
+
parentDeviceId: parentDeviceId ?? null,
|
|
1164
|
+
features: featuresArr
|
|
1165
|
+
}
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
},
|
|
1169
|
+
removeDevice: async (input) => {
|
|
1170
|
+
const { deviceId } = input;
|
|
1171
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1172
|
+
if (!persisted) {
|
|
1173
|
+
return;
|
|
1174
|
+
}
|
|
1175
|
+
const { addonId, stableId, meta: persistedMeta } = persisted;
|
|
1176
|
+
const key = deviceKey(addonId, stableId);
|
|
1177
|
+
const deviceName = persistedMeta.name;
|
|
1178
|
+
await withMetaWriteLock(async () => {
|
|
1179
|
+
const index = await readIndex();
|
|
1180
|
+
const remaining = (index[addonId] ?? []).filter((sid) => sid !== stableId);
|
|
1181
|
+
const updatedIndex = remaining.length > 0 ? { ...index, [addonId]: remaining } : (() => {
|
|
1182
|
+
const { [addonId]: _removed, ...rest } = index;
|
|
1183
|
+
return rest;
|
|
1184
|
+
})();
|
|
1185
|
+
await settings.writeAddonStore({ deviceIndex: updatedIndex });
|
|
1186
|
+
const meta = await readMeta();
|
|
1187
|
+
const { [key]: _removedMeta, ...restMeta } = meta;
|
|
1188
|
+
await settings.writeAddonStore({ deviceMeta: restMeta });
|
|
1189
|
+
const map = await readMetadataMap();
|
|
1190
|
+
if (key in map) {
|
|
1191
|
+
const { [key]: _removedMetadata, ...restMap } = map;
|
|
1192
|
+
await settings.writeAddonStore({ deviceMetadata: restMap });
|
|
1193
|
+
}
|
|
1194
|
+
});
|
|
1195
|
+
await settings.clearDeviceStore(deviceId);
|
|
1196
|
+
const bindingsStore = await this.readBindingsStore();
|
|
1197
|
+
const bindingKey = String(deviceId);
|
|
1198
|
+
if (bindingsStore.deviceBindings[bindingKey]) {
|
|
1199
|
+
const { [bindingKey]: _removedBindings, ...restBindings } = bindingsStore.deviceBindings;
|
|
1200
|
+
await this.writeBindingsStore({ deviceBindings: restBindings });
|
|
1201
|
+
}
|
|
1202
|
+
this.remoteNativeCaps.delete(deviceId);
|
|
1203
|
+
this.capabilityRegistry?.unregisterAllNativeForDevice(deviceId);
|
|
1204
|
+
idToAddonId.delete(deviceId);
|
|
1205
|
+
this.ctx.logger.info("removed device", { tags: { deviceId, deviceName: deviceName.length > 0 ? deviceName : stableId } });
|
|
1206
|
+
this.ctx.eventBus.emit({
|
|
1207
|
+
id: randomUUID(),
|
|
1208
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1209
|
+
source: { type: "device", id: deviceId },
|
|
1210
|
+
category: EventCategory.DeviceUnregistered,
|
|
1211
|
+
data: {
|
|
1212
|
+
deviceId,
|
|
1213
|
+
providerId: addonId,
|
|
1214
|
+
// Carry parentDeviceId so listeners can filter on "is
|
|
1215
|
+
// this MY child?" without consulting an in-memory map
|
|
1216
|
+
// they had to keep in sync. By the time this event
|
|
1217
|
+
// fires the meta row is already gone — we read it from
|
|
1218
|
+
// the resolved snapshot above.
|
|
1219
|
+
parentDeviceId: persistedMeta.parentDeviceId ?? null
|
|
1220
|
+
}
|
|
1221
|
+
});
|
|
1222
|
+
},
|
|
1223
|
+
persistConfig: async (input) => {
|
|
1224
|
+
const { deviceId, data } = input;
|
|
1225
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1226
|
+
if (!persisted) throw new Error(`[device-manager] persistConfig: unknown device id=${deviceId}`);
|
|
1227
|
+
await settings.writeDeviceStore(deviceId, data);
|
|
1228
|
+
},
|
|
1229
|
+
loadConfig: async (input) => {
|
|
1230
|
+
const { deviceId } = input;
|
|
1231
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1232
|
+
if (!persisted) return {};
|
|
1233
|
+
return settings.readDeviceStore(deviceId);
|
|
1234
|
+
},
|
|
1235
|
+
/**
|
|
1236
|
+
* Load the operator-organisational meta surface for one device
|
|
1237
|
+
* (`name` / `location` / `disabled` / `type` / `parentDeviceId`
|
|
1238
|
+
* / `addonId` + `id` / `stableId`). Used by the kernel proxy's
|
|
1239
|
+
* device-context factory to populate `ctx.deviceMeta` before
|
|
1240
|
+
* the device class constructor runs. Returns `null` when no
|
|
1241
|
+
* persisted row exists for the id.
|
|
1242
|
+
*
|
|
1243
|
+
* Reads default `location` to `null` and `disabled` to `false`
|
|
1244
|
+
* for legacy rows that predate the field — production code
|
|
1245
|
+
* relies on the IDevice type contract that both are present.
|
|
1246
|
+
*/
|
|
1247
|
+
loadMeta: async (input) => {
|
|
1248
|
+
const { deviceId } = input;
|
|
1249
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1250
|
+
if (!persisted) return null;
|
|
1251
|
+
const { addonId, stableId, meta: m } = persisted;
|
|
1252
|
+
const key = deviceKey(addonId, stableId);
|
|
1253
|
+
const map = await readMetadataMap();
|
|
1254
|
+
const metadata = map[key] ?? null;
|
|
1255
|
+
return {
|
|
1256
|
+
id: m.id,
|
|
1257
|
+
stableId,
|
|
1258
|
+
addonId,
|
|
1259
|
+
type: m.type,
|
|
1260
|
+
name: m.name,
|
|
1261
|
+
location: m.location ?? null,
|
|
1262
|
+
disabled: m.disabled ?? false,
|
|
1263
|
+
parentDeviceId: m.parentDeviceId,
|
|
1264
|
+
metadata
|
|
1265
|
+
};
|
|
1266
|
+
},
|
|
1267
|
+
/**
|
|
1268
|
+
* Update the operator-edited display name. Writes the meta
|
|
1269
|
+
* row, emits a `DeviceMetaChanged` event so live consumers
|
|
1270
|
+
* (UI device list, alert center) see the rename without
|
|
1271
|
+
* polling. The live `IDevice.name` mirror is updated by the
|
|
1272
|
+
* kernel proxy on its side (`device-cap-proxy.ts`).
|
|
1273
|
+
*/
|
|
1274
|
+
setName: async (input) => {
|
|
1275
|
+
const { deviceId, name } = input;
|
|
1276
|
+
await withMetaWriteLock(async () => {
|
|
1277
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1278
|
+
if (!persisted) throw new Error(`[device-manager] setName: unknown device id=${deviceId}`);
|
|
1279
|
+
const { addonId, stableId, meta: m } = persisted;
|
|
1280
|
+
const key = deviceKey(addonId, stableId);
|
|
1281
|
+
const allMeta = await readMeta();
|
|
1282
|
+
await settings.writeAddonStore({
|
|
1283
|
+
deviceMeta: { ...allMeta, [key]: { ...m, name } }
|
|
1284
|
+
});
|
|
1285
|
+
});
|
|
1286
|
+
this.ctx.eventBus.emit({
|
|
1287
|
+
id: randomUUID(),
|
|
1288
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1289
|
+
source: { type: "device", id: deviceId },
|
|
1290
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1291
|
+
data: { deviceId, field: "name", value: name }
|
|
1292
|
+
});
|
|
1293
|
+
},
|
|
1294
|
+
/**
|
|
1295
|
+
* Update the operator-organisational location label. `null`
|
|
1296
|
+
* clears it. Mirrors the same persist-then-emit shape as
|
|
1297
|
+
* `setName`; consumers subscribe to `DeviceMetaChanged` and
|
|
1298
|
+
* filter on `field: 'location'`.
|
|
1299
|
+
*/
|
|
1300
|
+
setLocation: async (input) => {
|
|
1301
|
+
const { deviceId, location } = input;
|
|
1302
|
+
await withMetaWriteLock(async () => {
|
|
1303
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1304
|
+
if (!persisted) throw new Error(`[device-manager] setLocation: unknown device id=${deviceId}`);
|
|
1305
|
+
const { addonId, stableId, meta: m } = persisted;
|
|
1306
|
+
const key = deviceKey(addonId, stableId);
|
|
1307
|
+
const allMeta = await readMeta();
|
|
1308
|
+
await settings.writeAddonStore({
|
|
1309
|
+
deviceMeta: { ...allMeta, [key]: { ...m, location } }
|
|
1310
|
+
});
|
|
1311
|
+
});
|
|
1312
|
+
this.ctx.eventBus.emit({
|
|
1313
|
+
id: randomUUID(),
|
|
1314
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1315
|
+
source: { type: "device", id: deviceId },
|
|
1316
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1317
|
+
data: { deviceId, field: "location", value: location }
|
|
1318
|
+
});
|
|
1319
|
+
},
|
|
1320
|
+
/**
|
|
1321
|
+
* Patch the device's hardware-identity metadata blob. Shallow
|
|
1322
|
+
* merge — `null` removes a key, anything else overwrites.
|
|
1323
|
+
* Drivers populate factual fields on first probe; operators
|
|
1324
|
+
* augment via the Device Info tab. Idempotent: a no-op patch
|
|
1325
|
+
* (every key already present with the same value) doesn't emit
|
|
1326
|
+
* the meta-changed event.
|
|
1327
|
+
*/
|
|
1328
|
+
setMetadata: async (input) => {
|
|
1329
|
+
const { deviceId, patch } = input;
|
|
1330
|
+
const result = await withMetaWriteLock(async () => {
|
|
1331
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1332
|
+
if (!persisted) throw new Error(`[device-manager] setMetadata: unknown device id=${deviceId}`);
|
|
1333
|
+
const { addonId, stableId } = persisted;
|
|
1334
|
+
const key = deviceKey(addonId, stableId);
|
|
1335
|
+
const map = await readMetadataMap();
|
|
1336
|
+
const current = map[key] ?? {};
|
|
1337
|
+
const next = { ...current };
|
|
1338
|
+
let changed = false;
|
|
1339
|
+
for (const [k, v] of Object.entries(patch)) {
|
|
1340
|
+
if (v === null) {
|
|
1341
|
+
if (k in next) {
|
|
1342
|
+
delete next[k];
|
|
1343
|
+
changed = true;
|
|
1344
|
+
}
|
|
1345
|
+
} else if (next[k] !== v) {
|
|
1346
|
+
next[k] = v;
|
|
1347
|
+
changed = true;
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
if (!changed) return { changed: false };
|
|
1351
|
+
const hasFields = Object.keys(next).length > 0;
|
|
1352
|
+
const updatedMap = { ...map };
|
|
1353
|
+
if (hasFields) {
|
|
1354
|
+
updatedMap[key] = next;
|
|
1355
|
+
} else {
|
|
1356
|
+
delete updatedMap[key];
|
|
1357
|
+
}
|
|
1358
|
+
await settings.writeAddonStore({ deviceMetadata: updatedMap });
|
|
1359
|
+
return { changed: true, finalMeta: hasFields ? next : null };
|
|
1360
|
+
});
|
|
1361
|
+
if (!result.changed) return;
|
|
1362
|
+
this.ctx.eventBus.emit({
|
|
1363
|
+
id: randomUUID(),
|
|
1364
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1365
|
+
source: { type: "device", id: deviceId },
|
|
1366
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1367
|
+
data: { deviceId, field: "metadata", value: result.finalMeta }
|
|
1368
|
+
});
|
|
1369
|
+
},
|
|
1370
|
+
/**
|
|
1371
|
+
* Soft-disable the device. Persisted on the meta row;
|
|
1372
|
+
* lifecycle gating is the driver's responsibility (BaseDevice
|
|
1373
|
+
* exposes `this.disabled` for the driver to consult at the top
|
|
1374
|
+
* of its lifecycle methods).
|
|
1375
|
+
*/
|
|
1376
|
+
setDisabled: async (input) => {
|
|
1377
|
+
const { deviceId, disabled } = input;
|
|
1378
|
+
await withMetaWriteLock(async () => {
|
|
1379
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1380
|
+
if (!persisted) throw new Error(`[device-manager] setDisabled: unknown device id=${deviceId}`);
|
|
1381
|
+
const { addonId, stableId, meta: m } = persisted;
|
|
1382
|
+
const key = deviceKey(addonId, stableId);
|
|
1383
|
+
const allMeta = await readMeta();
|
|
1384
|
+
await settings.writeAddonStore({
|
|
1385
|
+
deviceMeta: { ...allMeta, [key]: { ...m, disabled } }
|
|
1386
|
+
});
|
|
1387
|
+
});
|
|
1388
|
+
this.ctx.eventBus.emit({
|
|
1389
|
+
id: randomUUID(),
|
|
1390
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1391
|
+
source: { type: "device", id: deviceId },
|
|
1392
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1393
|
+
data: { deviceId, field: "disabled", value: disabled }
|
|
1394
|
+
});
|
|
1395
|
+
},
|
|
1396
|
+
loadRuntimeState: async (input) => {
|
|
1397
|
+
const { deviceId } = input;
|
|
1398
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1399
|
+
if (!persisted) return {};
|
|
1400
|
+
const data = await settings.readDeviceRuntimeState(deviceId);
|
|
1401
|
+
this.seedMirror(deviceId, data);
|
|
1402
|
+
return data;
|
|
1403
|
+
},
|
|
1404
|
+
/**
|
|
1405
|
+
* Union of (1) operator-curated location registry and (2) labels
|
|
1406
|
+
* currently in use on persisted devices. Case-insensitive
|
|
1407
|
+
* dedupe (preserves the first-seen casing). Sorted
|
|
1408
|
+
* case-insensitively for stable UI. Drives the Device Info
|
|
1409
|
+
* location autocomplete.
|
|
1410
|
+
*/
|
|
1411
|
+
listLocations: async () => {
|
|
1412
|
+
const store = await settings.readAddonStore();
|
|
1413
|
+
const meta = store.deviceMeta ?? {};
|
|
1414
|
+
const registry2 = store.locations ?? [];
|
|
1415
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1416
|
+
const consider = (raw) => {
|
|
1417
|
+
if (typeof raw !== "string") return;
|
|
1418
|
+
const trimmed = raw.trim();
|
|
1419
|
+
if (trimmed.length === 0) return;
|
|
1420
|
+
const key = trimmed.toLowerCase();
|
|
1421
|
+
if (!seen.has(key)) seen.set(key, trimmed);
|
|
1422
|
+
};
|
|
1423
|
+
for (const label of registry2) consider(label);
|
|
1424
|
+
for (const m of Object.values(meta)) consider(m.location);
|
|
1425
|
+
return [...seen.values()].sort(
|
|
1426
|
+
(a, b) => a.localeCompare(b, void 0, { sensitivity: "base" })
|
|
1427
|
+
);
|
|
1428
|
+
},
|
|
1429
|
+
/**
|
|
1430
|
+
* Add a label to the curated location registry. Idempotent:
|
|
1431
|
+
* existing entries (case-insensitive match) are silently kept.
|
|
1432
|
+
* Empty / whitespace-only inputs throw — operators must supply a
|
|
1433
|
+
* meaningful label.
|
|
1434
|
+
*/
|
|
1435
|
+
addLocation: async (input) => {
|
|
1436
|
+
const trimmed = input.name.trim();
|
|
1437
|
+
if (trimmed.length === 0) {
|
|
1438
|
+
throw new Error("[device-manager] addLocation: name must be non-empty");
|
|
1439
|
+
}
|
|
1440
|
+
const store = await settings.readAddonStore();
|
|
1441
|
+
const current = store.locations ?? [];
|
|
1442
|
+
if (current.some((l) => l.toLowerCase() === trimmed.toLowerCase())) {
|
|
1443
|
+
return;
|
|
1444
|
+
}
|
|
1445
|
+
await settings.writeAddonStore({ locations: [...current, trimmed] });
|
|
1446
|
+
},
|
|
1447
|
+
/**
|
|
1448
|
+
* Remove a label from the curated registry. Match is
|
|
1449
|
+
* case-insensitive. Devices that still reference this label keep
|
|
1450
|
+
* their `meta.location` value (the registry is a suggestion
|
|
1451
|
+
* list, not a foreign key) — pass `cascade: true` to also clear
|
|
1452
|
+
* `setLocation` on every device that referenced this exact
|
|
1453
|
+
* label. Cascade only matches case-insensitively + trimmed, same
|
|
1454
|
+
* as the registry equality check.
|
|
1455
|
+
*/
|
|
1456
|
+
removeLocation: async (input) => {
|
|
1457
|
+
const trimmed = input.name.trim();
|
|
1458
|
+
if (trimmed.length === 0) return;
|
|
1459
|
+
const store = await settings.readAddonStore();
|
|
1460
|
+
const current = store.locations ?? [];
|
|
1461
|
+
const remaining = current.filter((l) => l.toLowerCase() !== trimmed.toLowerCase());
|
|
1462
|
+
if (remaining.length !== current.length) {
|
|
1463
|
+
await settings.writeAddonStore({ locations: remaining });
|
|
1464
|
+
}
|
|
1465
|
+
if (input.cascade !== true) return;
|
|
1466
|
+
const meta = store.deviceMeta ?? {};
|
|
1467
|
+
const updates = { ...meta };
|
|
1468
|
+
const cleared = [];
|
|
1469
|
+
for (const [key, m] of Object.entries(meta)) {
|
|
1470
|
+
if (typeof m.location !== "string") continue;
|
|
1471
|
+
if (m.location.trim().toLowerCase() !== trimmed.toLowerCase()) continue;
|
|
1472
|
+
updates[key] = { ...m, location: null };
|
|
1473
|
+
cleared.push(m.id);
|
|
1474
|
+
}
|
|
1475
|
+
if (cleared.length === 0) return;
|
|
1476
|
+
await settings.writeAddonStore({ deviceMeta: updates });
|
|
1477
|
+
for (const deviceId of cleared) {
|
|
1478
|
+
this.ctx.eventBus.emit({
|
|
1479
|
+
id: randomUUID(),
|
|
1480
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
1481
|
+
source: { type: "device", id: deviceId },
|
|
1482
|
+
category: EventCategory.DeviceMetaChanged,
|
|
1483
|
+
data: { deviceId, field: "location", value: null }
|
|
1484
|
+
});
|
|
1485
|
+
}
|
|
1486
|
+
},
|
|
1487
|
+
listPersistedByAddon: async (input) => {
|
|
1488
|
+
const { addonId } = input;
|
|
1489
|
+
const [index, meta] = await Promise.all([readIndex(), readMeta()]);
|
|
1490
|
+
const stableIds = index[addonId] ?? [];
|
|
1491
|
+
return stableIds.map((stableId) => {
|
|
1492
|
+
const m = meta[deviceKey(addonId, stableId)];
|
|
1493
|
+
return {
|
|
1494
|
+
id: m.id,
|
|
1495
|
+
stableId,
|
|
1496
|
+
type: m.type,
|
|
1497
|
+
name: m.name,
|
|
1498
|
+
location: m.location ?? null,
|
|
1499
|
+
disabled: m.disabled ?? false,
|
|
1500
|
+
parentDeviceId: m.parentDeviceId
|
|
1501
|
+
};
|
|
1502
|
+
});
|
|
1503
|
+
},
|
|
1504
|
+
// ── Live queries — serve from live registry when available ────────────
|
|
1505
|
+
listAll: async (input) => {
|
|
1506
|
+
const { addonId } = input;
|
|
1507
|
+
const results = [];
|
|
1508
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1509
|
+
const meta = await readMeta();
|
|
1510
|
+
const metadataMap = await readMetadataMap();
|
|
1511
|
+
if (registry) {
|
|
1512
|
+
const liveEntries = addonId ? registry.getAllForAddon(addonId).map((device) => ({ addonId, device })) : registry.getAllWithAddonId();
|
|
1513
|
+
for (const { addonId: aid, device } of liveEntries) {
|
|
1514
|
+
const key = deviceKey(aid, device.stableId);
|
|
1515
|
+
const metadata = metadataMap[key] ?? null;
|
|
1516
|
+
const metaRow = meta[key] ?? null;
|
|
1517
|
+
results.push(toDeviceInfo(aid, device, metadata, metaRow));
|
|
1518
|
+
seen.add(key);
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
const index = await readIndex();
|
|
1522
|
+
const targetAddons = addonId ? [addonId] : Object.keys(index);
|
|
1523
|
+
for (const aid of targetAddons) {
|
|
1524
|
+
for (const stableId of index[aid] ?? []) {
|
|
1525
|
+
const key = deviceKey(aid, stableId);
|
|
1526
|
+
if (seen.has(key)) continue;
|
|
1527
|
+
const m = meta[key];
|
|
1528
|
+
const persistedType = m.type;
|
|
1529
|
+
const persistedConfig = await settings.readDeviceStore(m.id);
|
|
1530
|
+
const metadata = metadataMap[key] ?? null;
|
|
1531
|
+
results.push({
|
|
1532
|
+
id: m.id,
|
|
1533
|
+
stableId,
|
|
1534
|
+
addonId: aid,
|
|
1535
|
+
type: persistedType,
|
|
1536
|
+
name: m?.name ?? stableId,
|
|
1537
|
+
location: m?.location ?? null,
|
|
1538
|
+
disabled: m?.disabled ?? false,
|
|
1539
|
+
parentDeviceId: m?.parentDeviceId ?? null,
|
|
1540
|
+
// role is not persisted to disk — only set on the live
|
|
1541
|
+
// IDevice (`BaseDevice.role`) by accessory subclasses. The
|
|
1542
|
+
// forked-worker fallback path can't read it, so emit null;
|
|
1543
|
+
// accessories typically run in the same process as their
|
|
1544
|
+
// parent provider, so the live path covers them in practice.
|
|
1545
|
+
role: null,
|
|
1546
|
+
// registry===null was the legacy "offline view" signal; keep it
|
|
1547
|
+
// for that case so existing callers see online=false. When a
|
|
1548
|
+
// registry is present and the device lives elsewhere (forked
|
|
1549
|
+
// worker), default to online=true — persisted state implies it
|
|
1550
|
+
// was successfully registered by its owning process.
|
|
1551
|
+
online: registry !== null,
|
|
1552
|
+
features: persistedFeatures(m?.features),
|
|
1553
|
+
// Live IDevice isn't reachable from the hub, so infer
|
|
1554
|
+
// isCamera from the persisted DeviceType rather than the
|
|
1555
|
+
// method-presence check `toDeviceInfo` uses. Without this
|
|
1556
|
+
// forked-worker cameras looked non-camera to the stream-broker
|
|
1557
|
+
// and never got their RTSP restream wired up.
|
|
1558
|
+
isCamera: persistedType === DeviceType.Camera,
|
|
1559
|
+
config: persistedConfig ?? {},
|
|
1560
|
+
metadata
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
return results;
|
|
1565
|
+
},
|
|
1566
|
+
getDevice: async (input) => {
|
|
1567
|
+
const { deviceId } = input;
|
|
1568
|
+
if (registry) {
|
|
1569
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1570
|
+
if (found) {
|
|
1571
|
+
const key2 = deviceKey(found.addonId, found.device.stableId);
|
|
1572
|
+
const [map2, metaMap] = await Promise.all([readMetadataMap(), readMeta()]);
|
|
1573
|
+
const metadata2 = map2[key2] ?? null;
|
|
1574
|
+
const metaRow = metaMap[key2] ?? null;
|
|
1575
|
+
return toDeviceInfo(found.addonId, found.device, metadata2, metaRow);
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1579
|
+
if (!persisted) return null;
|
|
1580
|
+
const { addonId: aid, stableId, meta: m } = persisted;
|
|
1581
|
+
const persistedConfig = await settings.readDeviceStore(m.id);
|
|
1582
|
+
const key = deviceKey(aid, stableId);
|
|
1583
|
+
const map = await readMetadataMap();
|
|
1584
|
+
const metadata = map[key] ?? null;
|
|
1585
|
+
return {
|
|
1586
|
+
id: deviceId,
|
|
1587
|
+
stableId,
|
|
1588
|
+
addonId: aid,
|
|
1589
|
+
type: m.type,
|
|
1590
|
+
name: m.name,
|
|
1591
|
+
location: m.location ?? null,
|
|
1592
|
+
disabled: m.disabled ?? false,
|
|
1593
|
+
parentDeviceId: m.parentDeviceId,
|
|
1594
|
+
role: null,
|
|
1595
|
+
online: true,
|
|
1596
|
+
features: persistedFeatures(m.features),
|
|
1597
|
+
isCamera: false,
|
|
1598
|
+
config: persistedConfig ?? {},
|
|
1599
|
+
metadata
|
|
1600
|
+
};
|
|
1601
|
+
},
|
|
1602
|
+
getChildren: async (input) => {
|
|
1603
|
+
const { parentDeviceId } = input;
|
|
1604
|
+
let ownerAddonId = null;
|
|
1605
|
+
if (registry) {
|
|
1606
|
+
const liveParent = registry.getById(parentDeviceId);
|
|
1607
|
+
if (liveParent) {
|
|
1608
|
+
ownerAddonId = registry.getAddonId(parentDeviceId);
|
|
1609
|
+
}
|
|
1610
|
+
}
|
|
1611
|
+
if (!ownerAddonId) {
|
|
1612
|
+
const persisted = await resolvePersistedById(parentDeviceId);
|
|
1613
|
+
if (!persisted) return [];
|
|
1614
|
+
ownerAddonId = persisted.addonId;
|
|
1615
|
+
}
|
|
1616
|
+
const results = [];
|
|
1617
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1618
|
+
const [index, meta, metadataMap] = await Promise.all([readIndex(), readMeta(), readMetadataMap()]);
|
|
1619
|
+
if (registry) {
|
|
1620
|
+
const liveChildren = registry.getChildren(parentDeviceId);
|
|
1621
|
+
for (const device of liveChildren) {
|
|
1622
|
+
const key = deviceKey(ownerAddonId, device.stableId);
|
|
1623
|
+
const metadata = metadataMap[key] ?? null;
|
|
1624
|
+
const metaRow = meta[key] ?? null;
|
|
1625
|
+
results.push(toDeviceInfo(ownerAddonId, device, metadata, metaRow));
|
|
1626
|
+
seen.add(key);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
const stableIds = index[ownerAddonId] ?? [];
|
|
1630
|
+
const persistedChildren = stableIds.filter(
|
|
1631
|
+
(sid) => meta[deviceKey(ownerAddonId, sid)]?.parentDeviceId === parentDeviceId
|
|
1632
|
+
);
|
|
1633
|
+
for (const childStableId of persistedChildren) {
|
|
1634
|
+
const key = deviceKey(ownerAddonId, childStableId);
|
|
1635
|
+
if (seen.has(key)) continue;
|
|
1636
|
+
const m = meta[key];
|
|
1637
|
+
const persistedConfig = await settings.readDeviceStore(m.id);
|
|
1638
|
+
const metadata = metadataMap[key] ?? null;
|
|
1639
|
+
results.push({
|
|
1640
|
+
id: m.id,
|
|
1641
|
+
stableId: childStableId,
|
|
1642
|
+
addonId: ownerAddonId,
|
|
1643
|
+
type: m.type,
|
|
1644
|
+
name: m.name,
|
|
1645
|
+
location: m.location ?? null,
|
|
1646
|
+
disabled: m.disabled ?? false,
|
|
1647
|
+
parentDeviceId,
|
|
1648
|
+
role: null,
|
|
1649
|
+
online: registry !== null,
|
|
1650
|
+
features: persistedFeatures(m.features),
|
|
1651
|
+
isCamera: false,
|
|
1652
|
+
config: persistedConfig ?? {},
|
|
1653
|
+
metadata
|
|
1654
|
+
});
|
|
1655
|
+
}
|
|
1656
|
+
return results;
|
|
1657
|
+
},
|
|
1658
|
+
// ── Live runtime methods ──────────────────────────────────────────────
|
|
1659
|
+
getStreamSources: async (input) => {
|
|
1660
|
+
const { deviceId } = input;
|
|
1661
|
+
if (registry) {
|
|
1662
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1663
|
+
if (found) {
|
|
1664
|
+
if (!isCameraDevice(found.device)) return [];
|
|
1665
|
+
const sources2 = await found.device.getStreamSources();
|
|
1666
|
+
return sources2.map((s) => ({
|
|
1667
|
+
id: s.id,
|
|
1668
|
+
label: s.label,
|
|
1669
|
+
protocol: s.protocol,
|
|
1670
|
+
url: s.url,
|
|
1671
|
+
resolution: s.resolution,
|
|
1672
|
+
fps: s.fps,
|
|
1673
|
+
bitrate: s.bitrate,
|
|
1674
|
+
codec: s.codec,
|
|
1675
|
+
profileHint: s.profileHint
|
|
1676
|
+
}));
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1680
|
+
if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
|
|
1681
|
+
const ops = requireDeviceOps(deviceId);
|
|
1682
|
+
const sources = await ops.getStreamSources({ deviceId });
|
|
1683
|
+
return sources.map((s) => ({ ...s }));
|
|
1684
|
+
},
|
|
1685
|
+
getConfigSchema: async (input) => {
|
|
1686
|
+
const { deviceId } = input;
|
|
1687
|
+
if (registry) {
|
|
1688
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1689
|
+
if (found) {
|
|
1690
|
+
return found.device.config.entries().map((entry) => ({
|
|
1691
|
+
key: entry.key,
|
|
1692
|
+
value: entry.value,
|
|
1693
|
+
...entry.description !== void 0 ? { description: entry.description } : {}
|
|
1694
|
+
}));
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1698
|
+
if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
|
|
1699
|
+
const ops = requireDeviceOps(deviceId);
|
|
1700
|
+
const entries = await ops.getConfigEntries({ deviceId });
|
|
1701
|
+
return entries.map((e) => ({ ...e }));
|
|
1702
|
+
},
|
|
1703
|
+
getSettingsSchema: async (input) => {
|
|
1704
|
+
const { deviceId } = input;
|
|
1705
|
+
if (registry) {
|
|
1706
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1707
|
+
if (found) {
|
|
1708
|
+
return found.device.getSettingsUISchema();
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1712
|
+
if (!persisted) return null;
|
|
1713
|
+
const ops = requireDeviceOps(deviceId);
|
|
1714
|
+
const schema = await ops.getSettingsSchema({ deviceId });
|
|
1715
|
+
return schema ?? null;
|
|
1716
|
+
},
|
|
1717
|
+
updateConfig: async (input) => {
|
|
1718
|
+
const { deviceId } = input;
|
|
1719
|
+
if (registry) {
|
|
1720
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1721
|
+
if (found) {
|
|
1722
|
+
await found.device.config.setAll(input.values);
|
|
1723
|
+
return { success: true };
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1727
|
+
if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
|
|
1728
|
+
const ops = requireDeviceOps(deviceId);
|
|
1729
|
+
await ops.setConfig({ deviceId, values: input.values });
|
|
1730
|
+
return { success: true };
|
|
1731
|
+
},
|
|
1732
|
+
// `enable` / `disable` write to deviceMeta.disabled (the canonical
|
|
1733
|
+
// soft-disable flag that drivers consult via `BaseDevice.disabled`
|
|
1734
|
+
// at lifecycle entrypoints, and that `toDeviceInfo` projects onto
|
|
1735
|
+
// the wire by reading the LATEST persisted meta row — see the
|
|
1736
|
+
// `metaRow` argument plumbed through `listAll` / `getDevice` /
|
|
1737
|
+
// `getChildren`).
|
|
1738
|
+
//
|
|
1739
|
+
// Earlier these wrappers wrote `enabled: true/false` into the
|
|
1740
|
+
// device CONFIG blob — wrong store entirely. The config write
|
|
1741
|
+
// succeeded but the flag the rest of the system reads
|
|
1742
|
+
// (deviceMeta) stayed unchanged, so the UI's enable/disable
|
|
1743
|
+
// toggle appeared to do nothing. Delegating to `setDisabled`
|
|
1744
|
+
// routes through the correct withMetaWriteLock path and emits
|
|
1745
|
+
// the `DeviceMetaChanged` event for live invalidation.
|
|
1746
|
+
//
|
|
1747
|
+
// NB: `BaseDevice.disabled` is `readonly` and bound at
|
|
1748
|
+
// construction (base-device.ts:142). Drivers that gate behaviour
|
|
1749
|
+
// off `this.disabled` only see the value the device was
|
|
1750
|
+
// instantiated with — flipping disabled at runtime updates the
|
|
1751
|
+
// wire response immediately, but lifecycle gating inside the
|
|
1752
|
+
// driver only takes effect on the next instantiation. That's
|
|
1753
|
+
// acceptable today: the operator-facing semantic is "hide /
|
|
1754
|
+
// mark inactive in the UI"; the heavyweight teardown semantic
|
|
1755
|
+
// is `remove`.
|
|
1756
|
+
enable: async (input) => {
|
|
1757
|
+
await provider.setDisabled({ deviceId: input.deviceId, disabled: false });
|
|
1758
|
+
return { success: true };
|
|
1759
|
+
},
|
|
1760
|
+
disable: async (input) => {
|
|
1761
|
+
await provider.setDisabled({ deviceId: input.deviceId, disabled: true });
|
|
1762
|
+
return { success: true };
|
|
1763
|
+
},
|
|
1764
|
+
remove: async (input) => {
|
|
1765
|
+
const { deviceId } = input;
|
|
1766
|
+
if (registry) {
|
|
1767
|
+
const live = resolveDeviceById(registry, deviceId);
|
|
1768
|
+
if (live) {
|
|
1769
|
+
const deviceName = live.device.name;
|
|
1770
|
+
await live.device.removeDevice();
|
|
1771
|
+
registry.remove(deviceId);
|
|
1772
|
+
await provider.removeDevice({ deviceId });
|
|
1773
|
+
this.ctx.logger.info("removed hub-local device", { tags: { deviceId, deviceName } });
|
|
1774
|
+
return { success: true };
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1778
|
+
if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
|
|
1779
|
+
const { meta: persistedMeta } = persisted;
|
|
1780
|
+
try {
|
|
1781
|
+
const ops = requireDeviceOps(deviceId);
|
|
1782
|
+
await ops.removeDevice({ deviceId });
|
|
1783
|
+
} catch (err) {
|
|
1784
|
+
this.ctx.logger.warn("remove via device-ops failed \u2014 clearing persistence anyway", { tags: { deviceId, deviceName: persistedMeta.name }, meta: { error: errMsg(err) } });
|
|
1785
|
+
}
|
|
1786
|
+
await provider.removeDevice({ deviceId });
|
|
1787
|
+
return { success: true };
|
|
1788
|
+
},
|
|
1789
|
+
getStreamProfileMap: async (input) => {
|
|
1790
|
+
if (!registry) return {};
|
|
1791
|
+
const found = resolveDeviceById(registry, input.deviceId);
|
|
1792
|
+
if (!found) return {};
|
|
1793
|
+
const storedMap = found.device.config.entries().find((e) => e.key === "_profileMap")?.value;
|
|
1794
|
+
if (storedMap !== void 0 && typeof storedMap === "object" && storedMap !== null) {
|
|
1795
|
+
return storedMap;
|
|
1796
|
+
}
|
|
1797
|
+
if (!isCameraDevice(found.device)) return {};
|
|
1798
|
+
const sources = await found.device.getStreamSources();
|
|
1799
|
+
const profileMap = {};
|
|
1800
|
+
for (const s of sources) {
|
|
1801
|
+
if (s.profileHint && s.id) {
|
|
1802
|
+
profileMap[s.profileHint] = s.id;
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
return profileMap;
|
|
1806
|
+
},
|
|
1807
|
+
setStreamProfileMap: async (input) => {
|
|
1808
|
+
const { deviceId } = input;
|
|
1809
|
+
if (registry) {
|
|
1810
|
+
const found = resolveDeviceById(registry, deviceId);
|
|
1811
|
+
if (found) {
|
|
1812
|
+
await found.device.config.setAll({ _profileMap: input.profileMap });
|
|
1813
|
+
return { success: true };
|
|
1814
|
+
}
|
|
1815
|
+
}
|
|
1816
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1817
|
+
if (!persisted) throw new Error(`[device-manager] Device with id ${deviceId} not found`);
|
|
1818
|
+
const ops = requireDeviceOps(deviceId);
|
|
1819
|
+
await ops.setConfig({ deviceId, values: { _profileMap: input.profileMap } });
|
|
1820
|
+
return { success: true };
|
|
1821
|
+
},
|
|
1822
|
+
probeStreams: async (input) => {
|
|
1823
|
+
const streamProbe = this.ctx.kernel.streamProbe;
|
|
1824
|
+
if (!streamProbe) return [];
|
|
1825
|
+
const sources = await provider.getStreamSources({ deviceId: input.deviceId });
|
|
1826
|
+
const results = [];
|
|
1827
|
+
for (const s of sources) {
|
|
1828
|
+
if (!s.url) continue;
|
|
1829
|
+
try {
|
|
1830
|
+
const metadata = await streamProbe.probe(s.url, { force: true });
|
|
1831
|
+
results.push({
|
|
1832
|
+
streamId: s.id,
|
|
1833
|
+
width: metadata.width,
|
|
1834
|
+
height: metadata.height,
|
|
1835
|
+
codec: metadata.codec,
|
|
1836
|
+
fps: metadata.fps,
|
|
1837
|
+
bitrateKbps: metadata.bitrateKbps
|
|
1838
|
+
});
|
|
1839
|
+
} catch (err) {
|
|
1840
|
+
this.ctx.logger.debug("streamProbe.probe failed \u2014 returning placeholder", {
|
|
1841
|
+
meta: {
|
|
1842
|
+
deviceId: input.deviceId,
|
|
1843
|
+
streamId: s.id,
|
|
1844
|
+
error: err instanceof Error ? err.message : String(err)
|
|
1845
|
+
}
|
|
1846
|
+
});
|
|
1847
|
+
results.push({ streamId: s.id });
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
return results;
|
|
1851
|
+
},
|
|
1852
|
+
// ── Device-provider operations (routed via CapabilityRegistry) ───────
|
|
1853
|
+
discoverDevices: async (input) => {
|
|
1854
|
+
const dp = await this.requireDeviceProvider(input.addonId);
|
|
1855
|
+
const supported = await dp.supportsDiscovery({});
|
|
1856
|
+
if (!supported) {
|
|
1857
|
+
throw new Error(`Addon "${input.addonId}" does not support device discovery`);
|
|
1858
|
+
}
|
|
1859
|
+
const discovered = await dp.discoverDevices({});
|
|
1860
|
+
return discovered.map((d) => ({
|
|
1861
|
+
stableId: d.stableId,
|
|
1862
|
+
type: d.type,
|
|
1863
|
+
suggestedName: d.suggestedName,
|
|
1864
|
+
prefilledConfig: d.prefilledConfig
|
|
1865
|
+
}));
|
|
1866
|
+
},
|
|
1867
|
+
adoptDevice: async (input) => {
|
|
1868
|
+
const dp = await this.requireDeviceProvider(input.addonId);
|
|
1869
|
+
const supported = await dp.supportsDiscovery({});
|
|
1870
|
+
if (!supported) {
|
|
1871
|
+
throw new Error(`Addon "${input.addonId}" does not support device adoption`);
|
|
1872
|
+
}
|
|
1873
|
+
return dp.adoptDiscoveredDevice({
|
|
1874
|
+
candidate: input.candidate
|
|
1875
|
+
});
|
|
1876
|
+
},
|
|
1877
|
+
getCreationSchema: async (input) => {
|
|
1878
|
+
const dp = await this.requireDeviceProvider(input.addonId);
|
|
1879
|
+
const supported = await dp.supportsManualCreation({});
|
|
1880
|
+
if (!supported) return null;
|
|
1881
|
+
const schema = await dp.getChildCreationSchema({ type: input.type });
|
|
1882
|
+
return schema ?? null;
|
|
1883
|
+
},
|
|
1884
|
+
createDevice: async (input) => {
|
|
1885
|
+
const dp = await this.requireDeviceProvider(input.addonId);
|
|
1886
|
+
const supported = await dp.supportsManualCreation({});
|
|
1887
|
+
if (!supported) {
|
|
1888
|
+
throw new Error(`Addon "${input.addonId}" does not support manual device creation`);
|
|
1889
|
+
}
|
|
1890
|
+
return dp.createDevice({ type: input.type, config: input.config });
|
|
1891
|
+
},
|
|
1892
|
+
testCreationField: async (input) => {
|
|
1893
|
+
const dp = await this.requireDeviceProvider(input.addonId);
|
|
1894
|
+
return dp.testCreationField({
|
|
1895
|
+
type: input.type,
|
|
1896
|
+
key: input.key,
|
|
1897
|
+
value: input.value,
|
|
1898
|
+
...input.formValues !== void 0 ? { formValues: input.formValues } : {}
|
|
1899
|
+
});
|
|
1900
|
+
},
|
|
1901
|
+
testField: async (input) => {
|
|
1902
|
+
const { deviceId } = input;
|
|
1903
|
+
let owningAddonId = null;
|
|
1904
|
+
if (registry) {
|
|
1905
|
+
owningAddonId = registry.getAddonId(deviceId);
|
|
1906
|
+
}
|
|
1907
|
+
if (!owningAddonId) {
|
|
1908
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
1909
|
+
owningAddonId = persisted?.addonId ?? null;
|
|
1910
|
+
}
|
|
1911
|
+
if (!owningAddonId) {
|
|
1912
|
+
throw new Error(`Device with id ${deviceId} not found`);
|
|
1913
|
+
}
|
|
1914
|
+
const dp = await this.waitDeviceProvider(owningAddonId);
|
|
1915
|
+
if (!dp) {
|
|
1916
|
+
return { status: "ok", labels: [], error: void 0 };
|
|
1917
|
+
}
|
|
1918
|
+
if (typeof dp.testCreationField !== "function") {
|
|
1919
|
+
return { status: "ok", labels: [], error: void 0 };
|
|
1920
|
+
}
|
|
1921
|
+
return dp.testCreationField({ type: DeviceType.Camera, key: input.key, value: input.value });
|
|
1922
|
+
},
|
|
1923
|
+
// ── Bindings — per-device capability provider map ────────────────────
|
|
1924
|
+
getBindings: async (input) => {
|
|
1925
|
+
const result = await this.getBindings({ deviceId: input.deviceId });
|
|
1926
|
+
return { deviceId: input.deviceId, entries: result.entries };
|
|
1927
|
+
},
|
|
1928
|
+
getAllBindings: async () => {
|
|
1929
|
+
return this.getAllBindings();
|
|
1930
|
+
},
|
|
1931
|
+
setWrapperActive: async (input) => {
|
|
1932
|
+
return this.setWrapperActive({
|
|
1933
|
+
deviceId: input.deviceId,
|
|
1934
|
+
capName: input.capName,
|
|
1935
|
+
wrapperAddonId: input.wrapperAddonId,
|
|
1936
|
+
active: input.active
|
|
1937
|
+
});
|
|
1938
|
+
},
|
|
1939
|
+
listWrappersForCap: async (input) => this.listWrappersForCap(input),
|
|
1940
|
+
listBindableCapsForDeviceType: async (input) => this.listBindableCapsForDeviceType(input),
|
|
1941
|
+
// ── Device-details aggregators ──────────────────────────────────────
|
|
1942
|
+
getDeviceSettingsAggregate: async (input) => {
|
|
1943
|
+
return this.getDeviceAggregate(input.deviceId, "settings");
|
|
1944
|
+
},
|
|
1945
|
+
getDeviceLiveInfoAggregate: async (input) => {
|
|
1946
|
+
return this.getDeviceAggregate(input.deviceId, "live");
|
|
1947
|
+
},
|
|
1948
|
+
getDeviceAggregate: async (input) => {
|
|
1949
|
+
const [settings2, live] = await Promise.all([
|
|
1950
|
+
this.getDeviceAggregate(input.deviceId, "settings"),
|
|
1951
|
+
this.getDeviceAggregate(input.deviceId, "live")
|
|
1952
|
+
]);
|
|
1953
|
+
return { settings: settings2, live };
|
|
1954
|
+
},
|
|
1955
|
+
updateDeviceField: async (input) => {
|
|
1956
|
+
return this.updateDeviceField({
|
|
1957
|
+
deviceId: input.deviceId,
|
|
1958
|
+
writerCapName: input.writerCapName,
|
|
1959
|
+
writerAddonId: input.writerAddonId,
|
|
1960
|
+
key: input.key,
|
|
1961
|
+
value: input.value
|
|
1962
|
+
});
|
|
1963
|
+
},
|
|
1964
|
+
updateDeviceFieldsBatch: async (input) => {
|
|
1965
|
+
return this.updateDeviceFieldsBatch({ deviceId: input.deviceId, changes: input.changes });
|
|
1966
|
+
},
|
|
1967
|
+
getDeviceStatusAggregate: async (input) => this.getDeviceStatusAggregate(input)
|
|
1968
|
+
};
|
|
1969
|
+
this.ctx.logger.info("registered device-manager capability", { meta: { liveRegistry: registry !== null } });
|
|
1970
|
+
if (registry) {
|
|
1971
|
+
this.propagator = new DeviceEventPropagator({
|
|
1972
|
+
eventBus: this.ctx.eventBus,
|
|
1973
|
+
getParentOf: (id) => registry.getById(id)?.parentDeviceId ?? null,
|
|
1974
|
+
logger: {
|
|
1975
|
+
warn: (msg, meta) => this.ctx.logger.warn(msg, meta ?? {}),
|
|
1976
|
+
debug: (msg, meta) => this.ctx.logger.debug(msg, meta ?? {})
|
|
1977
|
+
}
|
|
1978
|
+
});
|
|
1979
|
+
this.propagator.start();
|
|
1980
|
+
this.ctx.logger.info("device-event-propagator started");
|
|
1981
|
+
}
|
|
1982
|
+
const deviceStateProvider = {
|
|
1983
|
+
getSnapshot: async (input) => {
|
|
1984
|
+
return this.snapshotForDevice(input.deviceId);
|
|
1985
|
+
},
|
|
1986
|
+
getCapSlice: async (input) => {
|
|
1987
|
+
const perCap = this.stateMirror.get(input.deviceId);
|
|
1988
|
+
const slice = perCap?.get(input.capName);
|
|
1989
|
+
return slice ? { ...slice } : null;
|
|
1990
|
+
},
|
|
1991
|
+
// Whole-system warm-boot dump. Iterates the mirror once and
|
|
1992
|
+
// returns a deeply-cloned `{[deviceId]: {[capName]: slice}}`
|
|
1993
|
+
// payload so callers (SystemManager, dashboards) seed their
|
|
1994
|
+
// local mirror with one round-trip instead of N per-device
|
|
1995
|
+
// calls. Empty inner record for devices with no slices yet.
|
|
1996
|
+
getAllSnapshots: async () => {
|
|
1997
|
+
const out = {};
|
|
1998
|
+
for (const [deviceId, perCap] of this.stateMirror) {
|
|
1999
|
+
const dev = {};
|
|
2000
|
+
for (const [capName, slice] of perCap) dev[capName] = { ...slice };
|
|
2001
|
+
out[String(deviceId)] = dev;
|
|
2002
|
+
}
|
|
2003
|
+
return out;
|
|
2004
|
+
},
|
|
2005
|
+
// Canonical cross-layer write — the single entrypoint every
|
|
2006
|
+
// caller funnels through. In-process providers reach it via
|
|
2007
|
+
// `BaseDevice.runtimeState.setCapState` (which delegates here);
|
|
2008
|
+
// system-scope addons (e.g. pipeline runner writing the motion
|
|
2009
|
+
// slice on phase transitions) call this cap method directly
|
|
2010
|
+
// through `ctx.api.deviceState.setCapSlice.mutate(...)`.
|
|
2011
|
+
setCapSlice: async (input) => {
|
|
2012
|
+
const { deviceId, capName, slice } = input;
|
|
2013
|
+
const persisted = await resolvePersistedById(deviceId);
|
|
2014
|
+
if (!persisted) throw new Error(`[device-manager] setCapSlice: unknown device id=${deviceId}`);
|
|
2015
|
+
this.applySingleCapUpdate(deviceId, capName, slice);
|
|
2016
|
+
this.scheduleRuntimeStateDiskWrite(deviceId, settings);
|
|
2017
|
+
}
|
|
2018
|
+
};
|
|
2019
|
+
return [
|
|
2020
|
+
{ capability: deviceManagerCapability, provider },
|
|
2021
|
+
{ capability: deviceStateCapability, provider: deviceStateProvider }
|
|
2022
|
+
];
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Single-cap mirror update — diff against the current mirror,
|
|
2026
|
+
* persist the new slice in-memory, emit `DeviceStateChanged` for
|
|
2027
|
+
* this cap. No-op on identical writes (both same shape and same
|
|
2028
|
+
* values). Called by `setCapSlice` provider.
|
|
2029
|
+
*/
|
|
2030
|
+
applySingleCapUpdate(deviceId, capName, slice) {
|
|
2031
|
+
let perCap = this.stateMirror.get(deviceId);
|
|
2032
|
+
if (!perCap) {
|
|
2033
|
+
perCap = /* @__PURE__ */ new Map();
|
|
2034
|
+
this.stateMirror.set(deviceId, perCap);
|
|
2035
|
+
}
|
|
2036
|
+
const prior = perCap.get(capName);
|
|
2037
|
+
if (prior && shallowEqual(prior, slice)) return;
|
|
2038
|
+
perCap.set(capName, { ...slice });
|
|
2039
|
+
this.emitStateChanged(deviceId, capName, slice);
|
|
2040
|
+
}
|
|
2041
|
+
/**
|
|
2042
|
+
* Debounced disk writer. Coalesces frequent writes (motion phase
|
|
2043
|
+
* transitions, battery pushes) into one `writeDeviceRuntimeState`
|
|
2044
|
+
* per `RUNTIME_STATE_DEBOUNCE_MS` window. Reads the per-device
|
|
2045
|
+
* blob from the live mirror at flush time so the disk picture is
|
|
2046
|
+
* always the latest state — no risk of writing a stale snapshot.
|
|
2047
|
+
*/
|
|
2048
|
+
scheduleRuntimeStateDiskWrite(deviceId, settings) {
|
|
2049
|
+
let slot = this.runtimeStateDebounce.get(deviceId);
|
|
2050
|
+
if (!slot) {
|
|
2051
|
+
slot = { timer: null, inFlight: null };
|
|
2052
|
+
this.runtimeStateDebounce.set(deviceId, slot);
|
|
2053
|
+
}
|
|
2054
|
+
if (slot.timer) return;
|
|
2055
|
+
slot.timer = setTimeout(() => {
|
|
2056
|
+
slot.timer = null;
|
|
2057
|
+
const blob = this.snapshotForDevice(deviceId);
|
|
2058
|
+
const write = (async () => {
|
|
2059
|
+
try {
|
|
2060
|
+
await settings.writeDeviceRuntimeState(deviceId, blob);
|
|
2061
|
+
} catch (err) {
|
|
2062
|
+
this.ctx.logger.warn("writeDeviceRuntimeState failed", {
|
|
2063
|
+
tags: { deviceId },
|
|
2064
|
+
meta: { error: err instanceof Error ? err.message : String(err) }
|
|
2065
|
+
});
|
|
2066
|
+
} finally {
|
|
2067
|
+
slot.inFlight = null;
|
|
2068
|
+
}
|
|
2069
|
+
})();
|
|
2070
|
+
slot.inFlight = write;
|
|
2071
|
+
}, _DeviceManagerAddon.RUNTIME_STATE_DEBOUNCE_MS);
|
|
2072
|
+
}
|
|
2073
|
+
/**
|
|
2074
|
+
* One-shot mirror seed used by `loadRuntimeState` at boot so the
|
|
2075
|
+
* hub knows about every persisted slice without waiting for the
|
|
2076
|
+
* first `setCapSlice` call. No events emitted — this is
|
|
2077
|
+
* initial-state population, not a transition.
|
|
2078
|
+
*/
|
|
2079
|
+
seedMirror(deviceId, blob) {
|
|
2080
|
+
let perCap = this.stateMirror.get(deviceId);
|
|
2081
|
+
if (!perCap) {
|
|
2082
|
+
perCap = /* @__PURE__ */ new Map();
|
|
2083
|
+
this.stateMirror.set(deviceId, perCap);
|
|
2084
|
+
}
|
|
2085
|
+
for (const [capName, raw] of Object.entries(blob)) {
|
|
2086
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
|
|
2087
|
+
perCap.set(capName, { ...raw });
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
snapshotForDevice(deviceId) {
|
|
2091
|
+
const perCap = this.stateMirror.get(deviceId);
|
|
2092
|
+
if (!perCap) return {};
|
|
2093
|
+
const out = {};
|
|
2094
|
+
for (const [k, v] of perCap) out[k] = { ...v };
|
|
2095
|
+
return out;
|
|
2096
|
+
}
|
|
2097
|
+
emitStateChanged(deviceId, capName, slice) {
|
|
2098
|
+
this.ctx.eventBus.emit({
|
|
2099
|
+
id: randomUUID(),
|
|
2100
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
2101
|
+
source: { type: "device", id: deviceId },
|
|
2102
|
+
category: EventCategory.DeviceStateChanged,
|
|
2103
|
+
data: { deviceId, capName, slice }
|
|
2104
|
+
});
|
|
2105
|
+
}
|
|
2106
|
+
async onShutdown() {
|
|
2107
|
+
this.propagator?.stop();
|
|
2108
|
+
this.propagator = null;
|
|
2109
|
+
const settings = this.ctx.settings;
|
|
2110
|
+
const pending = [];
|
|
2111
|
+
for (const [deviceId, slot] of this.runtimeStateDebounce) {
|
|
2112
|
+
if (slot.timer) {
|
|
2113
|
+
clearTimeout(slot.timer);
|
|
2114
|
+
slot.timer = null;
|
|
2115
|
+
if (settings) {
|
|
2116
|
+
const blob = this.snapshotForDevice(deviceId);
|
|
2117
|
+
pending.push(settings.writeDeviceRuntimeState(deviceId, blob).catch((err) => {
|
|
2118
|
+
this.ctx.logger.warn("shutdown writeDeviceRuntimeState failed", {
|
|
2119
|
+
tags: { deviceId },
|
|
2120
|
+
meta: { error: err instanceof Error ? err.message : String(err) }
|
|
2121
|
+
});
|
|
2122
|
+
}));
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
if (slot.inFlight) pending.push(slot.inFlight);
|
|
2126
|
+
}
|
|
2127
|
+
await Promise.all(pending);
|
|
2128
|
+
this.runtimeStateDebounce.clear();
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
var device_manager_addon_default = DeviceManagerAddon;
|
|
2132
|
+
|
|
2133
|
+
export {
|
|
2134
|
+
DeviceManagerAddon,
|
|
2135
|
+
device_manager_addon_default
|
|
2136
|
+
};
|
|
2137
|
+
//# sourceMappingURL=chunk-O4V246GG.mjs.map
|