node-red-contrib-unifi-ultimate 1.1.15 → 1.1.17

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 CHANGED
@@ -202,6 +202,8 @@ Every node has **two outputs**:
202
202
 
203
203
  When an error occurs, the node status turns red and the error message comes out of the second output. Connect it to a **debug** node to see what happened, or wire it to any notification logic in your flow.
204
204
 
205
+ **Startup and missing readings** — Protect, Access and Network device nodes have an advanced **Emit startup states and undefined payloads** checkbox, disabled by default, including for existing flows. With it disabled, initial state snapshots and missing, null or `undefined` readings are suppressed. Valid `false` and `0` readings still pass through. Enable the checkbox to allow startup snapshots and missing payloads. Protect observables never replay an old value when a fresh reading is unavailable; LPR and event-photo actions continue to emit only actual readings or photos.
206
+
205
207
  **Repeat periodically** — for read actions, you can tick _Emit periodically_ in the node editor to have the node send the result automatically at a fixed interval, without needing an Inject node. The **Presence Detection** node offers a similar **Resend (s)** field: set it above `0` to re-emit the last known presence value on that cadence (even when unchanged). Resent messages carry `msg.eventName = "repeat"` so you can tell them apart from real state changes; leave it at `0` to disable.
206
208
 
207
209
  ## Example Flows
@@ -15,6 +15,7 @@
15
15
  inputs: { value: 1 },
16
16
  capability: { value: "observe", required: true },
17
17
  capabilityConfig: { value: "{}" },
18
+ emitStartupAndUndefined: { value: false },
18
19
  autoEmit: { value: false },
19
20
  autoEmitInterval: { value: 60, validate: RED.validators.number() }
20
21
  },
@@ -99,11 +100,13 @@
99
100
  const $capabilityRow = $capability.closest(".form-row");
100
101
  const $advancedRow = $("#node-row-advanced");
101
102
  let capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
103
+ let deviceListRequestId = 0;
102
104
  let capabilityListRequestId = 0;
103
105
  let capabilityOptionsRequestId = 0;
104
106
  let suspendChangeHandling = false;
105
107
  let isInitializingEditor = true;
106
108
  let restoredPersistedAutoEmit = false;
109
+ let preserveSavedDeviceSelection = true;
107
110
  let deviceTypeDefinitions = [];
108
111
  let capabilityDefinitions = [];
109
112
 
@@ -568,6 +571,17 @@
568
571
  $deviceName.val(selectedDeviceName);
569
572
  }
570
573
 
574
+ function clearDeviceSelection() {
575
+ preserveSavedDeviceSelection = false;
576
+ deviceListRequestId += 1;
577
+ capabilityListRequestId += 1;
578
+ capabilityOptionsRequestId += 1;
579
+ $deviceName.val("");
580
+ renderDevices([]);
581
+ renderCapabilities([]);
582
+ renderCapabilityOptions({ fields: [] }, { clearStoredConfig: false });
583
+ }
584
+
571
585
  function renderDeviceTypes(items) {
572
586
  deviceTypeDefinitions = Array.isArray(items) ? items.slice() : [];
573
587
  const currentValue = getCurrentOrNodeValue($deviceType, node.deviceType, "");
@@ -840,7 +854,8 @@
840
854
  }
841
855
 
