node-red-contrib-unifi-ultimate 1.1.13 → 1.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.
@@ -1,5 +1,10 @@
1
1
  "use strict";
2
2
 
3
+ const { registerConnectionCheck } = require("./utils/unifi-connection-check");
4
+ const { actionGuidance } = require("./utils/unifi-action-guidance");
5
+
6
+ const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
7
+
3
8
  const {
4
9
  buildBaseUrlFromHost,
5
10
  normalizePort,
@@ -19,6 +24,7 @@ const {
19
24
  } = require("./utils/unifi-access-device-registry");
20
25
 
21
26
  module.exports = function(RED) {
27
+ registerConnectionCheck(RED, "access");
22
28
  // Doorbell requests are "best effort" from the public API perspective, so
23
29
  // keep a short-lived in-memory ledger to validate later cancel requests.
24
30
  const ACTIVE_DOORBELL_TTL_MS = 180000;
@@ -79,6 +85,7 @@ module.exports = function(RED) {
79
85
  node.isClosing = false;
80
86
  node.activeDoorbells = new Map();
81
87
  node.activeDoorbellRequests = new Map();
88
+ node.doorbellStateUpdatedAt = new Map();
82
89
  node.doorbellLogPollTimer = null;
83
90
  node.doorbellLogPollInFlight = false;
84
91
  node.doorbellLogPollCursor = 0;
@@ -194,12 +201,13 @@ module.exports = function(RED) {
194
201
  ? await node.fetchDeviceByTypeAndId(deviceType, deviceId)
195
202
  : null;
196
203
 
197
- return getCapabilityOptions(deviceType, capabilityId, {
204
+ const result = await getCapabilityOptions(deviceType, capabilityId, {
198
205
  deviceId,
199
206
  device: selectedDevice,
200
207
  capabilityConfig,
201
208
  fetchDevices: node.fetchDevices
202
209
  });
210
+ return { ...result, requirements: actionGuidance("access", capabilityId, capabilityConfig, selectedDevice, node.credentials) };
203
211
  };
204
212
 
205
213
  node.fetchCapabilities = async (deviceType, deviceId) => {
@@ -243,25 +251,23 @@ module.exports = function(RED) {
243
251
 
244
252
  const normalizedEntry = entry && typeof entry === "object" ? { ...entry } : {};
245
253
  normalizedEntry.requestId = normalizeString(normalizedEntry.requestId);
254
+ normalizedEntry.updatedAt = Number(normalizedEntry.updatedAt) || Date.now();
246
255
  node.activeDoorbells.set(normalizedId, normalizedEntry);
256
+ node.doorbellStateUpdatedAt.set(normalizedId, normalizedEntry.updatedAt);
247
257
 
248
258
  if (normalizedEntry.requestId) {
249
259
  node.activeDoorbellRequests.set(normalizedEntry.requestId, normalizedId);
250
260
  }
251
261
  };
252
262
 
253
- node.clearActiveDoorbell = (deviceId, expectedRequestIds) => {
263
+ node.clearActiveDoorbell = (deviceId, expectedRequestIds, updatedAt = Date.now()) => {
254
264
  const normalizedId = normalizeString(deviceId);
255
265
  if (!normalizedId) {
256
266
  return false;
257
267
  }
258
268
 
259
269
  const current = node.activeDoorbells.get(normalizedId);
260
- if (!current) {
261
- return false;
262
- }
263
-
264
- const requestId = normalizeString(current.requestId);
270
+ const requestId = normalizeString(current && current.requestId);
265
271
  const expectedIds = Array.isArray(expectedRequestIds)
266
272
  ? expectedRequestIds.map((value) => normalizeString(value)).filter(Boolean)
267
273
  : [];
@@ -271,6 +277,16 @@ module.exports = function(RED) {
271
277
  return false;
272
278
  }
273
279
 
280
+ // Remember completions even without an active entry: a delayed
281
+ // incoming log must not re-enable cancel for a call that has ended.
282
+ node.doorbellStateUpdatedAt.set(normalizedId, Math.max(
283
+ node.doorbellStateUpdatedAt.get(normalizedId) || 0,
284
+ updatedAt
285
+ ));
286
+ if (!current) {
287
+ return false;
288
+ }
289
+
274
290
  node.activeDoorbells.delete(normalizedId);
275
291
  if (requestId && node.activeDoorbellRequests.get(requestId) === normalizedId) {
276
292
  node.activeDoorbellRequests.delete(requestId);
@@ -407,15 +423,31 @@ module.exports = function(RED) {
407
423
  const eventType = normalizeEventName(event.type);
408
424
  const logKey = normalizeEventName(event.log_key);
409
425
  const deviceId = node.extractDoorbellDeviceIdFromLogEntry(entry);
426
+ const isIncoming = eventType === DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST;
427
+ const isCompleted = eventType === DOORBELL_LOG_EVENT_DOOR_UNLOCK && logKey.includes("access.doorbell.");
428
+ const publishedMs = Number(event.published);
429
+
430
+ // Logs are historical evidence. Without a timestamp they cannot
431
+ // safely establish that a ring is still active.
432
+ if ((!isIncoming && !isCompleted) || !deviceId || !Number.isFinite(publishedMs) || publishedMs <= 0) {
433
+ return false;
434
+ }
435
+
436
+ const current = node.getActiveDoorbell(deviceId);
437
+ const lastUpdatedAt = node.doorbellStateUpdatedAt.get(deviceId) || 0;
438
+ if (publishedMs < lastUpdatedAt || (isIncoming && publishedMs === lastUpdatedAt)) {
439
+ return false;
440
+ }
410
441
 
411
442
  // Doorbell request log means a ring has just started.
412
- if (eventType === DOORBELL_LOG_EVENT_REMOTE_CALL_REQUEST) {
413
- if (!deviceId) {
443
+ if (isIncoming) {
444
+ // Polling is a fallback, not a replacement for a live call.
445
+ // Overwriting it loses the websocket request id and reduces
446
+ // its lifetime from three minutes to the 25-second log window.
447
+ if (current && current.source !== "logs") {
414
448
  return false;
415
449
  }
416
450
 
417
- const published = Number(event.published);
418
- const publishedMs = Number.isFinite(published) && published > 0 ? published : Date.now();
419
451
  const expiresAt = Math.min(
420
452
  publishedMs + DOORBELL_LOG_ACTIVE_WINDOW_MS,
421
453
  Date.now() + DOORBELL_LOG_ACTIVE_WINDOW_MS
@@ -437,11 +469,8 @@ module.exports = function(RED) {
437
469
  // Access writes call-end outcomes as access.door.unlock with a
438
470
  // doorbell-specific log key (for example "missed"). Treat those as
439
471
  // completion signals and clear the tracked ring.
440
- if (eventType === DOORBELL_LOG_EVENT_DOOR_UNLOCK && logKey.includes("access.doorbell.")) {
441
- if (!deviceId) {
442
- return false;
443
- }
444
- node.clearActiveDoorbell(deviceId);
472
+ if (isCompleted) {
473
+ node.clearActiveDoorbell(deviceId, [], publishedMs);
445
474
  return true;
446
475
  }
447
476
 
@@ -473,7 +502,13 @@ module.exports = function(RED) {
473
502
  }
474
503
 
475
504
  const logPayload = extractAccessData(response.payload);
476
- const hits = Array.isArray(logPayload && logPayload.hits) ? logPayload.hits : [];
505
+ // Access returns newest-first batches. Apply starts before their
506
+ // corresponding completions, independent of API response order.
507
+ const hits = Array.isArray(logPayload && logPayload.hits)
508
+ ? logPayload.hits.slice().sort((left, right) =>
509
+ (Number(left && left._source && left._source.event && left._source.event.published) || 0)
510
+ - (Number(right && right._source && right._source.event && right._source.event.published) || 0))
511
+ : [];
477
512
  let matchedEvents = 0;
478
513
 
479
514
  for (const entry of hits) {
@@ -558,7 +593,12 @@ module.exports = function(RED) {
558
593
  Array.from(node.activeDoorbells.entries()).forEach(([deviceId, entry]) => {
559
594
  const expiresAt = Number(entry && entry.expiresAt);
560
595
  if (Number.isFinite(expiresAt) && expiresAt > 0 && expiresAt <= now) {
561
- node.clearActiveDoorbell(deviceId);
596
+ node.clearActiveDoorbell(deviceId, [], expiresAt);
597
+ }
598
+ });
599
+ node.doorbellStateUpdatedAt.forEach((updatedAt, deviceId) => {
600
+ if (updatedAt + ACTIVE_DOORBELL_TTL_MS <= now) {
601
+ node.doorbellStateUpdatedAt.delete(deviceId);
562
602
  }
563
603
  });
564
604
  };
@@ -600,8 +640,7 @@ module.exports = function(RED) {
600
640
  node.markDoorbellCanceled = (deviceId) => {
601
641
  const normalizedId = normalizeString(deviceId);
602
642
  if (!normalizedId) {
603
- node.activeDoorbells.clear();
604
- node.activeDoorbellRequests.clear();
643
+ Array.from(node.activeDoorbells.keys()).forEach((id) => node.clearActiveDoorbell(id));
605
644
  return;
606
645
  }
607
646
 
@@ -706,6 +745,11 @@ module.exports = function(RED) {
706
745
  }
707
746
  };
708
747
 
748
+ installSimpleMonitorScheduler(node, ({ kind, target }) => {
749
+ if (kind !== "observeDoorOpenTooLong") throw new Error("Unsupported Access monitor.");
750
+ return node.fetchDeviceByTypeAndId("door", target);
751
+ });
752
+
709
753
  node.addClient = (client) => {
710
754
  if (!client) {
711
755
  return;
@@ -715,6 +759,7 @@ module.exports = function(RED) {
715
759
  // when the first client subscribes.
716
760
  node.nodeClients = node.nodeClients.filter((entry) => entry && entry.id !== client.id);
717
761
  node.nodeClients.push(client);
762
+ node.refreshSimpleMonitorScheduler();
718
763
  try {
719
764
  node.ensureWebSocket();
720
765
  node.ensureDoorbellLogPolling();
@@ -725,6 +770,7 @@ module.exports = function(RED) {
725
770
 
726
771
  node.removeClient = (client) => {
727
772
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
773
+ node.refreshSimpleMonitorScheduler();
728
774
  if (node.nodeClients.length === 0) {
729
775
  node.closeWebSocket();
730
776
  node.stopDoorbellLogPolling();
@@ -734,8 +780,10 @@ module.exports = function(RED) {
734
780
  node.on("close", function(done) {
735
781
  try {
736
782
  node.isClosing = true;
783
+ node.stopSimpleMonitorScheduler();
737
784
  node.activeDoorbells.clear();
738
785
  node.activeDoorbellRequests.clear();
786
+ node.doorbellStateUpdatedAt.clear();
739
787
  node.closeWebSocket();
740
788
  node.stopDoorbellLogPolling();
741
789
  } catch (error) {
@@ -749,7 +797,9 @@ module.exports = function(RED) {
749
797
 
750
798
  RED.nodes.registerType("unifi-access-config", UnifiAccessConfigNode, {
751
799
  credentials: {
752
- apiToken: { type: "password" }
800
+ apiToken: { type: "password" },
801
+ localUsername: { type: "text" },
802
+ localPassword: { type: "password" }
753
803
  }
754
804
  });
755
805
 
@@ -708,6 +708,10 @@
708
708
  function renderCapabilityOptions(data, options) {
709
709
  const renderOptions = options || {};
710
710
  const fields = data && Array.isArray(data.fields) ? data.fields : [];
711
+ const $requirements = $("#node-capability-requirements").empty();
712
+ const requirements = data && Array.isArray(data.requirements) ? data.requirements : [];
713
+ requirements.forEach(function (text) { $("<p></p>").text(text).appendTo($requirements); });
714
+ $requirements.toggle(requirements.length > 0);
711
715
  syncCapabilityConfigFromInputs();
712
716
  $capabilityConfigContainer.empty();
713
717
 
@@ -759,6 +763,8 @@
759
763
  });
760
764
  } else if (field.type === "checkbox") {
761
765
  $input = $("<input>").attr({ id: fieldId, type: "checkbox" });
766
+ } else if (field.type === "textarea") {
767
+ $input = $("<textarea></textarea>").attr({ id: fieldId, rows: 4, placeholder: field.placeholder || "" }).css("width", "calc(100% - 160px)");
762
768
  } else if (field.type === "hidden") {
763
769
  $input = $("<input>").attr({ id: fieldId, type: "hidden" });
764
770
  } else {
@@ -769,6 +775,11 @@
769
775
  }).css("width", "calc(100% - 160px)");
770
776
  }
771
777
 
778
+ if (field.type === "number") {
779
+ if (field.min !== undefined) $input.attr("min", field.min);
780
+ if (field.max !== undefined) $input.attr("max", field.max);
781
+ $input.attr("step", field.id === "hours" ? "any" : "1");
782
+ }
772
783
  const currentValue = Object.prototype.hasOwnProperty.call(capabilityConfig, field.id)
773
784
  ? capabilityConfig[field.id]
774
785
  : undefined;
@@ -809,15 +820,12 @@
809
820
  $wrapper.append($input);
810
821
  } else {
811
822
  $wrapper.append($label).append($input);
812
- }
813
-
814
- if (field.helpText) {
815
- $wrapper.append(
816
- $("<div></div>")
817
- .addClass("form-tips unifi-ultimate-info-tip")
818
- .css({ marginLeft: "0", width: "100%", boxSizing: "border-box" })
819
- .text(field.helpText)
820
- );
823
+ if (field.tip) {
824
+ const tipId = fieldId + "-tip";
825
+ $input.attr("aria-describedby", tipId);
826
+ $("<p></p>").attr({ id: tipId, class: "unifi-ultimate-tip" })
827
+ .css("margin-left", "152px").text(field.tip).appendTo($wrapper);
828
+ }
821
829
  }
822
830
 
823
831
  $capabilityConfigContainer.append($wrapper);
@@ -1118,6 +1126,7 @@
1118
1126
  <label for="node-input-capability"><i class="fa fa-tasks"></i> Action</label>
1119
1127
  <select id="node-input-capability"></select>
1120
1128
  </div>
1129
+ <div id="node-capability-requirements" role="status" style="display:none; margin-bottom:12px;"></div>
1121
1130
  <div class="form-row" id="node-row-capabilityConfig" style="display:none;">
1122
1131
  <label></label>
1123
1132
  <div id="node-input-capabilityConfigContainer" style="width:70%; display:inline-block;"></div>
@@ -1155,13 +1164,25 @@
1155
1164
  <p>For <code>Set Temporary Lock Rule</code>, choose <code>Custom Duration</code> to reveal the minutes field. Legacy <code>ended_time</code> is still available only as fallback compatibility.</p>
1156
1165
  <p><code>Receive Events</code> fetches the current state once and then subscribes to events provided by the shared UniFi Access config node. The config node maintains the official notifications WebSocket and fans out events to runtime nodes. In this mode, <code>All</code> emits every event for the selected device/door, while specific <code>Event</code> choices filter to official UniFi Access event families (for example doorbell, door unlock, DPS, emergency, schedule, and temporary unlock events). The input pin is hidden and listening starts automatically after deploy/restart.</p>
1157
1166
  <p><code>Trigger Doorbell</code> and <code>Cancel Doorbell</code> use a manual <code>Room Name</code> field when needed. The node does not currently discover Intercom directory names automatically.</p>
1158
- <p><code>Cancel Doorbell</code> uses a shared safe-cancel guard in the UniFi Access config node with a 3 minute tracking window. Tracking is updated by websocket events and a fallback system-log poller.</p>
1167
+ <p><code>Cancel Doorbell</code> only runs while the selected device has a tracked active ring. WebSocket events and <code>Trigger Doorbell</code> requests are tracked for up to 3 minutes, or until the call ends. A fallback system-log poller requires <code>view:system_log</code> permission and uses a shorter 25 second window when no live call is tracked; it does not shorten live tracking. Delayed logs cannot reactivate a completed call or clear a newer one.</p>
1159
1168
  <p>Visitors support state reads and the official visitor-status event. Access policies, schedules, holiday groups, and door groups are read-only. <code>Read Door Group Topology</code> returns the complete hierarchy documented by Access.</p>
1160
1169
  <p><code>Recent System Log</code> lists entries from the previous 24 hours, up to the first 200 results. It is read-only and requires the token's <code>view:system_log</code> permission.</p>
1161
1170
  <p><b>Emit periodically</b> repeats read-only actions at the selected interval and sends each result to the flow. It is hidden for <code>Receive Events</code> and write actions.</p>
1162
1171
  <p>Request timeout is handled automatically by the node.</p>
1163
1172
  <p><b>Name</b> is the node name shown in the editor and is updated only when you manually select a different item from the list.</p>
1164
1173
 
1174
+ <h3>Door Open Too Long</h3>
1175
+ <p>Select <b>Door → Door Open Too Long</b> and set <b>Open for (seconds)</b> (default: 120). Monitoring starts after deploy, with no Inject required. The door must have a working physical door position sensor (DPS), configured in Access; an unlocked door is not necessarily open. The API token needs <code>view:space</code> permission. The optional local account is not used.</p>
1176
+ <p>The connection checks the physical position every 5 seconds and shares reads between nodes watching the same door. One alert is emitted after the threshold, followed by one recovery when the door closes. A DPS closure event can report recovery immediately. The first observed opening starts the clock, including when a door is already open at startup. Alerts can arrive up to one polling interval after the threshold, plus request time.</p>
1177
+ <pre><code>// Door remained open for the configured duration
1178
+ msg.eventName = "doorOpenTooLong"
1179
+ msg.payload = { state: "openTooLong", open: true, at: "2026-09-12T12:00:00.000Z" }
1180
+ // Closure after the alert
1181
+ msg.eventName = "doorClosed"
1182
+ msg.payload = { state: "closed", open: false, at: "2026-09-12T12:01:00.000Z" }</code></pre>
1183
+ <p><code>msg.details.monitor</code> contains the configured delay, observed start time and duration. Missing sensor data or controller errors go to output 2 and reset a pending alert; they do not create an open-door alarm or a false closure. Repeated identical errors are suppressed until data returns. Monitoring starts afresh after redeploy/restart.</p>
1184
+ <p>The physical position and DPS notification format follow the <a href="https://assets.identity.ui.com/unifi-access/api_reference.pdf" target="_blank" rel="noopener noreferrer">UniFi Access API reference</a>.</p>
1185
+
1165
1186
  <h3>Input</h3>
1166
1187
  <ul>
1167
1188
  <li>When <code>Receive Events</code> is selected, the input pin is hidden.</li>
@@ -1186,7 +1207,7 @@
1186
1207
  </dl>
1187
1208
  <dl class="message-properties">
1188
1209
  <dt>Output 2 — error</dt>
1189
- <dd>Emitted when the action fails (API error, timeout, or configuration problem). The node status also turns red. Errors are additionally forwarded to any connected <code>catch</code> node.</dd>
1210
+ <dd>Emitted when the action fails (API error, timeout, or configuration problem). The node status indicates the problem. Use this output to handle errors; request failures are also forwarded to connected <code>catch</code> nodes.</dd>
1190
1211
  <dt class="optional">msg.payload</dt>
1191
1212
  <dd><code>null</code></dd>
1192
1213
  <dt class="optional">msg.topic</dt>
@@ -1,5 +1,7 @@
1
1
  "use strict";
2
2
 
3
+ const { boundedNumber, createSimpleMonitorProcessor } = require("./utils/unifi-simple-monitor");
4
+
3
5
  const {
4
6
  buildCapabilityRequest,
5
7
  composeCapabilityExecution,
@@ -104,6 +106,28 @@ module.exports = function(RED) {
104
106
  node.timeout = DEFAULT_REQUEST_TIMEOUT_MS;
105
107
  node.currentDevice = null;
106
108
  node.isObserving = false;
109
+ const isSimpleMonitor = () => node.capability === "observeDoorOpenTooLong";
110
+ const monitorOptions = parseCapabilityConfig(node.capabilityConfig);
111
+ const monitorProcessor = createSimpleMonitorProcessor({
112
+ kind: node.capability, options: monitorOptions, status: setNodeStatus,
113
+ reportError: (error) => node.send([null, buildErrorOutputMessage(error, node.name)]),
114
+ emit: (payload, eventName, details) => {
115
+ const output = { payload };
116
+ decorateOutputMessage(output, node.currentDevice, eventName);
117
+ attachDetails(output, { ...details, unifiAccess: buildBaseMetadata(node.deviceType, node.deviceId, node.capability, { source: details.monitor.source }) });
118
+ node.send(output);
119
+ }
120
+ });
121
+ node.getSimpleMonitorDescriptor = () => node.isObserving && isSimpleMonitor() && node.deviceId ? {
122
+ kind: node.capability, target: node.deviceId,
123
+ intervalMs: 5000
124
+ } : null;
125
+ node.handleSimpleMonitorUpdate = (update) => {
126
+ if (!node.isObserving || !isSimpleMonitor()) return;
127
+ if (update.latest && node.capability !== "observeInternet") node.currentDevice = update.latest;
128
+ monitorProcessor.handle(update);
129
+ };
130
+
107
131
 
108
132
  function setNodeStatus(status) {
109
133
  if (!status || typeof status !== "object" || Array.isArray(status)) {
@@ -166,6 +190,10 @@ module.exports = function(RED) {
166
190
  async function fetchDeviceState(deviceType, deviceId, capabilityId, send, source) {
167
191
  const payload = await node.server.fetchDeviceByTypeAndId(deviceType, deviceId);
168
192
  node.currentDevice = payload;
193
+ if (isSimpleMonitor()) {
194
+ node.handleSimpleMonitorUpdate({ latest: payload, source });
195
+ return;
196
+ }
169
197
 
170
198
  const stateMsg = {
171
199
  payload
@@ -372,6 +400,11 @@ module.exports = function(RED) {
372
400
  }
373
401
 
374
402
  node.isObserving = true;
403
+ if (isSimpleMonitor() && typeof node.server.refreshSimpleMonitorScheduler === "function") {
404
+ node.server.refreshSimpleMonitorScheduler();
405
+ node.server.pollSimpleMonitors().catch(() => {});
406
+ return;
407
+ }
375
408
 
376
409
  // Emit one initial snapshot so the flow starts with a known state
377
410
  // before websocket events arrive.
@@ -449,9 +482,26 @@ module.exports = function(RED) {
449
482
  try {
450
483
  // Event matching is delegated to the registry because Access
451
484
  // events differ across doors, hubs, intercoms and devices.
452
- if (!node.isObserving || !matchesEvent(node.deviceType, node.deviceId, node.currentDevice, eventPayload)) {
485
+ if (!node.isObserving) {
486
+ return;
487
+ }
488
+ if (isSimpleMonitor()) {
489
+ // Ignore relay/unlock notifications. Only the selected
490
+ // door's physical DPS event can cancel the pending timer.
491
+ if (eventPayload.event === "access.device.dps_status" && eventPayload.data
492
+ && eventPayload.data.location && eventPayload.data.location.id === node.deviceId) {
493
+ const state = eventPayload.data.object && eventPayload.data.object.status;
494
+ if (state === "close" || state === "closed") {
495
+ node.handleSimpleMonitorUpdate({ latest: { ...node.currentDevice, door_position_status: "close" }, source: "events" });
496
+ } else {
497
+ // Polling confirms opening; a new open after a missed
498
+ // close must not reuse a stale pending interval.
499
+ if (state !== "open") monitorProcessor.invalidate();
500
+ }
501
+ }
453
502
  return;
454
503
  }
504
+ if (!matchesEvent(node.deviceType, node.deviceId, node.currentDevice, eventPayload)) return;
455
505
  const capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
456
506
  const observable = resolveConfiguredObservable(capabilityConfig);
457
507
  if (!matchesObservable(eventPayload, observable)) {
@@ -2,6 +2,7 @@
2
2
  href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
3
3
 
4
4
 
5
+ <script type="text/javascript" src="resources/node-red-contrib-unifi-ultimate/editor/unifi-connection-check.js"></script>
5
6
  <script type="text/javascript">
6
7
  RED.nodes.registerType("unifi-network-config", {
7
8
  category: "config",
@@ -31,13 +32,16 @@
31
32
  }
32
33
  },
33
34
  credentials: {
34
- apiKey: { type: "password", required: true }
35
+ apiKey: { type: "password", required: true },
36
+ localUsername: { type: "text" },
37
+ localPassword: { type: "password" }
35
38
  },
36
39
  label: function () {
37
40
  return this.name || this.host || "Unifi Network Config";
38
41
  },
39
42
  oneditprepare: function () {
40
43
  const node = this;
44
+ UnifiUltimateConnectionCheck.bind(node, "network");
41
45
  const $hostInput = $("#node-config-input-host");
42
46
  const $port = $("#node-config-input-port");
43
47
  const $apiKey = $("#node-config-input-apiKey");
@@ -48,6 +52,7 @@
48
52
  const $securityRow = $allowSelfSigned.closest(".form-row");
49
53
  const $powerObservationRow = $powerObservationIntervalSeconds.closest(".form-row");
50
54
  const $advancedRow = $("#node-config-row-advanced");
55
+ const $localAccountRow = $("#node-config-row-localAccount");
51
56
 
52
57
  // The stored field is rejectUnauthorized, but the checkbox is shown as
53
58
  // its inverse ("Allow self-signed certificate") because UniFi
@@ -62,6 +67,7 @@
62
67
  $securityRow.toggle(hasHost);
63
68
  $powerObservationRow.toggle(hasHost);
64
69
  $advancedRow.toggle(hasHost);
70
+ $localAccountRow.toggle(hasHost);
65
71
  }
66
72
 
67
73
  try {
@@ -76,7 +82,9 @@
76
82
  syncProgressiveRows();
77
83
  });
78
84
  },
85
+ oneditcancel: function () { UnifiUltimateConnectionCheck.cleanup(this); },
79
86
  oneditsave: function () {
87
+ UnifiUltimateConnectionCheck.cleanup(this);
80
88
  // Persist the inverse of the "Allow self-signed certificate" checkbox.
81
89
  this.rejectUnauthorized = !$("#node-config-input-allowSelfSigned").prop("checked");
82
90
  }
@@ -105,6 +113,17 @@
105
113
  <label for="node-config-input-apiKey"><i class="fa fa-key"></i> API Key</label>
106
114
  <input type="password" id="node-config-input-apiKey" placeholder="Paste your UniFi Network API key">
107
115
  </div>
116
+ <div id="node-config-row-localAccount">
117
+ <div class="form-row">
118
+ <label for="node-config-input-localUsername"><i class="fa fa-user"></i> Local User</label>
119
+ <input type="text" id="node-config-input-localUsername" autocomplete="off" placeholder="Local UniFi OS username (optional)">
120
+ </div>
121
+ <div class="form-row">
122
+ <label for="node-config-input-localPassword"><i class="fa fa-lock"></i> Local Password</label>
123
+ <input type="password" id="node-config-input-localPassword" autocomplete="new-password" placeholder="Local UniFi OS password (optional)">
124
+ </div>
125
+ <p class="unifi-ultimate-tip">Used when Internet/WAN monitoring requires a local login.</p>
126
+ </div>
108
127
  <div class="form-row">
109
128
  <label for="node-config-input-allowSelfSigned"><i class="fa fa-lock"></i> Security</label>
110
129
  <input type="checkbox" id="node-config-input-allowSelfSigned" style="display:inline-block; width:auto; vertical-align:top;">
@@ -114,6 +133,10 @@
114
133
  <label for="node-config-input-powerObservationIntervalSeconds"><i class="fa fa-repeat"></i> Power Poll (s)</label>
115
134
  <input type="text" id="node-config-input-powerObservationIntervalSeconds" placeholder="15">
116
135
  </div>
136
+ <div class="form-row">
137
+ <button type="button" class="red-ui-button" id="node-config-test-connection"><i class="fa fa-check-circle"></i> Verify Connection</button>
138
+ <div id="node-config-test-results" role="status" aria-live="polite" style="margin-top:10px; white-space:normal;"></div>
139
+ </div>
117
140
  <div id="node-config-row-advanced" class="unifi-ultimate-advanced">
118
141
  <div class="form-row">
119
142
  <label for="node-config-input-name"><i class="fa fa-tag"></i> Name</label>
@@ -135,9 +158,16 @@
135
158
  <p><b>Power Poll (s)</b> is the global polling interval used by all <code>Control POE</code> nodes when action is <code>Emit Power Consumption</code>. It is optional and defaults to 15 seconds.</p>
136
159
  <p><b>Name</b> is the config node name shown in the editor.</p>
137
160
 
161
+ <h3>Optional local account</h3>
162
+ <p><b>Local User</b> and <b>Local Password</b> accept an account created locally on the UniFi OS console configured above. Enter both fields when using a feature that requires a user login, or leave both empty. These credentials are stored by Node-RED in its credential store, separately from ordinary flow properties, and are not included in output messages.</p>
163
+ <p>The required <b>API Key</b> authenticates the normal actions. <b>Monitor Internet and WAN</b> also reads local Network endpoints: when they reject the key, it uses the optional local UniFi OS account with read access to the selected site. This session is shared by monitors on the connection and renewed when necessary. The account does not replace the API key or change how other actions authenticate.</p>
164
+
165
+ <h3>Verify Connection</h3>
166
+ <p>Use <b>Verify Connection</b> to check the values currently entered, before saving. The test runs from the Node-RED host and reports reachability, API authentication and available read permissions. For Protect and Network, a complete optional local account is also checked. It does not modify devices or save credentials. A successful check does not guarantee every camera, door or site permission.</p>
167
+ <p>If you change the controller address while using a saved password, re-enter the credentials to test it. An undeployed configuration with a masked password also needs the password entered again. Errors explain whether to check the address, certificate, credentials or permissions.</p>
138
168
  <h3>Usage</h3>
139
169
  <p>This config node is used by Network Device, Network Presence, and Control POE nodes.</p>
140
170
  <p>All UniFi Network requests are executed by this config node. Runtime nodes subscribe through <code>addClient/removeClient</code> and receive updates/events from here.</p>
141
171
  <p>Event streams and observation timers are centralized here (shared scheduler per config node), so runtime nodes do not open their own websocket channels or polling timers.</p>
142
172
  <p>The node uses the official Network integration API where available and falls back automatically to local legacy endpoints when the official <code>/v1</code> routes are not exposed (for example on older local releases). For switch port/client mapping and PoE enable/disable, legacy endpoints are also used where needed.</p>
143
- </script>
173
+ </script>
@@ -1,5 +1,11 @@
1
1
  "use strict";
2
2
 
3
+ const { registerConnectionCheck } = require("./utils/unifi-connection-check");
4
+ const { actionGuidance } = require("./utils/unifi-action-guidance");
5
+
6
+ const { installNetworkMonitorReads } = require("./utils/unifi-network-monitor");
7
+ const { installSimpleMonitorScheduler } = require("./utils/unifi-simple-monitor");
8
+
3
9
  const fs = require("fs");
4
10
  const os = require("os");
5
11
  const path = require("path");
@@ -32,6 +38,7 @@ const {
32
38
  } = require("./utils/unifi-network-presence-utils");
33
39
 
34
40
  module.exports = function(RED) {
41
+ registerConnectionCheck(RED, "network");
35
42
  const MIN_POWER_OBSERVER_INTERVAL_SECONDS = 5;
36
43
  const DEFAULT_POWER_OBSERVER_INTERVAL_SECONDS = 15;
37
44
  const POWER_OBSERVER_SCHEDULER_TICK_MS = 1000;
@@ -812,7 +819,7 @@ module.exports = function(RED) {
812
819
  ? await node.fetchDeviceByTypeAndId(deviceType, deviceId)
813
820
  : null;
814
821
 
815
- return getCapabilityOptions(deviceType, capabilityId, {
822
+ const result = await getCapabilityOptions(deviceType, capabilityId, {
816
823
  deviceId,
817
824
  device: selectedDevice,
818
825
  capabilityConfig,
@@ -820,6 +827,7 @@ module.exports = function(RED) {
820
827
  fetchDevice: node.fetchDeviceByTypeAndId,
821
828
  fetchDevicePorts: node.fetchDevicePorts
822
829
  });
830
+ return { ...result, requirements: actionGuidance("network", capabilityId, capabilityConfig, selectedDevice, node.credentials) };
823
831
  };
824
832
 
825
833
  node.fetchCapabilities = async (deviceType, deviceId) => {
@@ -3356,6 +3364,9 @@ module.exports = function(RED) {
3356
3364
  .filter((client) => client.mac);
3357
3365
  };
3358
3366
 
3367
+ installNetworkMonitorReads(node);
3368
+ installSimpleMonitorScheduler(node, (descriptor) => node.readSimpleMonitor(descriptor));
3369
+
3359
3370
  node.addClient = (client) => {
3360
3371
  if (!client) {
3361
3372
  return;
@@ -3364,6 +3375,7 @@ module.exports = function(RED) {
3364
3375
  // Store each consumer only once so config-node fan-out stays clean.
3365
3376
  node.nodeClients = node.nodeClients.filter((entry) => entry && entry.id !== client.id);
3366
3377
  node.nodeClients.push(client);
3378
+ node.refreshSimpleMonitorScheduler();
3367
3379
  try {
3368
3380
  node.ensureUnofficialNetworkWebSocket();
3369
3381
  } catch (error) {
@@ -3376,6 +3388,7 @@ module.exports = function(RED) {
3376
3388
 
3377
3389
  node.removeClient = (client) => {
3378
3390
  node.nodeClients = node.nodeClients.filter((entry) => entry && client && entry.id !== client.id);
3391
+ node.refreshSimpleMonitorScheduler();
3379
3392
  const clientId = normalizeString(client && client.id);
3380
3393
  if (clientId) {
3381
3394
  node.powerObserverNodeState.delete(clientId);
@@ -3404,6 +3417,8 @@ module.exports = function(RED) {
3404
3417
  node.on("close", function(done) {
3405
3418
  try {
3406
3419
  node.isClosing = true;
3420
+ node.stopSimpleMonitorScheduler();
3421
+ node.clearMonitorLocalSession();
3407
3422
  if (node.portOverrideCacheSaveTimer) {
3408
3423
  clearTimeout(node.portOverrideCacheSaveTimer);
3409
3424
  node.portOverrideCacheSaveTimer = null;
@@ -3427,7 +3442,9 @@ module.exports = function(RED) {
3427
3442
 
3428
3443
  RED.nodes.registerType("unifi-network-config", UnifiNetworkConfigNode, {
3429
3444
  credentials: {
3430
- apiKey: { type: "password" }
3445
+ apiKey: { type: "password" },
3446
+ localUsername: { type: "text" },
3447
+ localPassword: { type: "password" }
3431
3448
  }
3432
3449
  });
3433
3450