node-red-contrib-unifi-ultimate 0.1.2 → 0.1.5

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.
Files changed (30) hide show
  1. package/README.md +115 -139
  2. package/nodes/icons/unifi-access-icon.svg +8 -0
  3. package/nodes/icons/unifi-network-icon.svg +12 -0
  4. package/nodes/icons/unifi-protect-icon.svg +3 -3
  5. package/nodes/readme-assets/unifi-access-door-access.jpg +0 -0
  6. package/nodes/readme-assets/unifi-network-switching.jpg +0 -0
  7. package/nodes/readme-assets/unifi-protect-camera.png +0 -0
  8. package/nodes/unifi-access-config.html +68 -9
  9. package/nodes/unifi-access-config.js +359 -25
  10. package/nodes/unifi-access-device.html +239 -41
  11. package/nodes/unifi-access-device.js +71 -47
  12. package/nodes/unifi-network-config.html +71 -11
  13. package/nodes/unifi-network-config.js +1173 -4
  14. package/nodes/unifi-network-control-poe.html +555 -48
  15. package/nodes/unifi-network-control-poe.js +258 -83
  16. package/nodes/unifi-network-device.html +303 -53
  17. package/nodes/unifi-network-device.js +21 -51
  18. package/nodes/unifi-network-presence.html +297 -38
  19. package/nodes/unifi-network-presence.js +11 -26
  20. package/nodes/unifi-protect-config.html +68 -9
  21. package/nodes/unifi-protect-device.html +237 -40
  22. package/nodes/unifi-protect-device.js +19 -25
  23. package/nodes/utils/unifi-access-device-registry.js +9 -17
  24. package/nodes/utils/unifi-network-device-registry.js +106 -27
  25. package/nodes/utils/unifi-protect-device-registry.js +15 -21
  26. package/package.json +15 -2
  27. package/scripts/discover-unifi-access-registry.js +24 -0
  28. package/scripts/discover-unifi-network-registry.js +26 -0
  29. package/scripts/discover-unifi-protect-registry.js +26 -0
  30. package/scripts/unifi-registry-discovery-common.js +1043 -0