842
856
  function renderDevices(items) {
843
- const currentValue = getCurrentOrNodeValue($deviceId, node.deviceId, "");
857
+ const savedDeviceId = preserveSavedDeviceSelection ? node.deviceId : "";
858
+ const currentValue = getCurrentOrNodeValue($deviceId, savedDeviceId, "");
844
859
  withSuppressedChanges(function () {
845
860
  $deviceId.empty();
846
861
  $deviceId.append($("<option></option>").val("").text("Choose a device"));
@@ -950,6 +965,7 @@
950
965
  }
951
966
 
952
967
  function loadDevices() {
968
+ const requestId = ++deviceListRequestId;
953
969
  const serverId = $server.val();
954
970
  const selectedType = getCurrentOrNodeValue($deviceType, node.deviceType, "");
955
971
  if (!serverId || serverId === "_ADD_" || !selectedType) {
@@ -962,14 +978,22 @@
962
978
  return requestJson(
963
979
  "unifiAccess/devices?serverId=" + encodeURIComponent(serverId) + "&deviceType=" + encodeURIComponent(selectedType)
964
980
  ).then(function (data) {
981
+ if (requestId !== deviceListRequestId) {
982
+ return;
983
+ }
965
984
  renderDevices(Array.isArray(data) ? data : []);
966
985
  }).catch(function (xhr) {
986
+ if (requestId !== deviceListRequestId) {
987
+ return;
988
+ }
967
989
  renderDevices([]);
968
990
  renderCapabilityOptions({ fields: [] }, { clearStoredConfig: false });
969
991
  const errorText = xhr && xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : "Unable to load devices";
970
992
  RED.notify(errorText, "error");
971
993
  }).finally(function () {
972
- $refresh.find("i").removeClass("fa-spin");
994
+ if (requestId === deviceListRequestId) {
995
+ $refresh.find("i").removeClass("fa-spin");
996
+ }
973
997
  });
974
998
  }
975
999
 
@@ -1049,12 +1073,16 @@
1049
1073
  if (suspendChangeHandling || isInitializingEditor) {
1050
1074
  return;
1051
1075
  }
1076
+ clearDeviceSelection();
1077
+ capabilityConfig = {};
1078
+ writeCapabilityConfig();
1052
1079
  refreshAfterServerChange();
1053
1080
  });
1054
1081
  $deviceType.on("change", function () {
1055
1082
  if (suspendChangeHandling || isInitializingEditor) {
1056
1083
  return;
1057
1084
  }
1085
+ clearDeviceSelection();
1058
1086
  capabilityConfig = {};
1059
1087
  writeCapabilityConfig();
1060
1088
  refreshAfterTypeChange();
@@ -1138,6 +1166,11 @@
1138
1166
  <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
1139
1167
  <input type="text" id="node-input-name" placeholder="Node name">
1140
1168
  </div>
1169
+ <div class="form-row">
1170
+ <label for="node-input-emitStartupAndUndefined"><i class="fa fa-sign-out"></i> Output</label>
1171
+ <input type="checkbox" id="node-input-emitStartupAndUndefined" style="display:inline-block; width:auto; vertical-align:top;">
1172
+ <label for="node-input-emitStartupAndUndefined" style="width:auto;">Emit startup states and undefined payloads</label>
1173
+ </div>
1141
1174
  <div class="form-row" id="node-row-autoEmit">
1142
1175
  <label for="node-input-autoEmit"><i class="fa fa-repeat"></i> Repeat</label>
1143
1176
  <input type="checkbox" id="node-input-autoEmit" style="display:inline-block; width:auto; vertical-align:top;">
@@ -1152,18 +1185,19 @@
1152
1185
  </script>
1153
1186
 
1154
1187
  <script type="text/html" data-help-name="unifi-access-device">
1188
+ <p><b>Emit startup states and undefined payloads</b> is disabled by default, including in existing flows. Enable it to emit the initial device state and readings with a missing, null or undefined payload. Otherwise these messages are suppressed; false and zero remain valid values. Missing readings never replay a previous value.</p>
1155
1189
  <p><a href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
1156
1190
 
1157
1191
  <p>Use this node to execute a configured UniFi Access action or listen for live Access events.</p>
1158
1192
 
1159
1193
  <h3>Configuration</h3>
1160
1194
  <p><b>Connection</b> selects the shared UniFi Access config node.</p>
1161
- <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved instead of being cleared.</p>
1195
+ <p><b>Control</b> chooses the Access category. <b>Device</b> chooses the specific door, device, visitor, policy, schedule, holiday group, door group, or recent system-log entry. Selectors are searchable and open with the complete list before filtering. A saved selection that is temporarily unavailable is preserved until <b>Connection</b> or <b>Control</b> changes.</p>
1162
1196
  <p><b>Action</b> only shows actions supported by the selected item.</p>
1163
1197
  <p>Additional fields appear only when the selected action needs extra input, such as a temporary lock rule or a room name for doorbell actions.</p>
1164
1198
  <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>
1165
1199
  <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>
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>
1200
+ <p><code>Trigger Doorbell</code> and <code>Cancel Doorbell</code> are shown only for Intercom and Reader Pro devices supported by the official Access API. They use a manual <code>Room Name</code> field when needed. The node does not currently discover Intercom directory names automatically.</p>
1167
1201
  <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>
1168
1202
  <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>
1169
1203
  <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>
@@ -21,7 +21,8 @@ const {
21
21
  extractDeviceNameFromPayload,
22
22
  attachDeviceNameToPayload,
23
23
  attachDetails,
24
- buildErrorOutputMessage
24
+ buildErrorOutputMessage,
25
+ sendWithPayload
25
26
  } = require("./utils/common-utils");
26
27
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
27
28
 
@@ -98,6 +99,7 @@ module.exports = function(RED) {
98
99
  node.deviceId = config.deviceId || "";
99
100
  node.capability = config.capability || "observe";
100
101
  node.capabilityConfig = config.capabilityConfig || "{}";
102
+ node.emitStartupAndUndefined = parseBoolean(config.emitStartupAndUndefined);
101
103
  node.autoEmit = parseBoolean(config.autoEmit);
102
104
  node.autoEmitIntervalSeconds = parseIntervalSeconds(config.autoEmitInterval, 60);
103
105
  node.autoEmitTimer = null;
@@ -115,7 +117,7 @@ module.exports = function(RED) {
115
117
  const output = { payload };
116
118
  decorateOutputMessage(output, node.currentDevice, eventName);
117
119
  attachDetails(output, { ...details, unifiAccess: buildBaseMetadata(node.deviceType, node.deviceId, node.capability, { source: details.monitor.source }) });
118
- node.send(output);
120
+ sendWithPayload(node.send.bind(node), output, node.emitStartupAndUndefined);
119
121
  }
120
122
  });
121
123
  node.getSimpleMonitorDescriptor = () => node.isObserving && isSimpleMonitor() && node.deviceId ? {
@@ -163,10 +165,10 @@ module.exports = function(RED) {
163
165
  // event messages are available, forward them in sequence.
164
166
  try {
165
167
  if (stateMsg) {
166
- send(stateMsg);
168
+ sendWithPayload(send, stateMsg, node.emitStartupAndUndefined);
167
169
  }
168
170
  if (eventMsg) {
169
- send(eventMsg);
171
+ sendWithPayload(send, eventMsg, node.emitStartupAndUndefined);
170
172
  }
171
173
  } catch (error) {
172
174
  node.warn(`Access output send failed: ${error && error.message ? error.message : error}`);
@@ -207,6 +209,7 @@ module.exports = function(RED) {
207
209
  });
208
210
 
209
211
  setNodeStatus({ fill: "green", shape: "dot", text: buildNodeStatus(deviceType, payload) });
212
+ if (source === "startup" && !node.emitStartupAndUndefined) return;
210
213
  sendOutputs(send, stateMsg, null);
211
214
  }
212
215
 
@@ -406,8 +409,7 @@ module.exports = function(RED) {
406
409
  return;
407
410
  }
408
411
 
409
- // Emit one initial snapshot so the flow starts with a known state
410
- // before websocket events arrive.
412
+ // Load the initial snapshot; output at startup is opt-in.
411
413
  fetchDeviceState(node.deviceType, node.deviceId, "observe", node.send.bind(node), "startup").catch(() => {
412
414
  });
413
415
  }
@@ -13,7 +13,8 @@ const {
13
13
  extractDeviceNameFromPayload,
14
14
  attachDeviceNameToPayload,
15
15
  attachDetails,
16
- buildErrorOutputMessage
16
+ buildErrorOutputMessage,
17
+ sendWithPayload
17
18
  } = require("./utils/common-utils");
18
19
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
19
20
 
@@ -864,7 +865,7 @@ module.exports = function(RED) {
864
865
  shape: "dot",
865
866
  text: `p${portIdx} ${formatPowerText(powerW)}W`
866
867
  });
867
- send(output);
868
+ sendWithPayload(send, output);
868
869
  }
869
870
 
870
871
  function handlePowerObservationEvent(send, action, event) {
@@ -919,7 +920,7 @@ module.exports = function(RED) {
919
920
  shape: "dot",
920
921
  text: `p${portIdx} ${formatPowerText(normalizedPowerW)}W`
921
922
  });
922
- send(output);
923
+ sendWithPayload(send, output);
923
924
  }
924
925
 
925
926
  function stopPowerObservation() {
@@ -1074,7 +1075,7 @@ module.exports = function(RED) {
1074
1075
  setNodeStatus({ fill: "yellow", shape: "dot", text: `${effectiveAction.payloadAction} ${okCount}/${results.length}` });
1075
1076
  }
1076
1077
 
1077
- send(output);
1078
+ sendWithPayload(send, output);
1078
1079
  }
1079
1080
 
1080
1081
  node.on("input", async function(msg, send, done) {
@@ -15,6 +15,7 @@
15
15
  inputs: { value: 1 },
16
16
  capability: { value: "observe", required: true },
17
17
  capabilityConfig: { value: "{}" },
18
+ emitStartupAndUndefined: { value: false },
18
19
  autoEmit: { value: false },
19
20
  autoEmitInterval: { value: 60, validate: RED.validators.number() }
20
21
  },
@@ -1279,6 +1280,11 @@
1279
1280
  <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
1280
1281
  <input type="text" id="node-input-name" placeholder="Node name">
1281
1282
  </div>
1283
+ <div class="form-row">
1284
+ <label for="node-input-emitStartupAndUndefined"><i class="fa fa-sign-out"></i> Output</label>
1285
+ <input type="checkbox" id="node-input-emitStartupAndUndefined" style="display:inline-block; width:auto; vertical-align:top;">
1286
+ <label for="node-input-emitStartupAndUndefined" style="width:auto;">Emit startup states and undefined payloads</label>
1287
+ </div>
1282
1288
  <div class="form-row" id="node-row-autoEmit">
1283
1289
  <label for="node-input-autoEmit"><i class="fa fa-repeat"></i> Repeat</label>
1284
1290
  <input type="checkbox" id="node-input-autoEmit" style="display:inline-block; width:auto; vertical-align:top;">
@@ -1293,6 +1299,7 @@
1293
1299
  </script>
1294
1300
 
1295
1301
  <script type="text/html" data-help-name="unifi-network-device">
1302
+ <p><b>Emit startup states and undefined payloads</b> is disabled by default, including in existing flows. Enable it to emit the initial device state and readings with a missing, null or undefined payload. Otherwise these messages are suppressed; false and zero remain valid values. Missing readings never replay a previous value.</p>
1296
1303
  <p><a href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
1297
1304
 
1298
1305
  <p>Use this node to execute a configured UniFi Network action on a selected site, UniFi device, or client.</p>
@@ -20,7 +20,8 @@ const {
20
20
  extractDeviceNameFromPayload,
21
21
  attachDeviceNameToPayload,
22
22
  attachDetails,
23
- buildErrorOutputMessage
23
+ buildErrorOutputMessage,
24
+ sendWithPayload
24
25
  } = require("./utils/common-utils");
25
26
  const UNOFFICIAL_NETWORK_STREAM_CAPABILITY = "observeUnofficialEvents";
26
27
  const UNOFFICIAL_POLL_INTERVAL_MS = 3000;
@@ -502,6 +503,7 @@ module.exports = function(RED) {
502
503
  node.deviceId = config.deviceId || "";
503
504
  node.capability = config.capability || "observe";
504
505
  node.capabilityConfig = config.capabilityConfig || "{}";
506
+ node.emitStartupAndUndefined = parseBoolean(config.emitStartupAndUndefined);
505
507
  node.autoEmit = parseBoolean(config.autoEmit);
506
508
  node.autoEmitIntervalSeconds = parseIntervalSeconds(config.autoEmitInterval, 60);
507
509
  node.autoEmitTimer = null;
@@ -519,7 +521,7 @@ module.exports = function(RED) {
519
521
  const output = { payload };
520
522
  decorateOutputMessage(output, node.currentDevice, eventName);
521
523
  attachDetails(output, { ...details, unifiNetwork: buildBaseMetadata(node.deviceType, node.deviceId, node.capability, { source: details.monitor.source }) });
522
- node.send(output);
524
+ sendWithPayload(node.send.bind(node), output, node.emitStartupAndUndefined);
523
525
  }
524
526
  });
