node-red-contrib-unifi-ultimate 1.1.5 → 1.1.7
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/README.md +11 -0
- package/nodes/unifi-network-config.js +1 -4
- package/nodes/unifi-protect-config.html +5 -0
- package/nodes/unifi-protect-config.js +233 -0
- package/nodes/utils/knx-ai-camera-registry.js +253 -0
- package/nodes/utils/unifi-protect-device-registry.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -125,6 +125,17 @@ Things you can do:
|
|
|
125
125
|
- Monitor bridges, Link Stations, alarm hubs, key fobs, sirens, relays, and speakers.
|
|
126
126
|
- Play or stop a siren, control relay outputs, and test speaker or siren sound.
|
|
127
127
|
|
|
128
|
+
### Automatic KNX AI camera adapter
|
|
129
|
+
|
|
130
|
+
When `node-red-contrib-knx-ultimate` is installed, every configured **Unifi Protect Config** instance automatically publishes its cameras to the KNX AI chat runtime. No Protect Device node, selector, or intermediate wire is required. KNX AI can then:
|
|
131
|
+
|
|
132
|
+
- send a current camera snapshot to Telegram or RedBot;
|
|
133
|
+
- describe a fresh snapshot with the configured vision-capable LLM;
|
|
134
|
+
- create persistent chat notifications for unclassified motion or generic smart detections, as well as line crossings, intrusion zones, and loiter zones;
|
|
135
|
+
- filter smart events by the camera's supported classifications, including people, animals, vehicles, faces, license plates, and packages, and optionally by an exact line or zone exposed by Protect.
|
|
136
|
+
|
|
137
|
+
The integration uses the generic `node-red.knx-ai.camera-adapters.v1` runtime contract, so other camera packages can register the same catalog/snapshot/event capabilities without vendor-specific code in KNX AI. Protect API keys remain inside this config node and are never copied into KNX AI.
|
|
138
|
+
|
|
128
139
|
<br/>
|
|
129
140
|
<br/>
|
|
130
141
|
<p align="left">
|
|
@@ -907,10 +907,7 @@ module.exports = function(RED) {
|
|
|
907
907
|
let ws;
|
|
908
908
|
try {
|
|
909
909
|
ws = new WebSocket(node.buildUnofficialNetworkWebSocketUrl(), {
|
|
910
|
-
headers:
|
|
911
|
-
[API_KEY_HEADER]: apiKey,
|
|
912
|
-
Accept: "application/json"
|
|
913
|
-
},
|
|
910
|
+
headers: buildRequestHeaders(apiKey),
|
|
914
911
|
rejectUnauthorized: node.rejectUnauthorized
|
|
915
912
|
});
|
|
916
913
|
} catch (error) {
|
|
@@ -122,4 +122,9 @@
|
|
|
122
122
|
<h3>Usage</h3>
|
|
123
123
|
<p>This config node is used by UniFi Protect Device nodes for API requests and live device/event updates.</p>
|
|
124
124
|
<p>All Protect API calls and websocket streams are managed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive broadcast updates.</p>
|
|
125
|
+
|
|
126
|
+
<h3>Automatic KNX AI camera adapter</h3>
|
|
127
|
+
<p>If <code>node-red-contrib-knx-ultimate</code> is installed, this config node automatically publishes its available cameras to the KNX AI chat runtime. No Protect Device node, camera selector, or wire to KNX AI is required.</p>
|
|
128
|
+
<p>KNX AI can request snapshots directly and subscribe to motion, smart line, intrusion-zone, and loiter-zone events. Persistent notification rules remain owned by the KNX AI chat context. The API key stays private inside this config node.</p>
|
|
129
|
+
<p>The provider uses the generic <code>node-red.knx-ai.camera-adapters.v1</code> runtime contract, allowing other camera suites to expose the same capabilities independently.</p>
|
|
125
130
|
</script>
|
|
@@ -17,8 +17,73 @@ const {
|
|
|
17
17
|
normalizeDeviceCollection,
|
|
18
18
|
summarizeDevice
|
|
19
19
|
} = require("./utils/unifi-protect-device-registry");
|
|
20
|
+
const {
|
|
21
|
+
collectNamedScopes,
|
|
22
|
+
getKnxAiCameraRegistry,
|
|
23
|
+
normalizeProtectCameraEvent,
|
|
24
|
+
normalizeSearchText
|
|
25
|
+
} = require("./utils/knx-ai-camera-registry");
|
|
26
|
+
|
|
27
|
+
function extractProtectErrorDetail(response) {
|
|
28
|
+
let payload = response && response.payload;
|
|
29
|
+
if (Buffer.isBuffer(payload)) {
|
|
30
|
+
const text = payload.length <= 8192 ? payload.toString("utf8").trim() : "";
|
|
31
|
+
if (!text) return "";
|
|
32
|
+
try { payload = JSON.parse(text); } catch (error) { payload = text; }
|
|
33
|
+
}
|
|
34
|
+
if (typeof payload === "string") {
|
|
35
|
+
const text = payload.trim();
|
|
36
|
+
if (!text) return "";
|
|
37
|
+
try { payload = JSON.parse(text); } catch (error) { return text.slice(0, 300); }
|
|
38
|
+
}
|
|
39
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return "";
|
|
40
|
+
const nestedError = payload.error && typeof payload.error === "object" ? payload.error : {};
|
|
41
|
+
const detail = payload.detail
|
|
42
|
+
|| payload.message
|
|
43
|
+
|| payload.error_description
|
|
44
|
+
|| nestedError.detail
|
|
45
|
+
|| nestedError.message
|
|
46
|
+
|| (typeof payload.error === "string" ? payload.error : "");
|
|
47
|
+
return String(detail || "").replace(/[\r\n\t]+/g, " ").trim().slice(0, 300);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function createSnapshotError({ camera, response, retriedWithStandardQuality }) {
|
|
51
|
+
const statusCode = Number(response && response.statusCode) || 0;
|
|
52
|
+
const detail = extractProtectErrorDetail(response);
|
|
53
|
+
const cameraState = String(camera && camera.raw && camera.raw.state || camera && camera.state || "")
|
|
54
|
+
.trim()
|
|
55
|
+
.toUpperCase();
|
|
56
|
+
const isOffline = /\boffline\b/i.test(detail)
|
|
57
|
+
|| (statusCode === 503 && cameraState === "DISCONNECTED");
|
|
58
|
+
let message;
|
|
59
|
+
if (isOffline) {
|
|
60
|
+
const stateDetail = cameraState ? `; state: ${cameraState}` : "";
|
|
61
|
+
message = `UniFi Protect snapshot for '${camera.cameraName}' is unavailable because Protect reports that the camera is offline (HTTP ${statusCode || 503}${stateDetail}).`;
|
|
62
|
+
} else if (statusCode === 429) {
|
|
63
|
+
const retryAfter = response && response.headers && response.headers["retry-after"];
|
|
64
|
+
const retryDetail = retryAfter ? `; retry after ${retryAfter} second(s)` : "";
|
|
65
|
+
message = `UniFi Protect temporarily rate-limited the snapshot for '${camera.cameraName}' (HTTP 429${retryDetail}).`;
|
|
66
|
+
} else {
|
|
67
|
+
const apiDetail = detail ? `: ${detail}` : "";
|
|
68
|
+
const retryDetail = retriedWithStandardQuality ? " after one standard-quality retry" : "";
|
|
69
|
+
message = `UniFi Protect snapshot for '${camera.cameraName}' failed (HTTP ${statusCode || "unknown"}${apiDetail})${retryDetail}.`;
|
|
70
|
+
}
|
|
71
|
+
const error = new Error(message);
|
|
72
|
+
error.code = isOffline ? "UNIFI_PROTECT_CAMERA_OFFLINE" : statusCode === 429 ? "UNIFI_PROTECT_RATE_LIMITED" : "UNIFI_PROTECT_SNAPSHOT_FAILED";
|
|
73
|
+
error.statusCode = statusCode;
|
|
74
|
+
error.cameraState = cameraState;
|
|
75
|
+
return error;
|
|
76
|
+
}
|
|
20
77
|
|
|
21
78
|
module.exports = function(RED) {
|
|
79
|
+
const knxAiCameraRegistry = getKnxAiCameraRegistry();
|
|
80
|
+
knxAiCameraRegistry.registerAdapter({
|
|
81
|
+
id: "unifi-ultimate",
|
|
82
|
+
title: "UniFi Ultimate / Protect",
|
|
83
|
+
packageName: "node-red-contrib-unifi-ultimate",
|
|
84
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"]
|
|
85
|
+
});
|
|
86
|
+
|
|
22
87
|
function UnifiProtectConfigNode(config) {
|
|
23
88
|
RED.nodes.createNode(this, config);
|
|
24
89
|
|
|
@@ -35,6 +100,8 @@ module.exports = function(RED) {
|
|
|
35
100
|
node.wsEvents = null;
|
|
36
101
|
node.reconnectTimer = null;
|
|
37
102
|
node.isClosing = false;
|
|
103
|
+
node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
104
|
+
node.knxAiCameraListeners = new Set();
|
|
38
105
|
|
|
39
106
|
node.getApiKey = () => node.credentials && node.credentials.apiKey;
|
|
40
107
|
|
|
@@ -150,6 +217,118 @@ module.exports = function(RED) {
|
|
|
150
217
|
return getCapabilitiesForType(deviceType, selectedDevice);
|
|
151
218
|
};
|
|
152
219
|
|
|
220
|
+
node.listKnxAiCameras = async ({ force = false } = {}) => {
|
|
221
|
+
const now = Date.now();
|
|
222
|
+
if (!force && node.knxAiCameraCache.cameras.length > 0 && (now - node.knxAiCameraCache.at) < 30000) {
|
|
223
|
+
return node.knxAiCameraCache.cameras.slice();
|
|
224
|
+
}
|
|
225
|
+
const cameras = (await node.fetchDevices("camera")).map((camera) => {
|
|
226
|
+
const nativeCameraId = String(camera && camera.id || "").trim();
|
|
227
|
+
const cameraName = String(camera && (camera.name || camera.displayName) || nativeCameraId).trim();
|
|
228
|
+
const cameraState = String(camera && camera.state || "").trim().toUpperCase();
|
|
229
|
+
const objectTypes = Array.from(new Set([].concat(
|
|
230
|
+
camera && camera.smartDetectSettings && Array.isArray(camera.smartDetectSettings.objectTypes)
|
|
231
|
+
? camera.smartDetectSettings.objectTypes
|
|
232
|
+
: [],
|
|
233
|
+
camera && camera.featureFlags && Array.isArray(camera.featureFlags.smartDetectTypes)
|
|
234
|
+
? camera.featureFlags.smartDetectTypes
|
|
235
|
+
: []
|
|
236
|
+
).map((value) => String(value || "").trim()).filter(Boolean)));
|
|
237
|
+
return {
|
|
238
|
+
id: `${node.id}:${nativeCameraId}`,
|
|
239
|
+
cameraId: `${node.id}:${nativeCameraId}`,
|
|
240
|
+
nativeCameraId,
|
|
241
|
+
cameraName,
|
|
242
|
+
name: cameraName,
|
|
243
|
+
aliases: [cameraName, nativeCameraId].filter(Boolean),
|
|
244
|
+
controllerId: node.id,
|
|
245
|
+
controllerName: node.name || node.host || node.id,
|
|
246
|
+
adapterId: "unifi-ultimate",
|
|
247
|
+
adapterTitle: "UniFi Ultimate / Protect",
|
|
248
|
+
source: "unifi-ultimate",
|
|
249
|
+
state: cameraState,
|
|
250
|
+
online: cameraState ? cameraState === "CONNECTED" : null,
|
|
251
|
+
objectTypes,
|
|
252
|
+
lines: collectNamedScopes(camera, "line"),
|
|
253
|
+
zones: collectNamedScopes(camera, "zone"),
|
|
254
|
+
raw: camera
|
|
255
|
+
};
|
|
256
|
+
}).filter((camera) => camera.nativeCameraId);
|
|
257
|
+
node.knxAiCameraCache = { at: now, cameras };
|
|
258
|
+
return cameras.slice();
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
node.resolveKnxAiCamera = async ({ cameraId, cameraName } = {}) => {
|
|
262
|
+
const cameras = await node.listKnxAiCameras();
|
|
263
|
+
const requestedId = String(cameraId || "").trim();
|
|
264
|
+
const requestedName = normalizeSearchText(cameraName);
|
|
265
|
+
const exact = cameras.filter((camera) => {
|
|
266
|
+
return requestedId && [camera.id, camera.cameraId, camera.nativeCameraId].includes(requestedId)
|
|
267
|
+
|| requestedName && [camera.cameraName, camera.name].concat(camera.aliases || []).some((value) => normalizeSearchText(value) === requestedName);
|
|
268
|
+
});
|
|
269
|
+
if (exact.length === 1) return exact[0];
|
|
270
|
+
if (exact.length > 1) throw new Error("The camera name is ambiguous.");
|
|
271
|
+
const partial = requestedName ? cameras.filter((camera) => {
|
|
272
|
+
return [camera.cameraName, camera.name].concat(camera.aliases || []).some((value) => {
|
|
273
|
+
const candidate = normalizeSearchText(value);
|
|
274
|
+
return candidate && (candidate.includes(requestedName) || requestedName.includes(candidate));
|
|
275
|
+
});
|
|
276
|
+
}) : [];
|
|
277
|
+
if (partial.length === 1) return partial[0];
|
|
278
|
+
if (partial.length > 1) throw new Error("The camera name is ambiguous.");
|
|
279
|
+
throw new Error("Camera not found in this UniFi Protect controller.");
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
node.takeKnxAiCameraSnapshot = async ({ cameraId, cameraName, highQuality = false } = {}) => {
|
|
283
|
+
const camera = await node.resolveKnxAiCamera({ cameraId, cameraName });
|
|
284
|
+
const supportsHighQuality = camera.raw
|
|
285
|
+
&& camera.raw.featureFlags
|
|
286
|
+
&& camera.raw.featureFlags.supportFullHdSnapshot === true;
|
|
287
|
+
const requestHighQuality = highQuality === true && supportsHighQuality;
|
|
288
|
+
const requestSnapshot = (useHighQuality) => node.apiRequest({
|
|
289
|
+
path: `/v1/cameras/${encodeURIComponent(camera.nativeCameraId)}/snapshot`,
|
|
290
|
+
method: "GET",
|
|
291
|
+
// The Protect API defaults to standard quality. Do not send the
|
|
292
|
+
// highQuality flag unless this camera explicitly advertises it.
|
|
293
|
+
query: useHighQuality ? { highQuality: "true" } : {},
|
|
294
|
+
headers: { Accept: "image/jpeg" },
|
|
295
|
+
timeout: 20000
|
|
296
|
+
});
|
|
297
|
+
let response = await requestSnapshot(requestHighQuality);
|
|
298
|
+
const statusCode = Number(response && response.statusCode) || 0;
|
|
299
|
+
const firstErrorDetail = extractProtectErrorDetail(response);
|
|
300
|
+
const cameraState = String(camera && camera.raw && camera.raw.state || "").trim().toUpperCase();
|
|
301
|
+
const cameraIsOffline = /\boffline\b/i.test(firstErrorDetail)
|
|
302
|
+
|| (statusCode === 503 && cameraState === "DISCONNECTED");
|
|
303
|
+
const shouldRetryStandard = !cameraIsOffline && (requestHighQuality
|
|
304
|
+
? [400, 409, 422, 500, 502, 503, 504].includes(statusCode)
|
|
305
|
+
: [502, 503, 504].includes(statusCode));
|
|
306
|
+
let retriedWithStandardQuality = false;
|
|
307
|
+
if (shouldRetryStandard) {
|
|
308
|
+
// Some Protect/camera combinations reject forced full-HD
|
|
309
|
+
// snapshots with 503 even though a normal snapshot is ready.
|
|
310
|
+
retriedWithStandardQuality = true;
|
|
311
|
+
response = await requestSnapshot(false);
|
|
312
|
+
}
|
|
313
|
+
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
314
|
+
throw createSnapshotError({ camera, response, retriedWithStandardQuality });
|
|
315
|
+
}
|
|
316
|
+
if (!Buffer.isBuffer(response.payload) || response.payload.length === 0) {
|
|
317
|
+
throw new Error("UniFi Protect returned an empty or invalid snapshot.");
|
|
318
|
+
}
|
|
319
|
+
const contentTypeHeader = response.headers && response.headers["content-type"];
|
|
320
|
+
const mediaType = String(Array.isArray(contentTypeHeader) ? contentTypeHeader[0] : contentTypeHeader || "image/jpeg")
|
|
321
|
+
.split(";")[0]
|
|
322
|
+
.trim()
|
|
323
|
+
.toLowerCase();
|
|
324
|
+
return {
|
|
325
|
+
data: response.payload,
|
|
326
|
+
mediaType,
|
|
327
|
+
camera,
|
|
328
|
+
statusCode: response.statusCode
|
|
329
|
+
};
|
|
330
|
+
};
|
|
331
|
+
|
|
153
332
|
node.buildWebSocketUrl = (path) => {
|
|
154
333
|
// Reuse the configured HTTPS base URL and only swap protocol for the
|
|
155
334
|
// matching websocket scheme.
|
|
@@ -328,9 +507,63 @@ module.exports = function(RED) {
|
|
|
328
507
|
}
|
|
329
508
|
};
|
|
330
509
|
|
|
510
|
+
const knxAiBridgeClient = {
|
|
511
|
+
id: `knx-ai-camera-adapter:${node.id}`,
|
|
512
|
+
handleProtectDeviceUpdate(update) {
|
|
513
|
+
const item = update && update.item;
|
|
514
|
+
if (item && item.modelKey === "camera") node.knxAiCameraCache = { at: 0, cameras: [] };
|
|
515
|
+
},
|
|
516
|
+
handleProtectEventUpdate(update) {
|
|
517
|
+
const item = update && update.item;
|
|
518
|
+
if (!item || item.modelKey !== "event" || node.knxAiCameraListeners.size === 0) return;
|
|
519
|
+
Promise.resolve(node.listKnxAiCameras()).then((cameras) => {
|
|
520
|
+
const camera = cameras.find((entry) => entry.nativeCameraId === String(item.device || ""));
|
|
521
|
+
const event = normalizeProtectCameraEvent({
|
|
522
|
+
event: item,
|
|
523
|
+
camera: camera && camera.raw,
|
|
524
|
+
controllerId: node.id,
|
|
525
|
+
controllerName: node.name || node.host || node.id
|
|
526
|
+
});
|
|
527
|
+
if (!event) return;
|
|
528
|
+
node.knxAiCameraListeners.forEach((listener) => {
|
|
529
|
+
try { listener(event); } catch (error) { }
|
|
530
|
+
});
|
|
531
|
+
}).catch((error) => {
|
|
532
|
+
node.warn(`KNX AI camera event adapter failed: ${error && error.message ? error.message : error}`);
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
const knxAiProvider = {
|
|
538
|
+
id: `unifi-ultimate:${node.id}`,
|
|
539
|
+
adapterId: "unifi-ultimate",
|
|
540
|
+
title: "UniFi Ultimate / Protect",
|
|
541
|
+
packageName: "node-red-contrib-unifi-ultimate",
|
|
542
|
+
controllerId: node.id,
|
|
543
|
+
controllerName: node.name || node.host || node.id,
|
|
544
|
+
capabilities: ["camera_catalog", "snapshot", "motion", "smart_events", "zones", "lines"],
|
|
545
|
+
listCameras: (options) => node.listKnxAiCameras(options),
|
|
546
|
+
takeSnapshot: (request) => node.takeKnxAiCameraSnapshot(request),
|
|
547
|
+
subscribe(listener) {
|
|
548
|
+
if (typeof listener !== "function") return () => { };
|
|
549
|
+
const wasEmpty = node.knxAiCameraListeners.size === 0;
|
|
550
|
+
node.knxAiCameraListeners.add(listener);
|
|
551
|
+
if (wasEmpty) node.addClient(knxAiBridgeClient);
|
|
552
|
+
return () => {
|
|
553
|
+
node.knxAiCameraListeners.delete(listener);
|
|
554
|
+
if (node.knxAiCameraListeners.size === 0) node.removeClient(knxAiBridgeClient);
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
node.knxAiCameraProvider = knxAiProvider;
|
|
559
|
+
knxAiCameraRegistry.registerProvider(knxAiProvider);
|
|
560
|
+
|
|
331
561
|
node.on("close", function(done) {
|
|
332
562
|
try {
|
|
333
563
|
node.isClosing = true;
|
|
564
|
+
knxAiCameraRegistry.unregisterProvider(knxAiProvider.id);
|
|
565
|
+
node.knxAiCameraListeners.clear();
|
|
566
|
+
node.removeClient(knxAiBridgeClient);
|
|
334
567
|
node.closeWebSockets();
|
|
335
568
|
} catch (error) {
|
|
336
569
|
} finally {
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const KNX_AI_CAMERA_REGISTRY_KEY = Symbol.for("node-red.knx-ai.camera-adapters.v1");
|
|
4
|
+
const SMART_CAMERA_EVENTS = new Set([
|
|
5
|
+
"motion",
|
|
6
|
+
"ring",
|
|
7
|
+
"smartAudioDetect",
|
|
8
|
+
"smartDetectZone",
|
|
9
|
+
"smartDetectLine",
|
|
10
|
+
"smartDetectLoiterZone"
|
|
11
|
+
]);
|
|
12
|
+
|
|
13
|
+
function normalizeText(value, maxLength = 240) {
|
|
14
|
+
return String(value === undefined || value === null ? "" : value).trim().slice(0, maxLength);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function normalizeSearchText(value) {
|
|
18
|
+
return normalizeText(value, 300)
|
|
19
|
+
.normalize("NFKD")
|
|
20
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
21
|
+
.toLowerCase()
|
|
22
|
+
.replace(/[^a-z0-9]+/g, " ")
|
|
23
|
+
.trim();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// This is the vendor-neutral KNX AI camera adapter contract. Keep this registry
|
|
27
|
+
// shape aligned with KNX Ultimate: an adapter describes package capabilities,
|
|
28
|
+
// while each configured controller registers a provider implementing
|
|
29
|
+
// listCameras(), takeSnapshot(), and subscribe(). The shared Symbol avoids any
|
|
30
|
+
// direct package dependency or flow wiring.
|
|
31
|
+
function getKnxAiCameraRegistry() {
|
|
32
|
+
const existing = globalThis[KNX_AI_CAMERA_REGISTRY_KEY];
|
|
33
|
+
if (existing && existing.version === 1 && existing.adapters instanceof Map && existing.providers instanceof Map) {
|
|
34
|
+
return existing;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const registry = {
|
|
38
|
+
version: 1,
|
|
39
|
+
adapters: new Map(),
|
|
40
|
+
providers: new Map(),
|
|
41
|
+
listeners: new Set(),
|
|
42
|
+
registerAdapter(adapter) {
|
|
43
|
+
if (!adapter || !adapter.id) return;
|
|
44
|
+
this.adapters.set(String(adapter.id), Object.freeze({ ...adapter }));
|
|
45
|
+
this.listeners.forEach((listener) => {
|
|
46
|
+
try { listener({ type: "adapter_registered", adapter: this.adapters.get(String(adapter.id)) }); } catch (error) { }
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
registerProvider(provider) {
|
|
50
|
+
if (!provider || !provider.id) return;
|
|
51
|
+
this.providers.set(String(provider.id), provider);
|
|
52
|
+
this.listeners.forEach((listener) => {
|
|
53
|
+
try { listener({ type: "provider_registered", provider }); } catch (error) { }
|
|
54
|
+
});
|
|
55
|
+
},
|
|
56
|
+
unregisterProvider(providerId) {
|
|
57
|
+
const id = String(providerId || "");
|
|
58
|
+
const provider = this.providers.get(id);
|
|
59
|
+
if (!provider) return;
|
|
60
|
+
this.providers.delete(id);
|
|
61
|
+
this.listeners.forEach((listener) => {
|
|
62
|
+
try { listener({ type: "provider_unregistered", provider }); } catch (error) { }
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
subscribe(listener) {
|
|
66
|
+
if (typeof listener !== "function") return () => { };
|
|
67
|
+
this.listeners.add(listener);
|
|
68
|
+
return () => this.listeners.delete(listener);
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
globalThis[KNX_AI_CAMERA_REGISTRY_KEY] = registry;
|
|
72
|
+
return registry;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function collectNamedScopes(camera, scopeKind) {
|
|
76
|
+
if (!camera || typeof camera !== "object" || Array.isArray(camera)) return [];
|
|
77
|
+
const branchPattern = scopeKind === "line"
|
|
78
|
+
? /(line|lines|smart.?detect.?line)/i
|
|
79
|
+
: /(zone|zones|smart.?detect.?zone|loiter)/i;
|
|
80
|
+
const idKeys = scopeKind === "line"
|
|
81
|
+
? ["lineId", "lineID", "line_id", "id", "index"]
|
|
82
|
+
: ["zoneId", "zoneID", "zone_id", "id", "index"];
|
|
83
|
+
const byId = new Map();
|
|
84
|
+
const visited = new Set();
|
|
85
|
+
|
|
86
|
+
function firstValue(value, keys) {
|
|
87
|
+
for (const key of keys) {
|
|
88
|
+
if (value && value[key] !== undefined && value[key] !== null && String(value[key]).trim()) return value[key];
|
|
89
|
+
}
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function add(idValue, labelValue) {
|
|
94
|
+
const id = normalizeText(idValue, 160);
|
|
95
|
+
if (!id || byId.has(id)) return;
|
|
96
|
+
byId.set(id, {
|
|
97
|
+
id,
|
|
98
|
+
name: normalizeText(labelValue, 240) || `${scopeKind === "line" ? "Line" : "Zone"} ${id}`
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function collect(candidate) {
|
|
103
|
+
if (candidate === undefined || candidate === null) return;
|
|
104
|
+
if (typeof candidate === "string" || typeof candidate === "number") {
|
|
105
|
+
add(candidate, "");
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (Array.isArray(candidate)) {
|
|
109
|
+
candidate.forEach((entry) => {
|
|
110
|
+
if (entry && typeof entry === "object") {
|
|
111
|
+
add(firstValue(entry, idKeys), firstValue(entry, ["name", "displayName", "label", "title"]));
|
|
112
|
+
} else {
|
|
113
|
+
add(entry, "");
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (typeof candidate === "object") {
|
|
119
|
+
add(firstValue(candidate, idKeys), firstValue(candidate, ["name", "displayName", "label", "title"]));
|
|
120
|
+
Object.entries(candidate).forEach(([key, value]) => {
|
|
121
|
+
if (/^-?\d+$/.test(key)) {
|
|
122
|
+
add(key, value && typeof value === "object" ? firstValue(value, ["name", "displayName", "label", "title"]) : "");
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function walk(value, depth) {
|
|
129
|
+
if (!value || typeof value !== "object" || visited.has(value) || depth > 8) return;
|
|
130
|
+
visited.add(value);
|
|
131
|
+
Object.entries(value).forEach(([key, nested]) => {
|
|
132
|
+
if (branchPattern.test(key)) collect(nested);
|
|
133
|
+
walk(nested, depth + 1);
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
walk(camera, 0);
|
|
138
|
+
return Array.from(byId.values()).sort((left, right) => left.name.localeCompare(right.name));
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function collectEventScopeIds(event, scopeKind) {
|
|
142
|
+
if (!event || typeof event !== "object") return [];
|
|
143
|
+
const keyPattern = scopeKind === "line"
|
|
144
|
+
? /(lineIds?|smart.?detect.?lineIds?)/i
|
|
145
|
+
: /(zoneIds?|smart.?detect.?zoneIds?|loiterZoneIds?)/i;
|
|
146
|
+
const idKeys = scopeKind === "line"
|
|
147
|
+
? ["lineId", "lineID", "line_id", "id"]
|
|
148
|
+
: ["zoneId", "zoneID", "zone_id", "id"];
|
|
149
|
+
const ids = new Set();
|
|
150
|
+
const visited = new Set();
|
|
151
|
+
|
|
152
|
+
function add(value) {
|
|
153
|
+
const id = normalizeText(value, 160);
|
|
154
|
+
if (id) ids.add(id);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function collect(value) {
|
|
158
|
+
if (value === undefined || value === null) return;
|
|
159
|
+
if (typeof value === "string" || typeof value === "number") return add(value);
|
|
160
|
+
if (Array.isArray(value)) return value.forEach(collect);
|
|
161
|
+
if (typeof value === "object") {
|
|
162
|
+
for (const key of idKeys) {
|
|
163
|
+
if (value[key] !== undefined) add(value[key]);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function walk(value, depth) {
|
|
169
|
+
if (!value || typeof value !== "object" || visited.has(value) || depth > 8) return;
|
|
170
|
+
visited.add(value);
|
|
171
|
+
Object.entries(value).forEach(([key, nested]) => {
|
|
172
|
+
if (keyPattern.test(key)) collect(nested);
|
|
173
|
+
walk(nested, depth + 1);
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
walk(event, 0);
|
|
178
|
+
return Array.from(ids);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function collectDetectedObjectTypes(event) {
|
|
182
|
+
const types = new Set();
|
|
183
|
+
const visited = new Set();
|
|
184
|
+
const keyPattern = /(smart.?detect.?types?|detection.?types?|object.?types?|detected.?objects?)/i;
|
|
185
|
+
|
|
186
|
+
function add(value) {
|
|
187
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
188
|
+
const normalized = normalizeSearchText(value);
|
|
189
|
+
if (normalized) types.add(normalized);
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
if (Array.isArray(value)) value.forEach(add);
|
|
193
|
+
if (value && typeof value === "object") {
|
|
194
|
+
["type", "label", "name", "objectType"].forEach((key) => {
|
|
195
|
+
if (value[key] !== undefined) add(value[key]);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function walk(value, depth) {
|
|
201
|
+
if (!value || typeof value !== "object" || visited.has(value) || depth > 8) return;
|
|
202
|
+
visited.add(value);
|
|
203
|
+
Object.entries(value).forEach(([key, nested]) => {
|
|
204
|
+
if (keyPattern.test(key)) add(nested);
|
|
205
|
+
walk(nested, depth + 1);
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
walk(event, 0);
|
|
210
|
+
return Array.from(types).slice(0, 12);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function normalizeProtectCameraEvent({ event, camera, controllerId, controllerName } = {}) {
|
|
214
|
+
if (!event || typeof event !== "object" || event.modelKey !== "event") return null;
|
|
215
|
+
const eventType = normalizeText(event.type, 80);
|
|
216
|
+
const nativeCameraId = normalizeText(event.device, 160);
|
|
217
|
+
if (!nativeCameraId || !SMART_CAMERA_EVENTS.has(eventType)) return null;
|
|
218
|
+
const scopeKind = eventType === "smartDetectLine" ? "line"
|
|
219
|
+
: ["smartDetectZone", "smartDetectLoiterZone"].includes(eventType) ? "zone" : "";
|
|
220
|
+
const scopeIds = scopeKind ? collectEventScopeIds(event, scopeKind) : [];
|
|
221
|
+
const knownScopes = scopeKind ? collectNamedScopes(camera, scopeKind) : [];
|
|
222
|
+
const scopeId = scopeIds[0] || "";
|
|
223
|
+
const scope = knownScopes.find((item) => item.id === scopeId);
|
|
224
|
+
const cameraName = normalizeText(camera && (camera.name || camera.displayName), 240) || nativeCameraId;
|
|
225
|
+
return {
|
|
226
|
+
source: "unifi-ultimate",
|
|
227
|
+
controllerId: normalizeText(controllerId, 160),
|
|
228
|
+
controllerName: normalizeText(controllerName, 240),
|
|
229
|
+
cameraId: `${normalizeText(controllerId, 160)}:${nativeCameraId}`,
|
|
230
|
+
nativeCameraId,
|
|
231
|
+
cameraName,
|
|
232
|
+
eventId: normalizeText(event.id, 160),
|
|
233
|
+
eventType,
|
|
234
|
+
active: event.end === null || event.end === undefined,
|
|
235
|
+
scopeId,
|
|
236
|
+
scopeName: scope ? scope.name : "",
|
|
237
|
+
scopeIds,
|
|
238
|
+
objectTypes: collectDetectedObjectTypes(event),
|
|
239
|
+
at: new Date(Number(event.start || event.timestamp || Date.now())).toISOString(),
|
|
240
|
+
raw: event
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
module.exports = {
|
|
245
|
+
KNX_AI_CAMERA_REGISTRY_KEY,
|
|
246
|
+
SMART_CAMERA_EVENTS,
|
|
247
|
+
collectDetectedObjectTypes,
|
|
248
|
+
collectEventScopeIds,
|
|
249
|
+
collectNamedScopes,
|
|
250
|
+
getKnxAiCameraRegistry,
|
|
251
|
+
normalizeProtectCameraEvent,
|
|
252
|
+
normalizeSearchText
|
|
253
|
+
};
|
|
@@ -358,7 +358,7 @@ const TYPE_CAPABILITIES = {
|
|
|
358
358
|
},
|
|
359
359
|
requestComposer: ({ capabilityConfig }) => ({
|
|
360
360
|
query: capabilityConfig.forceHighQuality
|
|
361
|
-
? {
|
|
361
|
+
? { highQuality: capabilityConfig.forceHighQuality }
|
|
362
362
|
: {}
|
|
363
363
|
})
|
|
364
364
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "node-red-contrib-unifi-ultimate",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.7",
|
|
4
4
|
"description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
|
|
5
5
|
"files": [
|
|
6
6
|
"nodes/",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
}
|
|
67
67
|
},
|
|
68
68
|
"scripts": {
|
|
69
|
-
"test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
|
|
69
|
+
"test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-network-presence-utils.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check nodes/utils/knx-ai-camera-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
|
|
70
70
|
"registry:discover:network": "node scripts/discover-unifi-network-registry.js",
|
|
71
71
|
"registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
|
|
72
72
|
"registry:discover:access": "node scripts/discover-unifi-access-registry.js"
|
|
@@ -82,4 +82,4 @@
|
|
|
82
82
|
"bugs": {
|
|
83
83
|
"url": "https://github.com/Supergiovane/node-red-contrib-unifi-ultimate/issues"
|
|
84
84
|
}
|
|
85
|
-
}
|
|
85
|
+
}
|