@@ -21,6 +21,45 @@ module.exports = function(RED) {
21
21
  // Doorbell requests are "best effort" from the public API perspective, so
22
22
  // keep a short-lived in-memory ledger to validate later cancel requests.
23
23
  const ACTIVE_DOORBELL_TTL_MS = 180000;
24
+ const DOORBELL_EVENT_INCOMING_PREFIX = "access.doorbell.incoming";
25
+ const DOORBELL_EVENT_COMPLETED_PREFIX = "access.doorbell.completed";
26
+ const DOORBELL_EVENT_REMOTE_VIEW = "access.remote_view";
27
+ const DOORBELL_EVENT_REMOTE_VIEW_CHANGE = "access.remote_view.change";
28
+ const DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST = "access.remotecall.request";
29
+ const DOORBELL_LOG_EVENT_DOOR_UNLOCK = "access.door.unlock";
30
+ const DOORBELL_LOG_POLL_INTERVAL_MS = 10000;
31
+ const DOORBELL_LOG_POLL_LOOKBACK_SECONDS = 45;
32
+ const DOORBELL_LOG_ACTIVE_WINDOW_MS = 25000;
33
+
34
+ function normalizeEventName(value) {
35
+ return String(value || "").trim().toLowerCase();
36
+ }
37
+
38
+ function normalizeString(value) {
39
+ return String(value || "").trim();
40
+ }
41
+
42
+ function isDoorbellIncomingEvent(eventName) {
43
+ return eventName.startsWith(DOORBELL_EVENT_INCOMING_PREFIX) || eventName === DOORBELL_EVENT_REMOTE_VIEW;
44
+ }
45
+
46
+ function isDoorbellCompletedEvent(eventName) {
47
+ return eventName.startsWith(DOORBELL_EVENT_COMPLETED_PREFIX) || eventName === DOORBELL_EVENT_REMOTE_VIEW_CHANGE;
48
+ }
49
+
50
+ function firstNonEmptyString(values) {
51
+ for (const value of values) {
52
+ const normalized = normalizeString(value);
53
+ if (normalized) {
54
+ return normalized;
55
+ }
56
+ }
57
+ return "";
58
+ }
59
+
60
+ function isLikelyDoorbellDeviceId(value) {
61
+ return /^[0-9a-f]{12}$/i.test(String(value || "").trim());
62
+ }
24
63
 
25
64
  function UnifiAccessConfigNode(config) {
26
65
  RED.nodes.createNode(this, config);
@@ -35,6 +74,11 @@ module.exports = function(RED) {
35
74
  node.reconnectTimer = null;
36
75
  node.isClosing = false;
37
76
  node.activeDoorbells = new Map();
77
+ node.activeDoorbellRequests = new Map();
78
+ node.doorbellLogPollTimer = null;
79
+ node.doorbellLogPollInFlight = false;
80
+ node.doorbellLogPollCursor = 0;
81
+ node.seenDoorbellLogIds = new Set();
38
82
 
39
83
  node.getApiToken = () => node.credentials && node.credentials.apiToken;
40
84
 
@@ -163,24 +207,116 @@ module.exports = function(RED) {
163
207
  });
164
208
  };
165
209
 
210
+ node.setActiveDoorbell = (deviceId, entry) => {
211
+ const normalizedId = normalizeString(deviceId);
212
+ if (!normalizedId) {
213
+ return;
214
+ }
215
+
216
+ const previous = node.activeDoorbells.get(normalizedId);
217
+ if (previous && normalizeString(previous.requestId)) {
218
+ node.activeDoorbellRequests.delete(normalizeString(previous.requestId));
219
+ }
220
+
221
+ const normalizedEntry = entry && typeof entry === "object" ? { ...entry } : {};
222
+ normalizedEntry.requestId = normalizeString(normalizedEntry.requestId);
223
+ node.activeDoorbells.set(normalizedId, normalizedEntry);
224
+
225
+ if (normalizedEntry.requestId) {
226
+ node.activeDoorbellRequests.set(normalizedEntry.requestId, normalizedId);
227
+ }
228
+ };
229
+
230
+ node.clearActiveDoorbell = (deviceId, expectedRequestIds) => {
231
+ const normalizedId = normalizeString(deviceId);
232
+ if (!normalizedId) {
233
+ return false;
234
+ }
235
+
236
+ const current = node.activeDoorbells.get(normalizedId);
237
+ if (!current) {
238
+ return false;
239
+ }
240
+
241
+ const requestId = normalizeString(current.requestId);
242
+ const expectedIds = Array.isArray(expectedRequestIds)
243
+ ? expectedRequestIds.map((value) => normalizeString(value)).filter(Boolean)
244
+ : [];
245
+
246
+ // Ignore stale completion events that target an older request id.
247
+ if (expectedIds.length > 0 && requestId && !expectedIds.includes(requestId)) {
248
+ return false;
249
+ }
250
+
251
+ node.activeDoorbells.delete(normalizedId);
252
+ if (requestId && node.activeDoorbellRequests.get(requestId) === normalizedId) {
253
+ node.activeDoorbellRequests.delete(requestId);
254
+ }
255
+ return true;
256
+ };
257
+
166
258
  node.updateDoorbellState = (payload) => {
167
259
  // Track doorbell lifecycle so "Cancel Doorbell" can avoid sending a
168
260
  // blind cancel when no active ring is currently known.
169
- const eventName = String(payload && payload.event || "").trim();
170
- const data = payload && payload.data && typeof payload.data === "object" ? payload.data : {};
261
+ const event = payload && typeof payload === "object" ? payload : {};
262
+ const eventName = normalizeEventName(event.event);
263
+ if (!isDoorbellIncomingEvent(eventName) && !isDoorbellCompletedEvent(eventName)) {
264
+ return;
265
+ }
266
+
267
+ const data = event.data && typeof event.data === "object" ? event.data : {};
171
268
  const device = data.device && typeof data.device === "object" ? data.device : {};
172
- const deviceId = String(device.id || "").trim();
173
- const objectData = payload && payload.object && typeof payload.object === "object" ? payload.object : {};
269
+ const objectData = event.object && typeof event.object === "object" ? event.object : {};
174
270
  const nestedObjectData = data.object && typeof data.object === "object" ? data.object : {};
175
- const requestId = String(objectData.request_id || nestedObjectData.request_id || "").trim();
176
271
 
177
- if (!deviceId) {
178
- return;
179
- }
272
+ const requestId = firstNonEmptyString([
273
+ data.request_id,
274
+ data.remote_call_request_id,
275
+ objectData.request_id,
276
+ nestedObjectData.request_id
277
+ ]);
278
+ const clearRequestId = firstNonEmptyString([
279
+ data.clear_request_id,
280
+ objectData.clear_request_id,
281
+ nestedObjectData.clear_request_id
282
+ ]);
283
+ let deviceId = firstNonEmptyString([
284
+ device.id,
285
+ data.device_id,
286
+ data.uah_id,
287
+ data.uah_device_id,
288
+ objectData.device_id,
289
+ nestedObjectData.device_id,
290
+ data.connected_uah_id
291
+ ]);
292
+
293
+ if (!deviceId && requestId) {
294
+ deviceId = normalizeString(node.activeDoorbellRequests.get(requestId));
295
+ }
296
+ if (!deviceId && clearRequestId) {
297
+ deviceId = normalizeString(node.activeDoorbellRequests.get(clearRequestId));
298
+ }
299
+
300
+ if (isDoorbellIncomingEvent(eventName)) {
301
+ if (clearRequestId) {
302
+ const previousDeviceId = normalizeString(node.activeDoorbellRequests.get(clearRequestId));
303
+ if (previousDeviceId) {
304
+ node.clearActiveDoorbell(previousDeviceId, [clearRequestId]);
305
+ }
306
+ }
307
+
308
+ // Use the requestId as fallback storage key when the event does not
309
+ // carry a recognisable device id (e.g. physical button presses or
310
+ // triggers from external systems). hasAnyActiveDoorbell() will still
311
+ // return true so the cancel guard can allow the request through.
312
+ const storageKey = deviceId || requestId;
313
+ if (!storageKey) {
314
+ return;
315
+ }
180
316
 
181
- if (eventName.startsWith("access.doorbell.incoming")) {
182
- node.activeDoorbells.set(deviceId, {
317
+ node.setActiveDoorbell(storageKey, {
183
318
  requestId,
319
+ deviceId,
184
320
  updatedAt: Date.now(),
185
321
  expiresAt: Date.now() + ACTIVE_DOORBELL_TTL_MS,
186
322
  source: "event",
@@ -189,18 +325,203 @@ module.exports = function(RED) {
189
325
  return;
190
326
  }
191
327
 
192
- if (eventName.startsWith("access.doorbell.completed")) {
193
- // If a request id is present, use it to avoid deleting a newer
194
- // active ring with an old completion event.
195
- const current = node.activeDoorbells.get(deviceId);
196
- if (!current) {
197
- return;
328
+ if (!deviceId) {
329
+ if (requestId) {
330
+ const mappedDeviceId = normalizeString(node.activeDoorbellRequests.get(requestId));
331
+ if (mappedDeviceId) {
332
+ node.clearActiveDoorbell(mappedDeviceId, [requestId]);
333
+ }
334
+ }
335
+ if (clearRequestId) {
336
+ const mappedDeviceId = normalizeString(node.activeDoorbellRequests.get(clearRequestId));
337
+ if (mappedDeviceId) {
338
+ node.clearActiveDoorbell(mappedDeviceId, [clearRequestId]);
339
+ }
198
340
  }
341
+ return;
342
+ }
199
343
 
200
- if (!requestId || !current.requestId || current.requestId === requestId) {
201
- node.activeDoorbells.delete(deviceId);
344
+ node.clearActiveDoorbell(deviceId, [requestId, clearRequestId].filter(Boolean));
345
+ };
346
+
347
+ node.extractDoorbellDeviceIdFromLogEntry = (entry) => {
348
+ const source = entry && entry._source && typeof entry._source === "object" ? entry._source : {};
349
+ const targets = Array.isArray(source.target) ? source.target : [];
350
+
351
+ // Prefer direct intercom targets.
352
+ for (const target of targets) {
353
+ const targetType = normalizeString(target && target.type).toLowerCase();
354
+ const targetId = normalizeString(target && target.id);
355
+ if (!isLikelyDoorbellDeviceId(targetId)) {
356
+ continue;
357
+ }
358
+ if (targetType.includes("intercom") && !targetType.includes("viewer")) {
359
+ return targetId;
202
360
  }
203
361
  }
362
+
363
+ // Fallback: parse the device id from activity resource ids such as
364
+ // "protect_<deviceId>_<uuid>".
365
+ for (const target of targets) {
366
+ const targetType = normalizeString(target && target.type).toLowerCase();
367
+ const targetId = normalizeString(target && target.id);
368
+ if (!targetType.includes("resource") || !targetId) {
369
+ continue;
370
+ }
371
+
372
+ const match = targetId.match(/(?:^|_)([0-9a-f]{12})(?:_|$)/i);
373
+ if (match && isLikelyDoorbellDeviceId(match[1])) {
374
+ return normalizeString(match[1]);
375
+ }
376
+ }
377
+
378
+ return "";
379
+ };
380
+
381
+ node.processDoorbellLogEntry = (entry) => {
382
+ const source = entry && entry._source && typeof entry._source === "object" ? entry._source : {};
383
+ const event = source.event && typeof source.event === "object" ? source.event : {};
384
+ const eventType = normalizeEventName(event.type);
385
+ const logKey = normalizeEventName(event.log_key);
386
+ const deviceId = node.extractDoorbellDeviceIdFromLogEntry(entry);
387
+
388
+ // Doorbell request log means a ring has just started.
389
+ if (eventType === DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST) {
390
+ if (!deviceId) {
391
+ return false;
392
+ }
393
+
394
+ const published = Number(event.published);
395
+ const publishedMs = Number.isFinite(published) && published > 0 ? published : Date.now();
396
+ const expiresAt = Math.min(
397
+ publishedMs + DOORBELL_LOG_ACTIVE_WINDOW_MS,
398
+ Date.now() + DOORBELL_LOG_ACTIVE_WINDOW_MS
399
+ );
400
+ if (expiresAt <= Date.now()) {
401
+ return false;
402
+ }
403
+
404
+ node.setActiveDoorbell(deviceId, {
405
+ requestId: "",
406
+ updatedAt: publishedMs,
407
+ expiresAt,
408
+ source: "logs",
409
+ payload: entry
410
+ });
411
+ return true;
412
+ }
413
+
414
+ // Access writes call-end outcomes as access.door.unlock with a
415
+ // doorbell-specific log key (for example "missed"). Treat those as
416
+ // completion signals and clear the tracked ring.
417
+ if (eventType === DOORBELL_LOG_EVENT_DOOR_UNLOCK && logKey.includes("access.doorbell.")) {
418
+ if (!deviceId) {
419
+ return false;
420
+ }
421
+ node.clearActiveDoorbell(deviceId);
422
+ return true;
423
+ }
424
+
425
+ return false;
426
+ };
427
+
428
+ node.pollDoorbellLogs = async ({ since, until }) => {
429
+ if (!node.baseUrl || !node.getApiToken() || !since || !until || until <= since) {
430
+ return 0;
431
+ }
432
+
433
+ const response = await node.apiRequest({
434
+ path: "/api/v1/developer/system/logs",
435
+ method: "POST",
436
+ query: {
437
+ page_size: 200,
438
+ page_num: 1
439
+ },
440
+ payload: {
441
+ topic: "all",
442
+ since,
443
+ until
444
+ },
445
+ timeout: 10000
446
+ });
447
+
448
+ if (response.statusCode < 200 || response.statusCode >= 300) {
449
+ return 0;
450
+ }
451
+
452
+ const logPayload = extractAccessData(response.payload);
453
+ const hits = Array.isArray(logPayload && logPayload.hits) ? logPayload.hits : [];
454
+ let matchedEvents = 0;
455
+
456
+ for (const entry of hits) {
457
+ const logId = normalizeString(entry && entry._id);
458
+ if (logId) {
459
+ if (node.seenDoorbellLogIds.has(logId)) {
460
+ continue;
461
+ }
462
+ node.seenDoorbellLogIds.add(logId);
463
+ }
464
+
465
+ if (node.processDoorbellLogEntry(entry)) {
466
+ matchedEvents += 1;
467
+ }
468
+ }
469
+
470
+ if (node.seenDoorbellLogIds.size > 2000) {
471
+ node.seenDoorbellLogIds.clear();
472
+ }
473
+
474
+ return matchedEvents;
475
+ };
476
+
477
+ node.refreshDoorbellState = async (options) => {
478
+ const lookbackSeconds = Number(options && options.lookbackSeconds) > 0
479
+ ? Math.floor(Number(options.lookbackSeconds))
480
+ : DOORBELL_LOG_POLL_LOOKBACK_SECONDS;
481
+ const until = Math.floor(Date.now() / 1000);
482
+ const since = Math.max(0, until - lookbackSeconds);
483
+ return node.pollDoorbellLogs({ since, until });
484
+ };
485
+
486
+ node.runDoorbellLogPoll = async () => {
487
+ if (node.doorbellLogPollInFlight) {
488
+ return;
489
+ }
490
+ node.doorbellLogPollInFlight = true;
491
+
492
+ try {
493
+ const until = Math.floor(Date.now() / 1000);
494
+ const baseCursor = Number(node.doorbellLogPollCursor) > 0
495
+ ? Number(node.doorbellLogPollCursor)
496
+ : until - DOORBELL_LOG_POLL_LOOKBACK_SECONDS;
497
+ const since = Math.max(0, baseCursor - 2);
498
+ await node.pollDoorbellLogs({ since, until });
499
+ node.doorbellLogPollCursor = until;
500
+ } catch (error) {
501
+ node.warn(`Access doorbell log polling failed: ${error && error.message ? error.message : error}`);
502
+ } finally {
503
+ node.doorbellLogPollInFlight = false;
504
+ }
505
+ };
506
+
507
+ node.ensureDoorbellLogPolling = () => {
508
+ if (node.isClosing || node.nodeClients.length === 0 || node.doorbellLogPollTimer) {
509
+ return;
510
+ }
511
+
512
+ node.doorbellLogPollCursor = Math.floor(Date.now() / 1000) - DOORBELL_LOG_POLL_LOOKBACK_SECONDS;
513
+ node.runDoorbellLogPoll();
514
+ node.doorbellLogPollTimer = setInterval(() => {
515
+ node.runDoorbellLogPoll();
516
+ }, DOORBELL_LOG_POLL_INTERVAL_MS);
517
+ };
518
+
519
+ node.stopDoorbellLogPolling = () => {
520
+ if (node.doorbellLogPollTimer) {
521
+ clearInterval(node.doorbellLogPollTimer);
522
+ node.doorbellLogPollTimer = null;
523
+ }
524
+ node.doorbellLogPollInFlight = false;
204
525
  };
205
526
 
206
527
  node.purgeExpiredDoorbells = () => {
@@ -210,14 +531,14 @@ module.exports = function(RED) {
210
531
  Array.from(node.activeDoorbells.entries()).forEach(([deviceId, entry]) => {
211
532
  const expiresAt = Number(entry && entry.expiresAt);
212
533
  if (Number.isFinite(expiresAt) && expiresAt > 0 && expiresAt <= now) {
213
- node.activeDoorbells.delete(deviceId);
534
+ node.clearActiveDoorbell(deviceId);
214
535
  }
215
536
  });
216
537
  };
217
538
 
218
539
  node.getActiveDoorbell = (deviceId) => {
219
540
  node.purgeExpiredDoorbells();
220
- const normalizedId = String(deviceId || "").trim();
541
+ const normalizedId = normalizeString(deviceId);
221
542
  if (!normalizedId) {
222
543
  return null;
223
544
  }
@@ -225,6 +546,8 @@ module.exports = function(RED) {
225
546
  return node.activeDoorbells.get(normalizedId) || null;
226
547
  };
227
548
 
549
+ node.hasActiveDoorbell = (deviceId) => Boolean(node.getActiveDoorbell(deviceId));
550
+
228
551
  node.hasAnyActiveDoorbell = () => {
229
552
  node.purgeExpiredDoorbells();
230
553
  return node.activeDoorbells.size > 0;
@@ -233,13 +556,13 @@ module.exports = function(RED) {
233
556
  node.markDoorbellTriggered = (deviceId, metadata) => {
234
557
  // Manual trigger requests can arrive before the websocket confirms
235
558
  // the ring, so pre-mark them as active for safe cancel behavior.
236
- const normalizedId = String(deviceId || "").trim();
559
+ const normalizedId = normalizeString(deviceId);
237
560
  if (!normalizedId) {
238
561
  return;
239
562
  }
240
563
 
241
- node.activeDoorbells.set(normalizedId, {
242
- requestId: "",
564
+ node.setActiveDoorbell(normalizedId, {
565
+ requestId: metadata && typeof metadata === "object" ? metadata.requestId : "",
243
566
  updatedAt: Date.now(),
244
567
  expiresAt: Date.now() + ACTIVE_DOORBELL_TTL_MS,
245
568
  source: "request",
@@ -247,8 +570,15 @@ module.exports = function(RED) {
247
570
  });
248
571
  };
249
572
 
250
- node.markDoorbellCanceled = () => {
251
- node.activeDoorbells.clear();
573
+ node.markDoorbellCanceled = (deviceId) => {
574
+ const normalizedId = normalizeString(deviceId);
575
+ if (!normalizedId) {
576
+ node.activeDoorbells.clear();
577
+ node.activeDoorbellRequests.clear();
578
+ return;
579
+ }
580
+
581
+ node.clearActiveDoorbell(normalizedId);
252
582
  };
253
583
 
254
584
  node.scheduleReconnect = () => {
@@ -357,6 +687,7 @@ module.exports = function(RED) {
357
687
  node.nodeClients.push(client);
358
688
  try {
359
689
  node.ensureWebSocket();
690
+ node.ensureDoorbellLogPolling();
360
691
  } catch (error) {
361
692
  node.warn(`Unable to initialize Access websocket: ${error && error.message ? error.message : error}`);
362
693
  }
@@ -366,13 +697,16 @@ module.exports = function(RED) {
366
697
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
367
698
  if (node.nodeClients.length === 0) {
368
699
  node.closeWebSocket();
700
+ node.stopDoorbellLogPolling();
369
701
  }
370
702
  };
371
703
 
372
704
  node.on("close", function(done) {
373
705
  node.isClosing = true;
374
706
  node.activeDoorbells.clear();
707
+ node.activeDoorbellRequests.clear();
375
708
  node.closeWebSocket();
709
+ node.stopDoorbellLogPolling();
376
710
  if (typeof done === "function") {
377
711
  done();
378
712
  }