525
527
  node.getSimpleMonitorDescriptor = () => node.isObserving && isSimpleMonitor() && node.deviceId ? {
@@ -616,7 +618,8 @@ module.exports = function(RED) {
616
618
  decorateOutputMessage(outputMsg, payload, source || "observe");
617
619
 
618
620
  setNodeStatus({ fill: "green", shape: "dot", text: buildNodeStatus(deviceType, payload) });
619
- send(outputMsg);
621
+ if (source === "startup" && !node.emitStartupAndUndefined) return;
622
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
620
623
  }
621
624
 
622
625
  async function fetchDeviceTemperatures(deviceType, deviceId, capabilityId, send) {
@@ -660,7 +663,7 @@ module.exports = function(RED) {
660
663
  ? `${statusTemperatureC} C`
661
664
  : "no temperature";
662
665
  setNodeStatus({ fill: temperatures.length > 0 ? "green" : "yellow", shape: "dot", text: statusText });
663
- send(outputMsg);
666
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
664
667
  }
665
668
 
666
669
  async function executeConfiguredCapabilityRequest(deviceType, deviceId, capabilityId, capabilityConfig) {
@@ -742,7 +745,7 @@ module.exports = function(RED) {
742
745
  decorateOutputMessage(outputMsg, outputMsg.payload, `request:${capabilityId}`);
743
746
 
744
747
  setNodeStatus({ fill: online ? "green" : "yellow", shape: "dot", text: online ? "online" : "offline" });
745
- send(outputMsg);
748
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
746
749
  }
747
750
 
748
751
  async function countOnlineClients(deviceType, deviceId, capabilityId, send) {
@@ -777,7 +780,7 @@ module.exports = function(RED) {
777
780
  decorateOutputMessage(outputMsg, outputMsg.payload, `request:${capabilityId}`);
778
781
 
779
782
  setNodeStatus({ fill: "green", shape: "dot", text: `${onlineClients.length} online` });
780
- send(outputMsg);
783
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
781
784
  }
782
785
 
783
786
  async function fetchDeviceSimpleStatistic(deviceType, deviceId, capabilityId, capabilityConfig, send) {
@@ -836,7 +839,7 @@ module.exports = function(RED) {
836
839
  ? `${metric.label} n/a`
837
840
  : `${metric.label} ${payloadValue}${metric.unit}`;
838
841
  setNodeStatus({ fill: payloadValue === null ? "yellow" : "green", shape: "dot", text: statusText });
839
- send(outputMsg);
842
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
840
843
  }
841
844
 
842
845
  async function createGuestVoucher(deviceType, deviceId, capabilityId, capabilityConfig, send) {
@@ -882,7 +885,7 @@ module.exports = function(RED) {
882
885
  decorateOutputMessage(outputMsg, outputMsg.payload, `request:${capabilityId}`);
883
886
 
884
887
  setNodeStatus({ fill: vouchers.length > 0 ? "green" : "yellow", shape: "dot", text: `${vouchers.length} voucher` });
885
- send(outputMsg);
888
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
886
889
  }
887
890
 
888
891
  async function invokeCapability(send, triggerSource) {
@@ -977,7 +980,7 @@ module.exports = function(RED) {
977
980
  decorateOutputMessage(outputMsg, responseData, `request:${capabilityId}`);
978
981
 
979
982
  setNodeStatus({ fill: "green", shape: "dot", text: `${capability.label}` });
980
- send(outputMsg);
983
+ sendWithPayload(send, outputMsg, node.emitStartupAndUndefined);
981
984
  }
982
985
 
983
986
  function resolveConfiguredCapabilityDefinition() {
@@ -1052,8 +1055,7 @@ module.exports = function(RED) {
1052
1055
  }
1053
1056
  const capabilityId = resolveCapabilityId(node.capability);
1054
1057
 
1055
- // Emit an initial snapshot at startup so the flow has a known state
1056
- // as soon as Node-RED starts.
1058
+ // Load the initial snapshot; output at startup is opt-in.
1057
1059
  fetchDeviceState(node.deviceType, node.deviceId, capabilityId, node.send.bind(node), "startup").catch(() => {
1058
1060
  });
1059
1061
  refreshUnofficialPollingFallback();
@@ -1163,7 +1165,7 @@ module.exports = function(RED) {
1163
1165
  })
1164
1166
  });
1165
1167
  decorateOutputMessage(output, output.payload, eventName);
1166
- node.send(output);
1168
+ sendWithPayload(node.send.bind(node), output, node.emitStartupAndUndefined);
1167
1169
  } catch (error) {
1168
1170
  }
1169
1171
  };
@@ -1241,7 +1243,7 @@ module.exports = function(RED) {
1241
1243
  })
1242
1244
  });
1243
1245
  decorateOutputMessage(output, output.payload, resolvedEventName);
1244
- node.send(output);
1246
+ sendWithPayload(node.send.bind(node), output, node.emitStartupAndUndefined);
1245
1247
  } catch (error) {
1246
1248
  }
1247
1249
  };
@@ -10,7 +10,8 @@ const {
10
10
  extractDeviceNameFromPayload,
11
11
  attachDetails,
12
12
  buildErrorOutputMessage,
13
- parseBoolean
13
+ parseBoolean,
14
+ sendWithPayload
14
15
  } = require("./utils/common-utils");
15
16
  const DEFAULT_REQUEST_TIMEOUT_MS = 8000;
16
17
 
@@ -105,7 +106,7 @@ function setupNetworkClientWatch(node, config) {
105
106
  };
106
107
  attachDetails(outputMsg, { client });
107
108
 
108
- node.send([outputMsg, null]);
109
+ sendWithPayload(node.send.bind(node), [outputMsg, null]);
109
110
  }
110
111
 
111
112
  function diffAndEmit(currentClients) {
@@ -389,7 +390,7 @@ module.exports = function(RED) {
389
390
  }
390
391
 
391
392
  try {
392
- node.send(outputMsg);
393
+ sendWithPayload(node.send.bind(node), outputMsg);
393
394
  } catch (error) {
394
395
  node.warn(`Presence output send failed: ${error && error.message ? error.message : error}`);
395
396
  }
@@ -7,7 +7,8 @@ const {
7
7
  appendStatusTimestamp,
8
8
  resolveNodeName,
9
9
  attachDetails,
10
- buildErrorOutputMessage
10
+ buildErrorOutputMessage,
11
+ sendWithPayload
11
12
  } = require("./utils/common-utils");
12
13
 
13
14
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
@@ -343,7 +344,7 @@ module.exports = function(RED) {
343
344
  setNodeStatus({ fill: "yellow", shape: "ring", text: `${succeeded}/${results.length} ok` });
344
345
  }
345
346
 
346
- send([output, null]);
347
+ sendWithPayload(send, [output, null]);
347
348
  }
