node-red-contrib-unifi-ultimate 1.0.2 → 1.0.4

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.
@@ -7,6 +7,16 @@
7
7
  defaults: {
8
8
  name: { value: "Unifi Network Config" },
9
9
  host: { value: "", required: true },
10
+ port: {
11
+ value: "",
12
+ required: false,
13
+ validate: function (value) {
14
+ if (value === undefined || value === null || value === "") {
15
+ return true;
16
+ }
17
+ return /^\d+$/.test(String(value)) && Number(value) >= 1 && Number(value) <= 65535;
18
+ }
19
+ },
10
20
  rejectUnauthorized: { value: false },
11
21
  powerObservationIntervalSeconds: {
12
22
  value: 15,
@@ -28,9 +38,11 @@
28
38
  oneditprepare: function () {
29
39
  const node = this;
30
40
  const $hostInput = $("#node-config-input-host");
41
+ const $port = $("#node-config-input-port");
31
42
  const $apiKey = $("#node-config-input-apiKey");
32
43
  const $rejectUnauthorized = $("#node-config-input-rejectUnauthorized");
33
44
  const $powerObservationIntervalSeconds = $("#node-config-input-powerObservationIntervalSeconds");
45
+ const $portRow = $port.closest(".form-row");
34
46
  const $apiKeyRow = $apiKey.closest(".form-row");
35
47
  const $securityRow = $rejectUnauthorized.closest(".form-row");
36
48
  const $powerObservationRow = $powerObservationIntervalSeconds.closest(".form-row");
@@ -38,6 +50,7 @@
38
50
 
39
51
  function syncProgressiveRows() {
40
52
  const hasHost = String($hostInput.val() || node.host || "").trim() !== "";
53
+ $portRow.toggle(hasHost);
41
54
  $apiKeyRow.toggle(hasHost);
42
55
  $securityRow.toggle(hasHost);
43
56
  $powerObservationRow.toggle(hasHost);
@@ -73,6 +86,10 @@
73
86
  <label for="node-config-input-host"><i class="fa fa-globe"></i> Controller</label>
74
87
  <input type="text" id="node-config-input-host" placeholder="192.168.1.10">
75
88
  </div>
89
+ <div class="form-row">
90
+ <label for="node-config-input-port"><i class="fa fa-plug"></i> Port</label>
91
+ <input type="text" id="node-config-input-port" placeholder="443 (default)">
92
+ </div>
76
93
  <div class="form-row">
77
94
  <label for="node-config-input-apiKey"><i class="fa fa-key"></i> API Key</label>
78
95
  <input type="password" id="node-config-input-apiKey" placeholder="Paste your UniFi Network API key">
@@ -101,6 +118,7 @@
101
118
 
102
119
  <h3>Configuration</h3>
103
120
  <p><b>Controller</b> accepts the UniFi OS host or IP address. The node builds the local UniFi Network proxy URL automatically.</p>
121
+ <p><b>Port</b> is optional. Leave it empty to use the default <code>443</code>. Set it when your UniFi OS server listens on a custom port (for example <code>11443</code>). A port embedded directly in the Controller field (<code>host:port</code>) takes precedence over this field.</p>
104
122
  <p><b>API Key</b> is required for authentication and is sent as <code>X-API-Key</code>.</p>
105
123
  <p><b>Security</b> controls certificate verification. Disable it only when your controller uses a self-signed certificate.</p>
106
124
  <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>
@@ -2,6 +2,8 @@
2
2
 
3
3
  const {
4
4
  buildBaseUrlFromHost,
5
+ normalizePort,
6
+ applyPortToHost,
5
7
  buildQueryString,
6
8
  doRequest,
7
9
  buildRequestHeaders,
@@ -75,7 +77,8 @@ module.exports = function(RED) {
75
77
  const node = this;
76
78
  node.name = config.name;
77
79
  node.host = String(config.host || "").trim();
78
- node.baseUrl = buildBaseUrlFromHost(node.host);
80
+ node.port = normalizePort(config.port);
81
+ node.baseUrl = buildBaseUrlFromHost(node.host, node.port);
79
82
  node.rejectUnauthorized = config.rejectUnauthorized !== false && config.rejectUnauthorized !== "false";
80
83
  node.powerObservationIntervalSeconds = normalizePowerObserverIntervalSeconds(config.powerObservationIntervalSeconds);
81
84
  node.nodeClients = [];
@@ -642,10 +645,13 @@ module.exports = function(RED) {
642
645
  };
643
646
 
644
647
  node.buildUnofficialNetworkWebSocketUrl = () => {
645
- const normalizedHost = String(node.host || "")
646
- .trim()
647
- .replace(/^https?:\/\//i, "")
648
- .replace(/\/.*$/, "");
648
+ const normalizedHost = applyPortToHost(
649
+ String(node.host || "")
650
+ .trim()
651
+ .replace(/^https?:\/\//i, "")
652
+ .replace(/\/.*$/, ""),
653
+ node.port
654
+ );
649
655
  if (!normalizedHost) {
650
656
  throw new Error("The configured host is empty or invalid.");
651
657
  }
@@ -16,10 +16,10 @@
16
16
  action: { value: "msgPayload", required: true }
17
17
  },
18
18
  inputs: 1,
19
- outputs: 1,
19
+ outputs: 2,
20
20
  icon: "unifi-u-logo-light-network.svg",
21
21
  paletteLabel: "Control POE",
22
- outputLabels: ["result"],
22
+ outputLabels: ["result", "error"],
23
23
  label: function () {
24
24
  return this.name || "Control POE";
25
25
  },
@@ -1122,18 +1122,35 @@
1122
1122
  <li>For all other actions, input message properties are ignored.</li>
1123
1123
  </ul>
1124
1124
 
1125
- <h3>Output</h3>
1126
- <ul>
1127
- <li>The node emits a new message after the configured action completes.</li>
1128
- <li><code>msg.payload</code>: API response payload.</li>
1129
- <li><code>msg.topic</code>: node name from the editor.</li>
1130
- <li><code>msg.deviceName</code>: remembered selected switch/client name.</li>
1131
- <li><code>msg.eventName</code>: action that produced the message.</li>
1132
- <li><code>msg.details.unifiNetworkPoe</code>: metadata with device/site/action/port.</li>
1133
- <li><code>msg.details.unifiNetworkPoe.portPowerW</code>: current PoE power draw (watts) for the selected port when available.</li>
1134
- <li><code>msg.payload.powerConsumptionSwitchTotal</code>: sum of PoE power draw of all switch ports (watts) when available.</li>
1135
- <li>Power-consumption emit actions produce <code>msg.payload.portPowerW</code> and include <code>msg.payload.powerChanged</code>.</li>
1136
- </ul>
1125
+ <h3>Outputs</h3>
1126
+ <dl class="message-properties">
1127
+ <dt>Output 1 — result</dt>
1128
+ <dd>Emitted after the configured action completes successfully.</dd>
1129
+ <dt class="optional">msg.payload</dt>
1130
+ <dd>API response payload.</dd>
1131
+ <dt class="optional">msg.topic</dt>
1132
+ <dd>Node name from the editor.</dd>
1133
+ <dt class="optional">msg.deviceName</dt>
1134
+ <dd>Remembered name of the selected switch or client.</dd>
1135
+ <dt class="optional">msg.eventName</dt>
1136
+ <dd>Action that produced the message.</dd>
1137
+ <dt class="optional">msg.details.unifiNetworkPoe</dt>
1138
+ <dd>Metadata with device, site, action, and port details. Includes <code>portPowerW</code> for the selected port when available.</dd>
1139
+ <dt class="optional">msg.payload.powerConsumptionSwitchTotal</dt>
1140
+ <dd>Sum of PoE power draw for all switch ports (watts) when available.</dd>
1141
+ <dt class="optional">msg.payload.portPowerW / msg.payload.powerChanged</dt>
1142
+ <dd>Available in power-consumption emit messages.</dd>
1143
+ </dl>
1144
+ <dl class="message-properties">
1145
+ <dt>Output 2 — error</dt>
1146
+ <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>
1147
+ <dt class="optional">msg.payload</dt>
1148
+ <dd><code>null</code></dd>
1149
+ <dt class="optional">msg.topic</dt>
1150
+ <dd>Node name from the editor.</dd>
1151
+ <dt class="optional">msg.error.message</dt>
1152
+ <dd>Human-readable error description.</dd>
1153
+ </dl>
1137
1154
  <p><b>Power fields (guaranteed vs optional)</b></p>
1138
1155
  <table style="width:100%; border-collapse:collapse;">
1139
1156
  <thead>
@@ -1166,7 +1183,7 @@
1166
1183
  </tr>
1167
1184
  </tbody>
1168
1185
  </table>
1169
- <p>Example output:</p>
1186
+ <p>Example output (pin 1):</p>
1170
1187
  <pre><code>{
1171
1188
  "topic": "POE Soffitta Port 2",
1172
1189
  "deviceName": "Soffitta",
@@ -1188,5 +1205,11 @@
1188
1205
  "powerConsumptionSwitchTotal": 36.4
1189
1206
  }
1190
1207
  }
1208
+ }</code></pre>
1209
+ <p>Example output (pin 2 — error):</p>
1210
+ <pre><code>{
1211
+ "topic": "POE Soffitta Port 2",
1212
+ "payload": null,
1213
+ "error": { "message": "Missing switch device id." }
1191
1214
  }</code></pre>
1192
1215
  </script>
@@ -5,6 +5,16 @@ const {
5
5
  resolveScopedIdentifiers
6
6
  } = require("./utils/unifi-network-device-registry");
7
7
  const { extractNetworkData } = require("./utils/unifi-network-utils");
8
+ const {
9
+ buildStatusTimestampText,
10
+ appendStatusTimestamp,
11
+ resolveNodeName,
12
+ resolveDeviceName,
13
+ extractDeviceNameFromPayload,
14
+ attachDeviceNameToPayload,
15
+ attachDetails,
16
+ buildErrorOutputMessage
17
+ } = require("./utils/common-utils");
8
18
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
9
19
 
10
20
  function normalizeString(value) {
@@ -120,73 +130,6 @@ function resolvePayloadBoolean(value) {
120
130
  return null;
121
131
  }
122
132
 
123
- function resolveNodeName(value) {
124
- return String(value || "").trim();
125
- }
126
-
127
- function resolveDeviceName(value) {
128
- return String(value || "").trim();
129
- }
130
-
131
- function extractDeviceNameFromPayload(payload) {
132
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
133
- return "";
134
- }
135
-
136
- return resolveDeviceName(
137
- payload.name
138
- || payload.displayName
139
- || payload.hostname
140
- || payload.alias
141
- || payload.full_name
142
- || payload.macAddress
143
- || payload.id
144
- );
145
- }
146
-
147
- function attachDeviceNameToPayload(payload, deviceName) {
148
- if (!deviceName) {
149
- return payload;
150
- }
151
-
152
- if (payload && typeof payload === "object" && !Array.isArray(payload)) {
153
- return {
154
- ...payload,
155
- deviceName
156
- };
157
- }
158
-
159
- return payload;
160
- }
161
-
162
- function attachDetails(outputMsg, details) {
163
- if (!outputMsg || typeof outputMsg !== "object" || Array.isArray(outputMsg)) {
164
- return;
165
- }
166
- if (!details || typeof details !== "object" || Array.isArray(details)) {
167
- return;
168
- }
169
-
170
- outputMsg.details = {
171
- ...(outputMsg.details && typeof outputMsg.details === "object" && !Array.isArray(outputMsg.details)
172
- ? outputMsg.details
173
- : {}),
174
- ...details
175
- };
176
- }
177
-
178
- function buildStatusTimestampText() {
179
- const now = new Date();
180
- const time = now.toTimeString().split(" ")[0];
181
- return `(day ${now.getDate()}, ${time})`;
182
- }
183
-
184
- function appendStatusTimestamp(text) {
185
- const normalized = String(text === undefined || text === null ? "" : text).trim();
186
- const suffix = buildStatusTimestampText();
187
- return normalized ? `${normalized} ${suffix}` : suffix;
188
- }
189
-
190
133
  function resolveNumericPortIndex(value) {
191
134
  const parsed = Number(value);
192
135
  return Number.isFinite(parsed) ? Math.trunc(parsed) : NaN;
@@ -821,6 +764,7 @@ module.exports = function(RED) {
821
764
  }
822
765
  } catch (error) {
823
766
  setNodeStatus({ fill: "red", shape: "ring", text: "error" });
767
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
824
768
  if (typeof done === "function") {
825
769
  done(error);
826
770
  } else {
@@ -19,10 +19,10 @@
19
19
  autoEmitInterval: { value: 60, validate: RED.validators.number() }
20
20
  },
21
21
  inputs: 1,
22
- outputs: 1,
22
+ outputs: 2,
23
23
  icon: "unifi-u-logo-light-network.svg",
24
24
  paletteLabel: "NETWORK",
25
- outputLabels: ["result"],
25
+ outputLabels: ["result", "error"],
26
26
  label: function () {
27
27
  return this.name || this.deviceId || "Unifi Network";
28
28
  },
@@ -1287,16 +1287,32 @@
1287
1287
  <li>Input message properties are ignored by this node.</li>
1288
1288
  </ul>
1289
1289
 
1290
- <h3>Output</h3>
1291
- <ul>
1292
- <li>Output 1 emits a new message containing the current state or primary capability response.</li>
1293
- <li><code>msg.payload</code> contains the response payload.</li>
1294
- <li><code>msg.topic</code>: node name from the editor.</li>
1295
- <li><code>msg.deviceName</code>: remembered/observed selected item name.</li>
1296
- <li><code>msg.eventName</code>: trigger/event that produced the message.</li>
1297
- <li><code>msg.details.unifiNetwork</code>: standardized metadata for the selected item and capability.</li>
1298
- </ul>
1299
- <p>Example output:</p>
1290
+ <h3>Outputs</h3>
1291
+ <dl class="message-properties">
1292
+ <dt>Output 1 — result</dt>
1293
+ <dd>Emitted when the action completes successfully.</dd>
1294
+ <dt class="optional">msg.payload</dt>
1295
+ <dd>Response payload from the UniFi API.</dd>
1296
+ <dt class="optional">msg.topic</dt>
1297
+ <dd>Node name from the editor.</dd>
1298
+ <dt class="optional">msg.deviceName</dt>
1299
+ <dd>Remembered/observed name of the selected item.</dd>
1300
+ <dt class="optional">msg.eventName</dt>
1301
+ <dd>Trigger or event that produced the message.</dd>
1302
+ <dt class="optional">msg.details.unifiNetwork</dt>
1303
+ <dd>Standardized metadata for the selected item and capability.</dd>
1304
+ </dl>
1305
+ <dl class="message-properties">
1306
+ <dt>Output 2 — error</dt>
1307
+ <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>
1308
+ <dt class="optional">msg.payload</dt>
1309
+ <dd><code>null</code></dd>
1310
+ <dt class="optional">msg.topic</dt>
1311
+ <dd>Node name from the editor.</dd>
1312
+ <dt class="optional">msg.error.message</dt>
1313
+ <dd>Human-readable error description.</dd>
1314
+ </dl>
1315
+ <p>Example output (pin 1):</p>
1300
1316
  <pre><code>{
1301
1317
  "topic": "Switch Soffitta",
1302
1318
  "deviceName": "Soffitta",
@@ -1315,5 +1331,11 @@
1315
1331
  "source": "request"
1316
1332
  }
1317
1333
  }
1334
+ }</code></pre>
1335
+ <p>Example output (pin 2 — error):</p>
1336
+ <pre><code>{
1337
+ "topic": "Switch Soffitta",
1338
+ "payload": null,
1339
+ "error": { "message": "Request timed out" }
1318
1340
  }</code></pre>
1319
1341
  </script>
@@ -8,6 +8,18 @@ const {
8
8
  resolveScopedIdentifiers
9
9
  } = require("./utils/unifi-network-device-registry");
10
10
  const { extractNetworkData } = require("./utils/unifi-network-utils");
11
+ const {
12
+ parseBoolean,
13
+ parseIntervalSeconds,
14
+ buildStatusTimestampText,
15
+ appendStatusTimestamp,
16
+ resolveNodeName,
17
+ resolveDeviceName,
18
+ extractDeviceNameFromPayload,
19
+ attachDeviceNameToPayload,
20
+ attachDetails,
21
+ buildErrorOutputMessage
22
+ } = require("./utils/common-utils");
11
23
  const UNOFFICIAL_NETWORK_STREAM_CAPABILITY = "observeUnofficialEvents";
12
24
  const UNOFFICIAL_POLL_INTERVAL_MS = 3000;
13
25
  const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
@@ -47,18 +59,6 @@ function resolveCapabilityConfig(configuredCapabilityConfig) {
47
59
  return parseCapabilityConfig(configuredCapabilityConfig);
48
60
  }
49
61
 
50
- function parseBoolean(value) {
51
- return value === true || value === "true" || value === 1 || value === "1";
52
- }
53
-
54
- function parseIntervalSeconds(value, fallback) {
55
- const numeric = Number(value);
56
- if (!Number.isFinite(numeric) || numeric < 5) {
57
- return fallback;
58
- }
59
- return Math.trunc(numeric);
60
- }
61
-
62
62
  function normalizeIdentifierKey(value) {
63
63
  return String(value || "").trim().toLowerCase().replace(/[^a-z0-9]/g, "");
64
64
  }
@@ -149,73 +149,6 @@ function buildNodeStatus(deviceType, payload) {
149
149
  return baseName || normalizedType || "ready";
150
150
  }
151
151
 
152
- function resolveNodeName(value) {
153
- return String(value || "").trim();
154
- }
155
-
156
- function resolveDeviceName(value) {
157
- return String(value || "").trim();
158
- }
159
-
160
- function extractDeviceNameFromPayload(payload) {
161
- if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
162
- return "";
163
- }
164
-
165
- return resolveDeviceName(
166
- payload.name
167
- || payload.displayName
168
- || payload.hostname
169
- || payload.alias
170
- || payload.full_name
171
- || payload.macAddress
172
- || payload.id
173
- );
174
- }
175
-
176
- function attachDeviceNameToPayload(payload, deviceName) {
177
- if (!deviceName) {
178
- return payload;
179
- }
180
-
181
- if (payload && typeof payload === "object" && !Array.isArray(payload)) {
182
- return {
183
- ...payload,
184
- deviceName
185
- };
186
- }
187
-
188
- return payload;
189
- }
190
-
191
- function attachDetails(outputMsg, details) {
192
- if (!outputMsg || typeof outputMsg !== "object" || Array.isArray(outputMsg)) {
193
- return;
194
- }
195
- if (!details || typeof details !== "object" || Array.isArray(details)) {
196
- return;
197
- }
198
-
199
- outputMsg.details = {
200
- ...(outputMsg.details && typeof outputMsg.details === "object" && !Array.isArray(outputMsg.details)
201
- ? outputMsg.details
202
- : {}),
203
- ...details
204
- };
205
- }
206
-
207
- function buildStatusTimestampText() {
208
- const now = new Date();
209
- const time = now.toTimeString().split(" ")[0];
210
- return `(day ${now.getDate()}, ${time})`;
211
- }
212
-
213
- function appendStatusTimestamp(text) {
214
- const normalized = String(text === undefined || text === null ? "" : text).trim();
215
- const suffix = buildStatusTimestampText();
216
- return normalized ? `${normalized} ${suffix}` : suffix;
217
- }
218
-
219
152
  function extractNetworkEventName(payload) {
220
153
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
221
154
  return "event";
@@ -1116,6 +1049,7 @@ module.exports = function(RED) {
1116
1049
  invokeCapability(node.send.bind(node), "interval")
1117
1050
  .catch((error) => {
1118
1051
  setNodeStatus({ fill: "red", shape: "ring", text: "auto error" });
1052
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
1119
1053
  node.error(error);
1120
1054
  })
1121
1055
  .finally(() => {
@@ -1146,6 +1080,7 @@ module.exports = function(RED) {
1146
1080
  }
1147
1081
  } catch (error) {
1148
1082
  setNodeStatus({ fill: "red", shape: "ring", text: "error" });
1083
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
1149
1084
  if (typeof done === "function") {
1150
1085
  done(error);
1151
1086
  } else {
@@ -15,10 +15,10 @@
15
15
  offlineHysteresis: { value: 30, required: true, validate: RED.validators.number() }
16
16
  },
17
17
  inputs: 0,
18
- outputs: 1,
18
+ outputs: 2,
19
19
  icon: "unifi-u-logo-light-network.svg",
20
20
  paletteLabel: "Presence Detection",
21
- outputLabels: ["presence"],
21
+ outputLabels: ["presence", "error"],
22
22
  label: function () {
23
23
  return this.name || "Presence Detection";
24
24
  },
@@ -535,18 +535,36 @@
535
535
  <li>No input pin in this mode: checks run automatically at startup and then on the configured cadence through the shared config scheduler.</li>
536
536
  </ul>
537
537
 
538
- <h3>Output</h3>
539
- <ul>
540
- <li>The node emits a new message when the debounced presence state changes.</li>
541
- <li><code>msg.payload</code>: <code>true</code> when present, <code>false</code> when absent.</li>
542
- <li><code>msg.present</code>: same boolean presence value.</li>
543
- <li><code>msg.topic</code>: node name from the editor.</li>
544
- <li><code>msg.deviceName</code>: remembered selected client name.</li>
545
- <li><code>msg.eventName</code>: reason/source that produced the message.</li>
546
- <li><code>msg.details.client</code>: last known client object when available.</li>
547
- <li><code>msg.details.unifiNetworkPresence</code>: metadata including site/client ids and hysteresis settings.</li>
548
- </ul>
549
- <p>Example output:</p>
538
+ <h3>Outputs</h3>
539
+ <dl class="message-properties">
540
+ <dt>Output 1 — presence</dt>
541
+ <dd>Emitted when the debounced presence state changes.</dd>
542
+ <dt class="optional">msg.payload</dt>
543
+ <dd><code>true</code> when the client is present, <code>false</code> when absent.</dd>
544
+ <dt class="optional">msg.present</dt>
545
+ <dd>Same boolean presence value as <code>msg.payload</code>.</dd>
546
+ <dt class="optional">msg.topic</dt>
547
+ <dd>Node name from the editor.</dd>
548
+ <dt class="optional">msg.deviceName</dt>
549
+ <dd>Remembered name of the selected client.</dd>
550
+ <dt class="optional">msg.eventName</dt>
551
+ <dd>Reason or source that produced the message.</dd>
552
+ <dt class="optional">msg.details.client</dt>
553
+ <dd>Last known client object when available.</dd>
554
+ <dt class="optional">msg.details.unifiNetworkPresence</dt>
555
+ <dd>Metadata including site/client ids and hysteresis settings.</dd>
556
+ </dl>
557
+ <dl class="message-properties">
558
+ <dt>Output 2 — error</dt>
559
+ <dd>Emitted when a presence poll 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>
560
+ <dt class="optional">msg.payload</dt>
561
+ <dd><code>null</code></dd>
562
+ <dt class="optional">msg.topic</dt>
563
+ <dd>Node name from the editor.</dd>
564
+ <dt class="optional">msg.error.message</dt>
565
+ <dd>Human-readable error description.</dd>
566
+ </dl>
567
+ <p>Example output (pin 1):</p>
550
568
  <pre><code>{
551
569
  "topic": "iPhone Massimo Presence",
552
570
  "deviceName": "iPhone-Massimo",
@@ -560,5 +578,11 @@
560
578
  "reason": "connected"
561
579
  }
562
580
  }
581
+ }</code></pre>
582
+ <p>Example output (pin 2 — error):</p>
583
+ <pre><code>{
584
+ "topic": "iPhone Massimo Presence",
585
+ "payload": null,
586
+ "error": { "message": "Presence polling failed" }
563
587
  }</code></pre>
564
588
  </script>
@@ -1,6 +1,15 @@
1
1
  "use strict";
2
2
 
3
3
  const { decodeScopedDeviceId } = require("./utils/unifi-network-device-registry");
4
+ const {
5
+ buildStatusTimestampText,
6
+ appendStatusTimestamp,
7
+ resolveNodeName,
8
+ resolveDeviceName,
9
+ extractDeviceNameFromPayload,
10
+ attachDetails,
11
+ buildErrorOutputMessage
12
+ } = require("./utils/common-utils");
4
13
  const DEFAULT_REQUEST_TIMEOUT_MS = 8000;
5
14
 
6
15
  function parsePositiveSeconds(value, fallbackValue) {
@@ -25,58 +34,6 @@ function resolveClientId(configuredClientId) {
25
34
  return String(configuredClientId || "").trim();
26
35
  }
27
36
 
28
- function resolveNodeName(value) {
29
- return String(value || "").trim();
30
- }
31
-
32
- function resolveDeviceName(value) {
33
- return String(value || "").trim();
34
- }
35
-
36
- function extractDeviceNameFromClient(client) {
37
- if (!client || typeof client !== "object" || Array.isArray(client)) {
38
- return "";
39
- }
40
-
41
- return resolveDeviceName(
42
- client.name
43
- || client.displayName
44
- || client.hostname
45
- || client.alias
46
- || client.full_name
47
- || client.macAddress
48
- || client.id
49
- );
50
- }
51
-
52
- function attachDetails(outputMsg, details) {
53
- if (!outputMsg || typeof outputMsg !== "object" || Array.isArray(outputMsg)) {
54
- return;
55
- }
56
- if (!details || typeof details !== "object" || Array.isArray(details)) {
57
- return;
58
- }
59
-
60
- outputMsg.details = {
61
- ...(outputMsg.details && typeof outputMsg.details === "object" && !Array.isArray(outputMsg.details)
62
- ? outputMsg.details
63
- : {}),
64
- ...details
65
- };
66
- }
67
-
68
- function buildStatusTimestampText() {
69
- const now = new Date();
70
- const time = now.toTimeString().split(" ")[0];
71
- return `(day ${now.getDate()}, ${time})`;
72
- }
73
-
74
- function appendStatusTimestamp(text) {
75
- const normalized = String(text === undefined || text === null ? "" : text).trim();
76
- const suffix = buildStatusTimestampText();
77
- return normalized ? `${normalized} ${suffix}` : suffix;
78
- }
79
-
80
37
  module.exports = function(RED) {
81
38
  function UnifiNetworkPresenceNode(config) {
82
39
  RED.nodes.createNode(this, config);
@@ -125,7 +82,7 @@ module.exports = function(RED) {
125
82
  }
126
83
 
127
84
  function resolveOutputDeviceName(payload) {
128
- const extracted = extractDeviceNameFromClient(payload) || extractDeviceNameFromClient(node.lastKnownClient);
85
+ const extracted = extractDeviceNameFromPayload(payload) || extractDeviceNameFromPayload(node.lastKnownClient);
129
86
  if (extracted) {
130
87
  node.deviceName = extracted;
131
88
  return extracted;
@@ -290,7 +247,9 @@ module.exports = function(RED) {
290
247
 
291
248
  setNodeStatus({ fill: "red", shape: "ring", text: "error" });
292
249
  const errorMessage = String(snapshot && (snapshot.error || snapshot.message) || "Presence polling failed");
293
- node.error(new Error(errorMessage));
250
+ const presenceError = new Error(errorMessage);
251
+ node.send([null, buildErrorOutputMessage(presenceError, node.name)]);
252
+ node.error(presenceError);
294
253
  }
295
254
 
296
255
  async function requestPresenceSnapshot(source) {
@@ -341,6 +300,8 @@ module.exports = function(RED) {
341
300
  done();
342
301
  }
343
302
  } catch (error) {
303
+ setNodeStatus({ fill: "red", shape: "ring", text: "error" });
304
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
344
305
  if (typeof done === "function") {
345
306
  done(error);
346
307
  } else {
@@ -388,6 +349,7 @@ module.exports = function(RED) {
388
349
  processPresenceSnapshot(snapshot);
389
350
  }).catch((error) => {
390
351
  setNodeStatus({ fill: "red", shape: "ring", text: "error" });
352
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
391
353
  node.error(error);
392
354
  });
393
355
  }