348
349
 
349
350
  node.on("input", async function(msg, send, done) {
@@ -15,6 +15,7 @@
15
15
  inputs: { value: 1 },
16
16
  capability: { value: "observe", required: true },
17
17
  capabilityConfig: { value: "{}" },
18
+ emitStartupAndUndefined: { value: false },
18
19
  autoEmit: { value: false },
19
20
  autoEmitInterval: { value: 60, validate: RED.validators.number() }
20
21
  },
@@ -99,11 +100,13 @@
99
100
  const $capabilityRow = $capability.closest(".form-row");
100
101
  const $advancedRow = $("#node-row-advanced");
101
102
  let capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
103
+ let deviceListRequestId = 0;
102
104
  let capabilityListRequestId = 0;
103
105
  let capabilityOptionsRequestId = 0;
104
106
  let suspendChangeHandling = false;
105
107
  let isInitializingEditor = true;
106
108
  let restoredPersistedAutoEmit = false;
109
+ let preserveSavedDeviceSelection = true;
107
110
  let deviceTypeDefinitions = [];
108
111
  let capabilityDefinitions = [];
109
112
 
@@ -557,6 +560,17 @@
557
560
  $deviceName.val(selectedDeviceName);
558
561
  }
559
562
 
563
+ function clearDeviceSelection() {
564
+ preserveSavedDeviceSelection = false;
565
+ deviceListRequestId += 1;
566
+ capabilityListRequestId += 1;
567
+ capabilityOptionsRequestId += 1;
568
+ $deviceName.val("");
569
+ renderDevices([]);
570
+ renderCapabilities([]);
571
+ renderCapabilityOptions({ fields: [] }, { clearStoredConfig: false });
572
+ }
573
+
560
574
  function renderDeviceTypes(items) {
561
575
  deviceTypeDefinitions = Array.isArray(items) ? items.slice() : [];
562
576
  const currentValue = getCurrentOrNodeValue($deviceType, node.deviceType, "");
@@ -851,7 +865,8 @@
851
865
  }
852
866
 
853
867
  function renderDevices(items) {
854
- const currentValue = getCurrentOrNodeValue($deviceId, node.deviceId, "");
868
+ const savedDeviceId = preserveSavedDeviceSelection ? node.deviceId : "";
869
+ const currentValue = getCurrentOrNodeValue($deviceId, savedDeviceId, "");
855
870
  withSuppressedChanges(function () {
856
871
  $deviceId.empty();
857
872
  $deviceId.append($("<option></option>").val("").text("Choose a device"));
@@ -961,6 +976,7 @@
961
976
  }
962
977
 
963
978
  function loadDevices() {
979
+ const requestId = ++deviceListRequestId;
964
980
  const serverId = $server.val();
965
981
  const selectedType = getCurrentOrNodeValue($deviceType, node.deviceType, "");
966
982
  if (!serverId || serverId === "_ADD_" || !selectedType) {
@@ -973,14 +989,22 @@
973
989
  return requestJson(
974
990
  "unifiProtect/devices?serverId=" + encodeURIComponent(serverId) + "&deviceType=" + encodeURIComponent(selectedType)
975
991
  ).then(function (data) {
992
+ if (requestId !== deviceListRequestId) {
993
+ return;
994
+ }
976
995
  renderDevices(Array.isArray(data) ? data : []);
977
996
  }).catch(function (xhr) {
997
+ if (requestId !== deviceListRequestId) {
998
+ return;
999
+ }
978
1000
  renderDevices([]);
979
1001
  renderCapabilityOptions({ fields: [] }, { clearStoredConfig: false });
980
1002
  const errorText = xhr && xhr.responseJSON && xhr.responseJSON.error ? xhr.responseJSON.error : "Unable to load devices";
981
1003
  RED.notify(errorText, "error");
982
1004
  }).finally(function () {
983
- $refresh.find("i").removeClass("fa-spin");
1005
+ if (requestId === deviceListRequestId) {
1006
+ $refresh.find("i").removeClass("fa-spin");
1007
+ }
984
1008
  });
985
1009
  }
986
1010
 
@@ -1066,6 +1090,7 @@
1066
1090
  if (suspendChangeHandling || isInitializingEditor) {
1067
1091
  return;
1068
1092
  }
1093
+ clearDeviceSelection();
1069
1094
  capabilityConfig = {};
1070
1095
  writeCapabilityConfig();
1071
1096
  refreshAfterTypeChange();
@@ -1149,6 +1174,11 @@
1149
1174
  <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
1150
1175
  <input type="text" id="node-input-name" placeholder="Node name">
1151
1176
  </div>
1177
+ <div class="form-row">
1178
+ <label for="node-input-emitStartupAndUndefined"><i class="fa fa-sign-out"></i> Output</label>
1179
+ <input type="checkbox" id="node-input-emitStartupAndUndefined" style="display:inline-block; width:auto; vertical-align:top;">
1180
+ <label for="node-input-emitStartupAndUndefined" style="width:auto;">Emit startup states and undefined payloads</label>
1181
+ </div>
1152
1182
  <div class="form-row" id="node-row-autoEmit">
1153
1183
  <label for="node-input-autoEmit"><i class="fa fa-repeat"></i> Repeat</label>
1154
1184
  <input type="checkbox" id="node-input-autoEmit" style="display:inline-block; width:auto; vertical-align:top;">
@@ -1163,6 +1193,7 @@
1163
1193
  </script>
1164
1194
 
1165
1195
  <script type="text/html" data-help-name="unifi-protect-device">
1196
+ <p><b>Emit startup states and undefined payloads</b> is disabled by default, including in existing flows. Enable it to emit the initial device state and readings with a missing, null or undefined payload. Otherwise these messages are suppressed; false and zero remain valid values. Missing readings never replay a previous value.</p>
1166
1197
  <p><a href="https://youtube.com/playlist?list=PL9Yh1bjbLAYrWKtMlopN0swuQXbdJ8MFJ&si=4MmW1nNTCLrJtEHv" target="_blank" rel="noopener noreferrer"><img src="resources/node-red-contrib-unifi-ultimate/logos/youtube-icon.svg" alt="YouTube" width="24" height="18" style="vertical-align:text-bottom; margin-right:6px;">Youtube Tutorials</a></p>
1167
1198
 
1168
1199
  <p>Use this node to execute a configured UniFi Protect action or listen for live Protect events.</p>
@@ -1174,10 +1205,12 @@
1174
1205
  <p>Additional fields appear only when the selected action needs extra input. For example, events, PTZ presets, live views, or discovered properties.</p>
1175
1206
  <p>Action highlights: <code>Receive Events</code>, <code>Read Device State</code>, <code>Take Snapshot</code>, <code>Show Doorbell Message</code>, siren play/stop/test, relay output control, speaker sound test, and application/alarm actions on <code>NVR</code>.</p>
1176
1207
  <p>Protect resources include cameras, sensors, lights, chimes, viewers, live views, NVRs, bridges, Link Stations, alarm hubs, key fobs, relays, sirens, and speakers. The newer device families expose read state and events without the generic raw-update action.</p>
1177
- <p><code>Play Siren</code> uses a duration in seconds. <code>Control Relay Output</code> requires an explicit output and on/off state; auto-off applies only when turning an output on. Sound-test actions use a configured volume and never read control values from the incoming message.</p>
1208
+ <p><code>Play Siren</code> uses a duration in seconds. <code>Control Relay Output</code> requires an explicit output and on/off state; auto-off applies only when turning an output on. <code>Trigger Alarm Hub Output</code> can toggle an output or set it on/off, with an optional delay and duration. Sound-test actions use a configured volume and never read control values from the incoming message.</p>
1178
1209
  <p>Protect alarm arming is application-wide, so its actions are available under <code>NVR</code>, not on an individual Alarm Hub. Use <code>Read Arm Profiles</code>, <code>Select Arm Profile</code>, <code>Arm Alarm</code>, and <code>Disarm Alarm</code>. These endpoints require Protect's local Alarm Manager.</p>
1179
1210
  <p><code>Receive Events</code> performs an initial fetch and then subscribes to streams managed by the shared Protect config node. The config node keeps websocket channels and forwards matching updates to runtime nodes. In this mode, the input pin is hidden and listening starts automatically after deploy/restart.</p>
1180
- <p>For <code>Sensor</code>, <code>Camera</code>, and <code>Light</code> observables, <code>All</code> emits every event for the selected device. Choosing a specific observable normalizes the main output to a derived value and keeps the original context in <code>msg.details.raw</code>. Event observables emit <code>true/false</code>; sensor metrics such as <code>Temperature</code>, <code>Humidity</code>, <code>Light Level</code>, and <code>Battery Level</code> emit numeric values. <code>License Plate (LPR)</code> emits recognized plate text.</p>
1211
+ <p>For <code>Sensor</code>, <code>Camera</code>, <code>Light</code>, <code>Key Fob</code>, <code>Relay</code>, and <code>Alarm Hub</code> observables, <code>All</code> emits every event for the selected device. Choosing a specific observable normalizes the main output to a derived value and keeps the original context in <code>msg.details.raw</code>. Event observables emit <code>true/false</code>; sensor metrics such as <code>Temperature</code>, <code>Humidity</code>, <code>Light Level</code>, and <code>Battery Level</code> emit numeric values. <code>License Plate (LPR)</code> emits recognized plate text.</p>
1212
+ <p>For <code>Key Fob</code>, the event list includes <code>Arm (1)</code>, <code>Night (2)</code>, <code>Disarm (3)</code>, <code>Panic (4)</code>, <code>Left</code>, and <code>Right</code>. The two side buttons have no printed number. Selecting one emits <code>true</code> only for that button; the original <code>sensorButtonPressed</code> event remains available in <code>msg.details.raw</code>.</p>
1213
+ <p>The event list also covers the official Protect event families for NFC and fingerprint scans on supported cameras; vape, smoke/CO health, and button events on sensors; relay input changes; and Alarm Hub motion, entry, smoke, glass-break, emergency-button, tamper, relay, and battery events. Resource families without a granular official event type retain only <code>All</code>.</p>
1181
1214
  <p>To read plates, select <code>Camera</code> &rarr; <code>Receive Events</code> &rarr; <code>License Plate (LPR)</code>. Use an LPR-capable camera and enable license plate recognition in Protect. Open the shared <b>Connection</b> and enter its optional <b>Local User</b> and <b>Local Password</b> for a local UniFi OS account that can view the camera's recordings. All Protect nodes using that connection share this account. The official event stream identifies license plate detections but does not include OCR text in its documented schema, so the node retrieves the matching event's metadata through Protect's local, unofficial events API. Compatibility of this lookup depends on the Protect version.</p>
1182
1215
  <p>LPR emits the first available reading immediately, including low-confidence text, as a string such as <code>"AB123CD"</code> in <code>msg.payload</code>, with <code>msg.eventName = "licensePlate"</code>. Text already present in a live event bypasses any outstanding HTTP lookup. Otherwise the node starts looking for OCR as soon as a vehicle is detected, using a prepared local session without waiting for the live LPR classification or for the event to end. Only actual plate metadata is emitted.</p>
1183
1216
  <p>After a detection/update, up to five follow-up reads look for missing or improved OCR, with delays of 150, 350, 750, 1500 and 3000 milliseconds between requests. Corrected text, additional plates and higher confidence for the same text produce another message. Identical readings and lower confidence for previously emitted text are suppressed. The first text still depends on when Protect makes OCR available; a later reading is not a guarantee of accuracy.</p>
@@ -18,7 +18,9 @@ const {
18
18
  extractDeviceNameFromPayload,
19
19
  attachDeviceNameToPayload,
20
20
  attachDetails,
21
- buildErrorOutputMessage
21
+ buildErrorOutputMessage,
22
+ sendWithPayload,
23
+ hasPayloadValue
22
24
  } = require("./utils/common-utils");
23
25
  const { parseKnownPlates, namePlate, matchesDetection, describeDetection } = require("./utils/unifi-protect-detections");
24
26
  const { LICENSE_PLATE_EVENT_TYPES, extractLicensePlates, isLicensePlateEvent } = require("./utils/unifi-protect-lpr");
@@ -106,6 +108,7 @@ module.exports = function(RED) {
106
108
  node.deviceId = config.deviceId || "";
107
109
  node.capability = config.capability || "observe";
108
110
  node.capabilityConfig = config.capabilityConfig || "{}";
111
+ node.emitStartupAndUndefined = parseBoolean(config.emitStartupAndUndefined);
109
112
  node.autoEmit = parseBoolean(config.autoEmit);
110
113
  node.autoEmitIntervalSeconds = parseIntervalSeconds(config.autoEmitInterval, 60);
111
114
  node.autoEmitTimer = null;
@@ -164,10 +167,10 @@ module.exports = function(RED) {
164
167
  // event messages are available, forward them in sequence.
165
168
  try {
166
169
  if (stateMsg) {
167
- send(stateMsg);
170
+ sendWithPayload(send, stateMsg, node.emitStartupAndUndefined);
168
171
  }
169
172
  if (eventMsg) {
170
- send(eventMsg);
173
+ sendWithPayload(send, eventMsg, node.emitStartupAndUndefined);
171
174
  }
172
175
  } catch (error) {
173
176
  node.warn(`Protect output send failed: ${error && error.message ? error.message : error}`);
@@ -194,7 +197,8 @@ module.exports = function(RED) {
194
197
  if (observable) {
195
198
  // Observables let the node collapse complex Protect payloads into
196
199
  // a stable typed value while preserving the original context in details.raw.
197
- const observableValue = resolveObservableState(deviceType, payload, observable, node.currentObservableValue);
200
+ const observableValue = resolveObservableState(deviceType, payload, observable);
201
+ if (!node.emitStartupAndUndefined && !hasPayloadValue(observableValue)) return null;
198
202
  node.currentObservableValue = observableValue;
199
203
 
200
204
  const outputMsg = {
@@ -254,6 +258,7 @@ module.exports = function(RED) {
254
258
  const stateMsg = buildObservedStateMessage(deviceType, deviceId, capabilityConfig, payload, source);
255
259
 
256
260
  setNodeStatus({ fill: "green", shape: "dot", text: buildNodeStatus(deviceType, payload) });
261
+ if (source === "startup" && !node.emitStartupAndUndefined) return;
257
262
  sendOutputs(send, stateMsg, null);
258
263
  }
259
264
 
@@ -293,7 +298,7 @@ module.exports = function(RED) {
293
298
  const { events, ...history } = result;
294
299
  attachDetails(output, { history, unifiProtect: buildBaseMetadata(deviceType, deviceId, capabilityId, { source: "history" }) });
295
300
  setNodeStatus({ fill: result.hasMore ? "yellow" : "green", shape: "dot", text: `${events.length} detections${result.hasMore ? "; more available" : ""}` });
296
- send(output);
301
+ sendWithPayload(send, output, node.emitStartupAndUndefined);
297
302
  return;
298
303
  }
299
304
 
@@ -688,7 +693,7 @@ module.exports = function(RED) {
688
693
  decorateOutputMessage(output, node.currentDevice, "detectionWithImage");
689
694
  attachDetails(output, { raw: event, unifiProtect: buildBaseMetadata(node.deviceType, node.deviceId, node.capability, { source: "events" }) });
690
695
  state.sent = true;
691
- node.send(output);
696
+ sendWithPayload(node.send.bind(node), output, node.emitStartupAndUndefined);
692
697
  setNodeStatus({ fill: "blue", shape: "dot", text: "event photo received" });
693
698
  }).catch((error) => {
694
699
  if (!node.isObserving) return;
@@ -726,6 +731,7 @@ module.exports = function(RED) {
726
731
  // state output directly instead of only the event payload.
727
732
  const observation = resolveObservableEventValue(node.deviceType, item, observable, observableScopeId);
728
733
  if (observation.matched) {
734
+ if (!node.emitStartupAndUndefined && !hasPayloadValue(observation.value)) return;
729
735
  const resolvedDeviceName = resolveOutputDeviceName(node.currentDevice);
730
736
  node.currentObservableValue = observation.value;
731
737
  setNodeStatus({ fill: "blue", shape: "ring", text: `${item.type || "event"}` });
@@ -776,9 +782,9 @@ module.exports = function(RED) {
776
782
  return;
777
783
  }
778
784
 
779
- if (observation.eventTypeMatched) {
780
- return;
781
- }
785
+ // No value for the selected observable: do not emit a raw
786
+ // event as an alternative downstream command.
787
+ return;
782
788
  }
783
789
 
784
790
  setNodeStatus({ fill: "blue", shape: "ring", text: `${item.type || "event"}` });
@@ -131,6 +131,24 @@ function attachDetails(outputMsg, details) {
131
131
  };
132
132
  }
133
133
 
134
+ // Missing readings must never become downstream commands. Keep false and zero.
135
+ function hasPayloadValue(value) {
136
+ return value !== undefined && value !== null
137
+ && !(typeof value === "string" && value.trim().toLowerCase() === "undefined");
138
+ }
139
+
140
+ function sendWithPayload(send, messages, allowMissing = false) {
141
+ function filter(message) {
142
+ if (Array.isArray(message)) {
143
+ const filtered = message.map(filter);
144
+ return filtered.some((item) => item !== null) ? filtered : null;
145
+ }
146
+ return message && (allowMissing || hasPayloadValue(message.payload)) ? message : null;
147
+ }
148
+ const filtered = filter(messages);
149
+ if (filtered !== null) send(filtered);
150
+ }
151
+
134
152
  function buildErrorOutputMessage(error, nodeName) {
135
153
  return {
136
154
  topic: String(nodeName || "").trim() || undefined,
@@ -153,5 +171,7 @@ module.exports = {
153
171
  extractDeviceNameFromPayload,
154
172
  attachDeviceNameToPayload,
155
173
  attachDetails,
156
- buildErrorOutputMessage
174
+ buildErrorOutputMessage,
175
+ hasPayloadValue,
176
+ sendWithPayload
157
177
  };
@@ -591,7 +591,9 @@ function isDoorbellCapableAccessDevice(device) {
591
591
  return true;
592
592
  }
593
593
 
594
- return /READER[^A-Z0-9]*PRO/.test(joined) || /UA[-_ ]?G2[-_ ]?PRO/.test(joined);
594
+ return /READER[^A-Z0-9]*PRO/.test(joined)
595
+ || /UA[-_ ]?(?:G2|G3)[-_ ]?PRO/.test(joined)
596
+ || /(?:^|\s)UA[-_ ]?PRO(?:\s|$)/.test(joined);
595
597
  }
596
598
 
597
599
  function normalizeObjectArray(value) {
@@ -197,6 +197,42 @@ const SENSOR_OBSERVABLE_DEFINITIONS = [
197
197
  label: "Extreme values",
198
198
  eventTypes: ["sensorExtremeValues"]
199
199
  },
200
+ {
201
+ id: "vape",
202
+ label: "Vape detected",
203
+ eventTypes: ["sensorVape"]
204
+ },
205
+ {
206
+ id: "button",
207
+ label: "Button pressed",
208
+ eventTypes: ["sensorButtonPressed"],
209
+ occurrence: true
210
+ },
211
+ {
212
+ id: "smokeBatteryLow",
213
+ label: "Smoke detector battery low",
214
+ eventTypes: ["sensorSmokeBatteryLow"]
215
+ },
216
+ {
217
+ id: "smokeNeedsCleaning",
218
+ label: "Smoke detector needs cleaning",
219
+ eventTypes: ["sensorSmokeNeedsCleaning"]
220
+ },
221
+ {
222
+ id: "smokeFault",
223
+ label: "Smoke detector fault",
224
+ eventTypes: ["sensorSmokeFault"]
225
+ },
226
+ {
227
+ id: "coFault",
228
+ label: "CO detector fault",
229
+ eventTypes: ["sensorCoFault"]
230
+ },
231
+ {
232
+ id: "smokeEndOfLife",
233
+ label: "Smoke detector end of life",
234
+ eventTypes: ["sensorSmokeEndOfLife"]
235
+ },
200
236
  {
201
237
  id: "temperature",
202
238
  label: "Temperature",
@@ -254,6 +290,18 @@ const CAMERA_OBSERVABLE_DEFINITIONS = [
254
290
  id: "smartDetectLoiterZone",
255
291
  label: "Smart detect loiter",
256
292
  eventTypes: ["smartDetectLoiterZone"]
293
+ },
294
+ {
295
+ id: "nfcCardScanned",
296
+ label: "NFC card scanned",
297
+ eventTypes: ["nfcCardScanned"],
298
+ occurrence: true
299
+ },
300
+ {
301
+ id: "fingerprintIdentified",
302
+ label: "Fingerprint identified",
303
+ eventTypes: ["fingerprintIdentified"],
304
+ occurrence: true
257
305
  }
258
306
  ];
259
307
 
@@ -270,6 +318,98 @@ const LIGHT_OBSERVABLE_DEFINITIONS = [
270
318
  }
271
319
  ];
272
320
 
321
+ const FOB_OBSERVABLE_DEFINITIONS = [
322
+ {
323
+ id: "arm",
324
+ label: "Arm (1)",
325
+ eventTypes: ["sensorButtonPressed"]
326
+ },
327
+ {
328
+ id: "night",
329
+ label: "Night (2)",
330
+ eventTypes: ["sensorButtonPressed"]
331
+ },
332
+ {
333
+ id: "disarm",
334
+ label: "Disarm (3)",
335
+ eventTypes: ["sensorButtonPressed"]
336
+ },
337
+ {
338
+ id: "panic",
339
+ label: "Panic (4)",
340
+ eventTypes: ["sensorButtonPressed"]
341
+ },
342
+ {
343
+ id: "left",
344
+ label: "Left",
345
+ eventTypes: ["sensorButtonPressed"]
346
+ },
347
+ {
348
+ id: "right",
349
+ label: "Right",
350
+ eventTypes: ["sensorButtonPressed"]
351
+ }
352
+ ];
353
+
354
+ const RELAY_OBSERVABLE_DEFINITIONS = [
355
+ {
356
+ id: "inputChanged",
357
+ label: "Input changed",
358
+ eventTypes: ["relayInputChanged"]
359
+ }
360
+ ];
361
+
362
+ const ALARM_HUB_OBSERVABLE_DEFINITIONS = [
363
+ {
364
+ id: "motion",
365
+ label: "Motion input",
366
+ eventTypes: ["alarmHubMotion"]
367
+ },
368
+ {
369
+ id: "entry",
370
+ label: "Entry open/closed",
371
+ eventTypes: ["alarmHubEntryOpened", "alarmHubEntryClosed"]
372
+ },
373
+ {
374
+ id: "smoke",
375
+ label: "Smoke input",
376
+ eventTypes: ["alarmHubSmoke"]
377
+ },
378
+ {
379
+ id: "glassBreak",
380
+ label: "Glass break input",
381
+ eventTypes: ["alarmHubGlassBreak"]
382
+ },
383
+ {
384
+ id: "emergencyButton",
385
+ label: "Emergency button",
386
+ eventTypes: ["alarmHubButtonPress"],
387
+ occurrence: true
388
+ },
389
+ {
390
+ id: "tamper",
391
+ label: "Tamper",
392
+ eventTypes: ["alarmHubTamper"]
393
+ },
394
+ {
395
+ id: "relaySwitched",
396
+ label: "Relay switched",
397
+ eventTypes: ["alarmHubRelaySwitched"],
398
+ occurrence: true
399
+ },
400
+ {
401
+ id: "batteryLow",
402
+ label: "Battery low",
403
+ eventTypes: ["alarmHubBatteryLow"]
404
+ },
405
+ {
406
+ id: "batteryConnected",
407
+ label: "Battery connected",
408
+ eventTypes: ["alarmHubBatteryConnected"],
409
+ occurrence: true
410
+ }
411
+ ];
412
+
273
413
  const ALL_OBSERVABLE_VALUE = "all";
274
414
  const ALL_OBSERVABLE_OPTION = {
275
415
  value: ALL_OBSERVABLE_VALUE,
@@ -651,7 +791,74 @@ const TYPE_CAPABILITIES = {
651
791
  ],
652
792
  bridge: [],
653
793
  linkStation: [],
654
- alarmHub: [],
794
+ alarmHub: [
795
+ {
796
+ id: "triggerAlarmHubOutput",
797
+ label: "Trigger Alarm Hub Output",
798
+ description: "Turn, toggle, or pulse an Alarm Hub output.",
799
+ method: "POST",
800
+ path: "/v1/alarm-hubs/:id/outputs/:outputId/trigger",
801
+ mode: "request",
802
+ ignoreInputPayload: true,
803
+ useConfiguredPayload: true,
804
+ editor: {
805
+ fields: [
806
+ {
807
+ id: "outputId",
808
+ label: "Output",
809
+ type: "select",
810
+ options: [
811
+ { value: "0", label: "Output 0" },
812
+ { value: "1", label: "Output 1" }
813
+ ],
814
+ defaultValue: "0"
815
+ },
816
+ {
817
+ id: "state",
818
+ label: "State",
819
+ type: "select",
820
+ options: [
821
+ { value: "toggle", label: "Toggle" },
822
+ { value: "on", label: "On" },
823
+ { value: "off", label: "Off" }
824
+ ],
825
+ defaultValue: "toggle"
826
+ },
827
+ {
828
+ id: "delay",
829
+ label: "Delay (ms)",
830
+ type: "number",
831
+ defaultValue: 0,
832
+ min: 0
833
+ },
834
+ {
835
+ id: "duration",
836
+ label: "Duration (ms)",
837
+ type: "number",
838
+ defaultValue: 0,
839
+ min: 0
840
+ }
841
+ ]
842
+ },
843
+ requestComposer: ({ capabilityConfig }) => {
844
+ const state = String(capabilityConfig.state || "toggle").trim().toLowerCase();
845
+ const payload = {
846
+ delay: parseConfiguredInteger(capabilityConfig.delay, 0, Number.MAX_SAFE_INTEGER, 0),
847
+ duration: parseConfiguredInteger(capabilityConfig.duration, 0, Number.MAX_SAFE_INTEGER, 0)
848
+ };
849
+ if (state === "on" || state === "off") {
850
+ payload.enable = state === "on";
851
+ }
852
+
853
+ return {
854
+ params: {
855
+ outputId: parseConfiguredInteger(capabilityConfig.outputId, 0, 1, 0)
856
+ },
857
+ payload
858
+ };
859
+ }
860
+ }
861
+ ],
655
862
  fob: [],
656
863
  relay: [
657
864
  {
@@ -1713,7 +1920,10 @@ function getObservableDefinitions(deviceType) {
1713
1920
  const definitionsByDeviceType = {
1714
1921
  sensor: SENSOR_OBSERVABLE_DEFINITIONS,
1715
1922
  camera: CAMERA_OBSERVABLE_DEFINITIONS,
1716
- light: LIGHT_OBSERVABLE_DEFINITIONS
1923
+ light: LIGHT_OBSERVABLE_DEFINITIONS,
1924
+ fob: FOB_OBSERVABLE_DEFINITIONS,
1925
+ relay: RELAY_OBSERVABLE_DEFINITIONS,
1926
+ alarmHub: ALARM_HUB_OBSERVABLE_DEFINITIONS
1717
1927
  };
1718
1928
 
1719
1929
  return definitionsByDeviceType[String(deviceType || "").trim()] || [];
@@ -1942,6 +2152,18 @@ function resolveObservableEventValue(deviceType, event, observable, observableSc
1942
2152
  return resolveLightObservableEventValue(event, observable);
1943
2153
  }
1944
2154
 
2155
+ if (deviceType === "fob") {
2156
+ return resolveFobObservableEventValue(event, observable);
2157
+ }
2158
+
2159
+ if (deviceType === "relay") {
2160
+ return resolveRelayObservableEventValue(event, observable);
2161
+ }
2162
+
2163
+ if (deviceType === "alarmHub") {
2164
+ return resolveAlarmHubObservableEventValue(event, observable);
2165
+ }
2166
+
1945
2167
  return { matched: false };
1946
2168
  }
1947
2169
 
@@ -1970,6 +2192,13 @@ function resolveSensorObservableEventValue(event, observable) {
1970
2192
  return { matched: false };
1971
2193
  }
1972
2194
 
2195
+ if (definition.occurrence) {
2196
+ return {
2197
+ matched: true,
2198
+ value: true
2199
+ };
2200
+ }
2201
+
1973
2202
  return {
1974
2203
  matched: true,
1975
2204
  value: event.end === null || event.end === undefined
@@ -1997,6 +2226,14 @@ function resolveCameraObservableEventValue(event, observable, observableScopeId)
1997
2226
  };
1998
2227
  }
1999
2228
 
2229
+ if (definition.occurrence) {
2230
+ return {
2231
+ matched: true,
2232
+ eventTypeMatched: true,
2233
+ value: true
2234
+ };
2235
+ }
2236
+
2000
2237
  const scopeDefinition = CAMERA_OBSERVABLE_SCOPE_DEFINITIONS[String(observable || "").trim()];
2001
2238
  if (scopeDefinition) {
2002
2239
  const configuredScopeId = normalizeScopeIdentifier(observableScopeId);
@@ -2035,6 +2272,84 @@ function resolveLightObservableEventValue(event, observable) {
2035
2272
  return { matched: false };
2036
2273
  }
2037
2274
 
2275
+ function resolveFobObservableEventValue(event, observable) {
2276
+ if (!event || typeof event !== "object") {
2277
+ return { matched: false };
2278
+ }
2279
+
2280
+ const eventType = String(event.type || "").trim();
2281
+ if (eventType !== "sensorButtonPressed") {
2282
+ return { matched: false };
2283
+ }
2284
+
2285
+ const button = String(firstDefinedValue(event, [
2286
+ "metadata.button.text",
2287
+ "metadata.button.value",
2288
+ "metadata.button.name",
2289
+ "button"
2290
+ ]) || "").trim().toLowerCase();
2291
+ const selectedButton = String(observable || "").trim().toLowerCase();
2292
+
2293
+ if (!button || !selectedButton || button !== selectedButton) {
2294
+ return {
2295
+ matched: false,
2296
+ eventTypeMatched: true
2297
+ };
2298
+ }
2299
+
2300
+ return {
2301
+ matched: true,
2302
+ eventTypeMatched: true,
2303
+ value: true
2304
+ };
2305
+ }
2306
+
2307
+ function resolveRelayObservableEventValue(event, observable) {
2308
+ if (!event || typeof event !== "object" || observable !== "inputChanged" || event.type !== "relayInputChanged") {
2309
+ return { matched: false };
2310
+ }
2311
+
2312
+ const inputState = String(firstDefinedValue(event, [
2313
+ "metadata.inputState.text",
2314
+ "metadata.inputState.value",
2315
+ "inputState"
2316
+ ]) || "").trim();
2317
+
2318
+ return {
2319
+ matched: true,
2320
+ eventTypeMatched: true,
2321
+ value: inputState === "circuitClosed"
2322
+ };
2323
+ }
2324
+
2325
+ function resolveAlarmHubObservableEventValue(event, observable) {
2326
+ if (!event || typeof event !== "object") {
2327
+ return { matched: false };
2328
+ }
2329
+
2330
+ const eventType = String(event.type || "").trim();
2331
+ if (observable === "entry") {
2332
+ if (eventType === "alarmHubEntryOpened") {
2333
+ return { matched: true, eventTypeMatched: true, value: true };
2334
+ }
2335
+ if (eventType === "alarmHubEntryClosed") {
2336
+ return { matched: true, eventTypeMatched: true, value: false };
2337
+ }
2338
+ return { matched: false };
2339
+ }
2340
+
2341
+ const definition = ALARM_HUB_OBSERVABLE_DEFINITIONS.find((entry) => entry.id === observable);
2342
+ if (!definition || !definition.eventTypes.includes(eventType)) {
2343
+ return { matched: false };
2344
+ }
2345
+
2346
+ return {
2347
+ matched: true,
2348
+ eventTypeMatched: true,
2349
+ value: definition.occurrence === true || event.end === null || event.end === undefined
2350
+ };
2351
+ }
2352
+
2038
2353
  function normalizeBooleanState(value, fallbackValue) {
2039
2354
  if (typeof value === "boolean") {
2040
2355
  return value;
@@ -205,6 +205,16 @@ const OBSERVABLE_METADATA = {
205
205
  label: "Smart Detect Loiter",
206
206
  description: "True while a smart loitering detection event is active.",
207
207
  source: "inferred"
208
+ },
209
+ nfcCardScanned: {
210
+ label: "NFC Card Scanned",
211
+ description: "Emits true when an NFC card is scanned at the camera device.",
212
+ source: "official"
213
+ },
214
+ fingerprintIdentified: {
215
+ label: "Fingerprint Identified",
216
+ description: "Emits true when a fingerprint is scanned at the camera device.",
217
+ source: "official"
208
218
  }
209
219
  },
210
220
  sensor: {
@@ -248,6 +258,41 @@ const OBSERVABLE_METADATA = {
248
258
  description: "True while the sensor is reporting an active extreme-values event.",
249
259
  source: "official"
250
260
  },
261
+ vape: {
262
+ label: "Vape Detected",
263
+ description: "True while the sensor is reporting a vape detection.",
264
+ source: "official"
265
+ },
266
+ button: {
267
+ label: "Button Pressed",
268
+ description: "Emits true when the sensor reports a button press.",
269
+ source: "official"
270
+ },
271
+ smokeBatteryLow: {
272
+ label: "Smoke Detector Battery Low",
273
+ description: "True while the smoke or CO detector reports that its internal battery needs replacement.",
274
+ source: "official"
275
+ },
276
+ smokeNeedsCleaning: {
277
+ label: "Smoke Detector Needs Cleaning",
278
+ description: "True while the smoke detector reports that cleaning is required.",
279
+ source: "official"
280
+ },
281
+ smokeFault: {
282
+ label: "Smoke Detector Fault",
283
+ description: "True while the smoke detector reports a fault.",
284
+ source: "official"
285
+ },
286
+ coFault: {
287
+ label: "CO Detector Fault",
288
+ description: "True while the carbon-monoxide detector reports a fault.",
289
+ source: "official"
290
+ },
291
+ smokeEndOfLife: {
292
+ label: "Smoke Detector End of Life",
293
+ description: "True when the smoke or CO detector reports the end of its service life.",
294
+ source: "official"
295
+ },
251
296
  temperature: {
252
297
  label: "Temperature",
253
298
  description: "Current ambient temperature reported by the sensor.",
@@ -280,6 +325,92 @@ const OBSERVABLE_METADATA = {
280
325
  description: "True when the light output is currently on.",
281
326
  source: "inferred"
282
327
  }
328
+ },
329
+ fob: {
330
+ arm: {
331
+ label: "Arm (1)",
332
+ description: "Emits true when the Key Fob Arm button is pressed.",
333
+ source: "official"
334
+ },
335
+ night: {
336
+ label: "Night (2)",
337
+ description: "Emits true when the Key Fob Night button is pressed.",
338
+ source: "official"
339
+ },
340
+ disarm: {
341
+ label: "Disarm (3)",
342
+ description: "Emits true when the Key Fob Disarm button is pressed.",
343
+ source: "official"
344
+ },
345
+ panic: {
346
+ label: "Panic (4)",
347
+ description: "Emits true when the Key Fob Panic button is pressed.",
348
+ source: "official"
349
+ },
350
+ left: {
351
+ label: "Left",
352
+ description: "Emits true when the Key Fob left side button is pressed.",
353
+ source: "official"
354
+ },
355
+ right: {
356
+ label: "Right",
357
+ description: "Emits true when the Key Fob right side button is pressed.",
358
+ source: "official"
359
+ }
360
+ },
361
+ relay: {
362
+ inputChanged: {
363
+ label: "Input Changed",
364
+ description: "Emits true when the relay input circuit closes and false when it opens.",
365
+ source: "official"
366
+ }
367
+ },
368
+ alarmHub: {
369
+ motion: {
370
+ label: "Motion Input",
371
+ description: "True while an Alarm Hub motion input is active.",
372
+ source: "official"
373
+ },
374
+ entry: {
375
+ label: "Entry Open/Closed",
376
+ description: "True when an Alarm Hub entry input opens and false when it closes.",
377
+ source: "official"
378
+ },
379
+ smoke: {
380
+ label: "Smoke Input",
381
+ description: "True while an Alarm Hub smoke input is active.",
382
+ source: "official"
383
+ },
384
+ glassBreak: {
385
+ label: "Glass Break Input",
386
+ description: "True while an Alarm Hub glass-break input is active.",
387
+ source: "official"
388
+ },
389
+ emergencyButton: {
390
+ label: "Emergency Button",
391
+ description: "Emits true when an Alarm Hub emergency button is pressed.",
392
+ source: "official"
393
+ },
394
+ tamper: {
395
+ label: "Tamper",
396
+ description: "True while an Alarm Hub input reports tampering.",
397
+ source: "official"
398
+ },
399
+ relaySwitched: {
400
+ label: "Relay Switched",
401
+ description: "Emits true when an Alarm Hub relay output is switched.",
402
+ source: "official"
403
+ },
404
+ batteryLow: {
405
+ label: "Battery Low",
406
+ description: "True while the Alarm Hub reports a low battery condition.",
407
+ source: "official"
408
+ },
409
+ batteryConnected: {
410
+ label: "Battery Connected",
411
+ description: "Emits true when an Alarm Hub battery is connected.",
412
+ source: "official"
413
+ }
283
414
  }
284
415
  };
285
416
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.1.15",
3
+ "version": "1.1.17",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",