node-red-contrib-unifi-ultimate 1.0.5 → 1.0.6

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
@@ -82,6 +82,7 @@ Things you can do:
82
82
  - Restart a UniFi device.
83
83
  - Power-cycle or turn on/off a PoE port.
84
84
  - Let the PoE node automatically find which port a client is connected to.
85
+ - Restart a whole list of switches/APs at once, or power-cycle all their active PoE ports, with the **Restart** node.
85
86
 
86
87
  <br/>
87
88
  <br/>
@@ -1107,7 +1107,7 @@
1107
1107
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
1108
1108
  <p><b>Search by</b> chooses how to target the port: select <code>Switch + Port</code> directly, or select a <code>Client</code> and let the node fill in the connected switch and port.</p>
1109
1109
  <p><b>Switch</b> selects the adopted UniFi switch. The selector is searchable.</p>
1110
- <p><b>Client</b> lists clients with known switch and port mapping. The selector is searchable.</p>
1110
+ <p><b>Client</b> lists clients with known switch and port mapping. The selector is searchable and shows the user-defined client name (e.g. "iPhone di Massimo") when set, otherwise the device hostname.</p>
1111
1111
  <p><b>Port</b> selects the physical port index. Port labels include connected clients or downstream UniFi devices when available.</p>
1112
1112
  <p><b>Action</b> executes the configured PoE operation. <code>POE controlled by msg.payload</code> maps incoming payloads to PoE mode (<code>true</code> enables PoE, <code>false</code> disables PoE). Enable and Disable update the UniFi port override (<code>poe_mode</code> auto/off). Power Cycle uses the official Network port action. <code>Emit Power Consumption</code> emits power values from the shared observer in the config node.</p>
1113
1113
  <p><b>Power poll interval</b> for emit action is configured globally in <code>Unifi Network Config</code>. This node does not run its own timer.</p>
@@ -362,7 +362,7 @@
362
362
  || item.online === false
363
363
  || String(item.state || "").toLowerCase() === "offline";
364
364
  const stateSuffix = isOffline
365
- ? ""
365
+ ? " (offline)"
366
366
  : (item.state ? " [" + item.state + "]" : "");
367
367
  const $option = $("<option></option>")
368
368
  .val(item.id)
@@ -523,7 +523,7 @@
523
523
 
524
524
  <h3>Configuration</h3>
525
525
  <p><b>Connection</b> selects the shared UniFi Network config node.</p>
526
- <p><b>Client</b> selects the client to track. The selector is searchable and opens with the complete list before filtering.</p>
526
+ <p><b>Client</b> selects the client to track. The selector is searchable and opens with the complete list before filtering. Each entry shows the user-defined client name (e.g. "iPhone di Massimo") when set, otherwise the device hostname. Known-but-offline clients are included too and marked with an <code>(offline)</code> label, so you can pick a target even while it is disconnected.</p>
527
527
  <p><b>Poll (s)</b> sets this node cadence for presence checks. Scheduling and fetch execution are handled by the shared Network config node.</p>
528
528
  <p><b>Connect Hysteresis (s)</b> delays the <code>true</code> output so brief reconnects do not flap.</p>
529
529
  <p><b>Hysteresis (s)</b> delays the <code>false</code> output to avoid flapping when the client disconnects briefly.</p>
@@ -0,0 +1,373 @@
1
+ <link rel="stylesheet" type="text/css" href="resources/node-red-contrib-unifi-ultimate/editor/unifi-ultimate-editor-common.css">
2
+
3
+
4
+ <script type="text/javascript">
5
+ RED.nodes.registerType("unifi-network-restart", {
6
+ category: "Unifi Ultimate",
7
+ color: "#CFE8FB",
8
+ defaults: {
9
+ name: { value: "" },
10
+ server: { value: "", type: "unifi-network-config", required: true },
11
+ operation: { value: "restartDevices", required: true },
12
+ deviceIds: { value: "[]" },
13
+ deviceNames: { value: "{}" }
14
+ },
15
+ inputs: 1,
16
+ outputs: 2,
17
+ icon: "unifi-u-logo-light-network.svg",
18
+ paletteLabel: "Restart",
19
+ outputLabels: ["result", "error"],
20
+ label: function () {
21
+ return this.name || "Restart";
22
+ },
23
+ oneditsave: function () {
24
+ const selected = [];
25
+ const names = {};
26
+ $("#unifi-restart-device-list input[type='checkbox']:checked").each(function () {
27
+ const id = String($(this).attr("data-id") || "").trim();
28
+ if (!id) {
29
+ return;
30
+ }
31
+ selected.push(id);
32
+ names[id] = String($(this).attr("data-name") || "").trim() || id;
33
+ });
34
+
35
+ $("#node-input-deviceIds").val(JSON.stringify(selected));
36
+ $("#node-input-deviceNames").val(JSON.stringify(names));
37
+ },
38
+ oneditprepare: function () {
39
+ const node = this;
40
+ const $server = $("#node-input-server");
41
+ const $operation = $("#node-input-operation");
42
+ const $listRow = $("#node-row-deviceList");
43
+ const $list = $("#unifi-restart-device-list");
44
+ const $count = $("#unifi-restart-selected-count");
45
+ const $filter = $("#unifi-restart-filter");
46
+ const $refresh = $("#node-input-refreshDevices");
47
+ const $status = $("#unifi-restart-list-status");
48
+
49
+ let loadedServerId = "";
50
+ let loadingPromise = null;
51
+
52
+ function parseStoredIds() {
53
+ try {
54
+ const parsed = JSON.parse(String(node.deviceIds || "[]"));
55
+ return Array.isArray(parsed) ? parsed.map(function (id) { return String(id || "").trim(); }).filter(Boolean) : [];
56
+ } catch (error) {
57
+ return [];
58
+ }
59
+ }
60
+
61
+ function hasSelection($field) {
62
+ return String($field.val() || "").trim() !== "";
63
+ }
64
+
65
+ function requestJson(url) {
66
+ return new Promise(function (resolve, reject) {
67
+ $.getJSON(url, function (data) {
68
+ resolve(data);
69
+ }).fail(function (xhr) {
70
+ reject(xhr);
71
+ });
72
+ });
73
+ }
74
+
75
+ // Gateways, consoles and cloud keys are not switches/APs, so they are
76
+ // available in the list but never checked by default.
77
+ function isGatewayLike(item) {
78
+ const raw = item && item.raw && typeof item.raw === "object" ? item.raw : {};
79
+ const type = String(raw.type || "").trim().toLowerCase();
80
+ if (["udm", "ugw", "uxg", "ucg", "uck"].indexOf(type) !== -1) {
81
+ return true;
82
+ }
83
+ const haystack = [
84
+ item && item.name,
85
+ item && item.state,
86
+ raw.model,
87
+ raw.modelName,
88
+ raw.type
89
+ ].map(function (value) { return String(value || "").toLowerCase(); }).join(" ");
90
+ return /dream|gateway|\budm\b|\buxg\b|\bucg\b|\bugw\b|cloud ?key|\buck\b|console/.test(haystack);
91
+ }
92
+
93
+ function updateSelectedCount() {
94
+ const total = $("#unifi-restart-device-list input[type='checkbox']").length;
95
+ const checked = $("#unifi-restart-device-list input[type='checkbox']:checked").length;
96
+ $count.text(checked + " / " + total + " selected");
97
+ }
98
+
99
+ function renderDevices(items) {
100
+ const storedIds = parseStoredIds();
101
+ const hasStoredSelection = storedIds.length > 0;
102
+ const storedSet = {};
103
+ storedIds.forEach(function (id) { storedSet[id] = true; });
104
+
105
+ $list.empty();
106
+
107
+ if (!Array.isArray(items) || items.length === 0) {
108
+ $list.append($("<div class='unifi-restart-empty'></div>").text("No UniFi Network devices found."));
109
+ updateSelectedCount();
110
+ return;
111
+ }
112
+
113
+ items
114
+ .slice()
115
+ .sort(function (a, b) {
116
+ return String(a.name || a.id).localeCompare(String(b.name || b.id));
117
+ })
118
+ .forEach(function (item) {
119
+ const id = String(item.id || "").trim();
120
+ if (!id) {
121
+ return;
122
+ }
123
+ const name = String(item.name || id).trim();
124
+ const model = String(item.state || "").trim();
125
+ const checked = hasStoredSelection ? Boolean(storedSet[id]) : !isGatewayLike(item);
126
+
127
+ const $row = $("<label class='unifi-restart-device-row'></label>");
128
+ const $checkbox = $("<input type='checkbox'>")
129
+ .attr("data-id", id)
130
+ .attr("data-name", name)
131
+ .prop("checked", checked);
132
+ $checkbox.on("change", updateSelectedCount);
133
+
134
+ $row.append($checkbox);
135
+ $row.append($("<span class='unifi-restart-device-name'></span>").text(name));
136
+ if (model) {
137
+ $row.append($("<span class='unifi-restart-device-model'></span>").text(model));
138
+ }
139
+ $list.append($row);
140
+ });
141
+
142
+ applyFilter();
143
+ updateSelectedCount();
144
+ }
145
+
146
+ function applyFilter() {
147
+ const term = String($filter.val() || "").trim().toLowerCase();
148
+ $("#unifi-restart-device-list .unifi-restart-device-row").each(function () {
149
+ const text = String($(this).text() || "").toLowerCase();
150
+ $(this).toggle(term === "" || text.indexOf(term) !== -1);
151
+ });
152
+ }
153
+
154
+ function loadDevices(force) {
155
+ const serverId = String($server.val() || "").trim();
156
+ if (!serverId || serverId === "_ADD_") {
157
+ $list.empty();
158
+ $status.text("");
159
+ updateSelectedCount();
160
+ return Promise.resolve();
161
+ }
162
+
163
+ if (!force && serverId === loadedServerId && loadingPromise) {
164
+ return loadingPromise;
165
+ }
166
+
167
+ $status.text("Loading devices...");
168
+ loadedServerId = serverId;
169
+ loadingPromise = requestJson("unifiNetwork/devices?serverId=" + encodeURIComponent(serverId) + "&deviceType=device")
170
+ .then(function (devices) {
171
+ renderDevices(devices);
172
+ $status.text("");
173
+ })
174
+ .catch(function (xhr) {
175
+ $list.empty();
176
+ const message = xhr && xhr.responseJSON && xhr.responseJSON.error
177
+ ? xhr.responseJSON.error
178
+ : "Unable to load devices.";
179
+ $status.text(message);
180
+ updateSelectedCount();
181
+ });
182
+ return loadingPromise;
183
+ }
184
+
185
+ function syncRows() {
186
+ $listRow.toggle(hasSelection($server));
187
+ }
188
+
189
+ // Wire up controls.
190
+ $operation.val(this.operation || "restartDevices");
191
+
192
+ $filter.on("input", applyFilter);
193
+
194
+ $("#unifi-restart-select-all").on("click", function (event) {
195
+ event.preventDefault();
196
+ $("#unifi-restart-device-list .unifi-restart-device-row:visible input[type='checkbox']").prop("checked", true);
197
+ updateSelectedCount();
198
+ });
199
+
200
+ $("#unifi-restart-select-none").on("click", function (event) {
201
+ event.preventDefault();
202
+ $("#unifi-restart-device-list .unifi-restart-device-row:visible input[type='checkbox']").prop("checked", false);
203
+ updateSelectedCount();
204
+ });
205
+
206
+ $refresh.on("click", function (event) {
207
+ event.preventDefault();
208
+ loadDevices(true);
209
+ });
210
+
211
+ $server.on("change", function () {
212
+ syncRows();
213
+ loadDevices(false);
214
+ });
215
+
216
+ syncRows();
217
+ loadDevices(false);
218
+ }
219
+ });
220
+ </script>
221
+
222
+ <script type="text/html" data-template-name="unifi-network-restart">
223
+ <div class="form-row unifi-ultimate-product-logo-row">
224
+ <img class="unifi-ultimate-product-logo" src="resources/node-red-contrib-unifi-ultimate/logos/unifi-network-black.svg" alt="UniFi Network logo" onerror="this.closest('.unifi-ultimate-product-logo-row').style.display='none';">
225
+ </div>
226
+ <div class="form-row">
227
+ <label for="node-input-server"><i class="fa fa-cog"></i> Connection</label>
228
+ <input type="text" id="node-input-server">
229
+ </div>
230
+ <div class="form-row">
231
+ <label for="node-input-operation"><i class="fa fa-power-off"></i> Operation</label>
232
+ <select id="node-input-operation">
233
+ <option value="restartDevices">Restart devices</option>
234
+ <option value="powerCyclePoe">Power cycle PoE ports</option>
235
+ </select>
236
+ </div>
237
+ <div class="form-row" id="node-row-deviceList" style="display:none;">
238
+ <label style="vertical-align:top;"><i class="fa fa-list"></i> Devices</label>
239
+ <div class="unifi-restart-device-panel">
240
+ <div class="unifi-restart-toolbar">
241
+ <input type="text" id="unifi-restart-filter" placeholder="Filter devices...">
242
+ <a href="#" id="unifi-restart-select-all" class="editor-button">All</a>
243
+ <a href="#" id="unifi-restart-select-none" class="editor-button">None</a>
244
+ <a href="#" id="node-input-refreshDevices" class="editor-button" title="Reload devices" aria-label="Reload devices"><i class="fa fa-refresh"></i></a>
245
+ </div>
246
+ <div id="unifi-restart-device-list" class="unifi-restart-device-list"></div>
247
+ <div class="unifi-restart-list-footer">
248
+ <span id="unifi-restart-selected-count">0 / 0 selected</span>
249
+ <span id="unifi-restart-list-status" class="unifi-restart-list-status"></span>
250
+ </div>
251
+ </div>
252
+ </div>
253
+ <div class="form-row">
254
+ <div class="unifi-ultimate-card unifi-ultimate-warning">
255
+ <strong>This action is disruptive.</strong>
256
+ <div><b>Restart devices</b> reboots every selected switch/AP. <b>Power cycle PoE ports</b> drops power on each active PoE port of the selected switches, disconnecting attached devices.</div>
257
+ </div>
258
+ </div>
259
+ <div class="form-row">
260
+ <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
261
+ <input type="text" id="node-input-name" placeholder="Node name">
262
+ </div>
263
+ <input type="hidden" id="node-input-deviceIds">
264
+ <input type="hidden" id="node-input-deviceNames">
265
+ </script>
266
+
267
+ <script type="text/html" data-help-name="unifi-network-restart">
268
+ <p>Restarts a list of UniFi Network devices, or power-cycles their PoE ports, in a single batch.</p>
269
+
270
+ <h3>Configuration</h3>
271
+ <p><b>Connection</b> selects the shared UniFi Network config node.</p>
272
+ <p><b>Operation</b> chooses one of two mutually exclusive actions:</p>
273
+ <ul>
274
+ <li><code>Restart devices</code> — reboots each selected device (UniFi <code>RESTART</code> action).</li>
275
+ <li><code>Power cycle PoE ports</code> — power-cycles every port currently delivering PoE on each selected device (UniFi <code>POWER_CYCLE</code> action). Devices with no active PoE ports are skipped.</li>
276
+ </ul>
277
+ <p><b>Devices</b> lists every adopted UniFi Network device. By default switches and access points are pre-selected; gateways, consoles and cloud keys are listed but unchecked. Add or remove devices freely — the selection is saved with the node. Use <code>All</code>/<code>None</code> and the filter box to manage long lists.</p>
278
+
279
+ <h3>Input</h3>
280
+ <ul>
281
+ <li>Any incoming message triggers the configured operation on the saved device list.</li>
282
+ <li>Input message properties are ignored.</li>
283
+ </ul>
284
+
285
+ <h3>Outputs</h3>
286
+ <dl class="message-properties">
287
+ <dt>Output 1 — result</dt>
288
+ <dd>A single summary message emitted after the whole batch completes.</dd>
289
+ <dt class="optional">msg.payload.operation</dt>
290
+ <dd><code>restartDevices</code> or <code>powerCyclePoe</code>.</dd>
291
+ <dt class="optional">msg.payload.total / succeeded / failed</dt>
292
+ <dd>Counts across all selected devices.</dd>
293
+ <dt class="optional">msg.payload.results</dt>
294
+ <dd>Per-device outcome (<code>ok</code>, device name, site/resource ids, errors). For PoE mode each entry also includes the per-port results.</dd>
295
+ <dt class="optional">msg.topic</dt>
296
+ <dd>Node name from the editor.</dd>
297
+ </dl>
298
+ <dl class="message-properties">
299
+ <dt>Output 2 — error</dt>
300
+ <dd>Emitted only on a setup failure (missing config or empty device selection). Per-device API errors are reported inside the Output 1 summary, not here.</dd>
301
+ </dl>
302
+ </script>
303
+
304
+ <style>
305
+ .unifi-restart-device-panel {
306
+ display: inline-block;
307
+ width: 70%;
308
+ vertical-align: top;
309
+ }
310
+ .unifi-restart-toolbar {
311
+ display: flex;
312
+ gap: 6px;
313
+ align-items: center;
314
+ margin-bottom: 6px;
315
+ }
316
+ .unifi-restart-toolbar #unifi-restart-filter {
317
+ flex: 1 1 auto;
318
+ min-width: 0;
319
+ }
320
+ .unifi-restart-device-list {
321
+ max-height: 220px;
322
+ overflow-y: auto;
323
+ border: 1px solid var(--red-ui-form-input-border-color, #ccc);
324
+ border-radius: 4px;
325
+ padding: 4px 6px;
326
+ background: var(--red-ui-form-input-background, #fff);
327
+ }
328
+ /* Node-RED styles every `.form-row label` as a fixed-width inline-block,
329
+ which would tile our rows into a grid. Override it explicitly. */
330
+ #unifi-restart-device-list .unifi-restart-device-row {
331
+ display: flex !important;
332
+ align-items: center;
333
+ gap: 8px;
334
+ width: 100% !important;
335
+ margin: 0 !important;
336
+ padding: 3px 2px;
337
+ font-weight: normal;
338
+ cursor: pointer;
339
+ box-sizing: border-box;
340
+ vertical-align: top;
341
+ }
342
+ #unifi-restart-device-list .unifi-restart-device-row input[type='checkbox'] {
343
+ margin: 0 !important;
344
+ width: auto !important;
345
+ flex: 0 0 auto;
346
+ }
347
+ #unifi-restart-device-list .unifi-restart-device-name {
348
+ flex: 1 1 auto;
349
+ overflow: hidden;
350
+ text-overflow: ellipsis;
351
+ white-space: nowrap;
352
+ }
353
+ #unifi-restart-device-list .unifi-restart-device-model {
354
+ flex: 0 0 auto;
355
+ opacity: 0.6;
356
+ font-size: 0.85em;
357
+ white-space: nowrap;
358
+ }
359
+ .unifi-restart-list-footer {
360
+ display: flex;
361
+ justify-content: space-between;
362
+ margin-top: 4px;
363
+ font-size: 0.85em;
364
+ opacity: 0.8;
365
+ }
366
+ .unifi-restart-list-status {
367
+ color: var(--red-ui-text-color-error, #b30000);
368
+ }
369
+ .unifi-restart-empty {
370
+ opacity: 0.6;
371
+ padding: 6px 2px;
372
+ }
373
+ </style>
@@ -0,0 +1,381 @@
1
+ "use strict";
2
+
3
+ const {
4
+ resolveScopedIdentifiers
5
+ } = require("./utils/unifi-network-device-registry");
6
+ const {
7
+ appendStatusTimestamp,
8
+ resolveNodeName,
9
+ attachDetails,
10
+ buildErrorOutputMessage
11
+ } = require("./utils/common-utils");
12
+
13
+ const DEFAULT_REQUEST_TIMEOUT_MS = 15000;
14
+ // Cap parallel requests so a large fleet does not flood the controller while
15
+ // still finishing the batch faster than a strictly sequential loop.
16
+ const DEFAULT_CONCURRENCY = 4;
17
+
18
+ function normalizeString(value) {
19
+ return String(value || "").trim();
20
+ }
21
+
22
+ function parseDeviceIds(value) {
23
+ // The editor stores the selection as a JSON array string, but tolerate an
24
+ // already-parsed array or a comma separated fallback for hand edits.
25
+ if (Array.isArray(value)) {
26
+ return value.map(normalizeString).filter(Boolean);
27
+ }
28
+
29
+ const raw = normalizeString(value);
30
+ if (!raw) {
31
+ return [];
32
+ }
33
+
34
+ try {
35
+ const parsed = JSON.parse(raw);
36
+ if (Array.isArray(parsed)) {
37
+ return parsed.map(normalizeString).filter(Boolean);
38
+ }
39
+ } catch (error) {
40
+ // Not JSON: fall back to a comma separated list.
41
+ }
42
+
43
+ return raw.split(",").map(normalizeString).filter(Boolean);
44
+ }
45
+
46
+ function parseDeviceNames(value) {
47
+ if (value && typeof value === "object" && !Array.isArray(value)) {
48
+ return value;
49
+ }
50
+
51
+ const raw = normalizeString(value);
52
+ if (!raw) {
53
+ return {};
54
+ }
55
+
56
+ try {
57
+ const parsed = JSON.parse(raw);
58
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
59
+ } catch (error) {
60
+ return {};
61
+ }
62
+ }
63
+
64
+ function resolveOperation(value) {
65
+ const normalized = normalizeString(value).toLowerCase();
66
+ if (["powercyclepoe", "powercycle", "poe", "power_cycle_poe"].includes(normalized)) {
67
+ return "powerCyclePoe";
68
+ }
69
+ return "restartDevices";
70
+ }
71
+
72
+ async function runWithConcurrency(items, limit, worker) {
73
+ const results = new Array(items.length);
74
+ let cursor = 0;
75
+
76
+ async function pump() {
77
+ while (cursor < items.length) {
78
+ const index = cursor;
79
+ cursor += 1;
80
+ results[index] = await worker(items[index], index);
81
+ }
82
+ }
83
+
84
+ const runners = [];
85
+ const runnerCount = Math.max(1, Math.min(limit, items.length));
86
+ for (let i = 0; i < runnerCount; i += 1) {
87
+ runners.push(pump());
88
+ }
89
+
90
+ await Promise.all(runners);
91
+ return results;
92
+ }
93
+
94
+ module.exports = function(RED) {
95
+ function UnifiNetworkRestartNode(config) {
96
+ RED.nodes.createNode(this, config);
97
+
98
+ const node = this;
99
+ node.name = config.name;
100
+ node.server = RED.nodes.getNode(config.server);
101
+ node.operation = resolveOperation(config.operation);
102
+ node.deviceIds = parseDeviceIds(config.deviceIds);
103
+ node.deviceNames = parseDeviceNames(config.deviceNames);
104
+ node.timeout = DEFAULT_REQUEST_TIMEOUT_MS;
105
+
106
+ function setNodeStatus(status) {
107
+ if (!status || typeof status !== "object" || Array.isArray(status)) {
108
+ return;
109
+ }
110
+ node.status({
111
+ ...status,
112
+ text: appendStatusTimestamp(status.text)
113
+ });
114
+ }
115
+
116
+ function resolveDeviceLabel(deviceId, scoped) {
117
+ const stored = normalizeString(node.deviceNames && node.deviceNames[deviceId]);
118
+ if (stored) {
119
+ return stored;
120
+ }
121
+ return normalizeString(scoped && scoped.resourceId) || deviceId;
122
+ }
123
+
124
+ function buildScopeError(deviceId) {
125
+ return {
126
+ deviceId,
127
+ deviceName: normalizeString(node.deviceNames && node.deviceNames[deviceId]) || deviceId,
128
+ ok: false,
129
+ error: "Device selection is invalid. Re-open the node and re-select the device."
130
+ };
131
+ }
132
+
133
+ async function restartDevice(deviceId) {
134
+ const scoped = resolveScopedIdentifiers("device", deviceId);
135
+ if (!scoped.siteId || !scoped.resourceId) {
136
+ return buildScopeError(deviceId);
137
+ }
138
+
139
+ const deviceName = resolveDeviceLabel(deviceId, scoped);
140
+ const path = `/v1/sites/${encodeURIComponent(scoped.siteId)}/devices/${encodeURIComponent(scoped.resourceId)}/actions`;
141
+
142
+ try {
143
+ const response = await node.server.executeNetworkRequest({
144
+ path,
145
+ method: "POST",
146
+ payload: { action: "RESTART" },
147
+ timeout: node.timeout
148
+ });
149
+
150
+ if (response.statusCode < 200 || response.statusCode >= 300) {
151
+ return {
152
+ deviceId,
153
+ deviceName,
154
+ siteId: scoped.siteId,
155
+ resourceId: scoped.resourceId,
156
+ action: "RESTART",
157
+ ok: false,
158
+ statusCode: response.statusCode,
159
+ error: `Restart request failed (${response.statusCode}).`
160
+ };
161
+ }
162
+
163
+ return {
164
+ deviceId,
165
+ deviceName,
166
+ siteId: scoped.siteId,
167
+ resourceId: scoped.resourceId,
168
+ action: "RESTART",
169
+ ok: true,
170
+ statusCode: response.statusCode
171
+ };
172
+ } catch (error) {
173
+ return {
174
+ deviceId,
175
+ deviceName,
176
+ siteId: scoped.siteId,
177
+ resourceId: scoped.resourceId,
178
+ action: "RESTART",
179
+ ok: false,
180
+ error: String(error && error.message ? error.message : error)
181
+ };
182
+ }
183
+ }
184
+
185
+ async function resolvePoePorts(deviceId) {
186
+ if (typeof node.server.fetchDevicePortsPowerLite !== "function") {
187
+ return [];
188
+ }
189
+ const ports = await node.server.fetchDevicePortsPowerLite(deviceId);
190
+ if (!Array.isArray(ports)) {
191
+ return [];
192
+ }
193
+ // A power cycle only makes sense on ports actively delivering PoE.
194
+ return ports.filter((port) => normalizeString(port && port.poeEnabled).toLowerCase() === "on");
195
+ }
196
+
197
+ async function powerCycleDevicePorts(deviceId) {
198
+ const scoped = resolveScopedIdentifiers("device", deviceId);
199
+ if (!scoped.siteId || !scoped.resourceId) {
200
+ return buildScopeError(deviceId);
201
+ }
202
+
203
+ const deviceName = resolveDeviceLabel(deviceId, scoped);
204
+ const base = {
205
+ deviceId,
206
+ deviceName,
207
+ siteId: scoped.siteId,
208
+ resourceId: scoped.resourceId,
209
+ action: "POWER_CYCLE"
210
+ };
211
+
212
+ let poePorts;
213
+ try {
214
+ poePorts = await resolvePoePorts(deviceId);
215
+ } catch (error) {
216
+ return {
217
+ ...base,
218
+ ok: false,
219
+ error: `Unable to read PoE ports: ${String(error && error.message ? error.message : error)}`
220
+ };
221
+ }
222
+
223
+ if (poePorts.length === 0) {
224
+ return {
225
+ ...base,
226
+ ok: true,
227
+ skipped: true,
228
+ portsCycled: 0,
229
+ ports: [],
230
+ note: "No PoE ports actively delivering power."
231
+ };
232
+ }
233
+
234
+ const portResults = [];
235
+ for (const port of poePorts) {
236
+ const portIdx = Number(port.idx);
237
+ const path = `/v1/sites/${encodeURIComponent(scoped.siteId)}/devices/${encodeURIComponent(scoped.resourceId)}/interfaces/ports/${encodeURIComponent(String(portIdx))}/actions`;
238
+ try {
239
+ const response = await node.server.executeNetworkRequest({
240
+ path,
241
+ method: "POST",
242
+ payload: { action: "POWER_CYCLE" },
243
+ timeout: node.timeout
244
+ });
245
+
246
+ const ok = response.statusCode >= 200 && response.statusCode < 300;
247
+ portResults.push({
248
+ portIdx,
249
+ portName: normalizeString(port.name) || `Port ${portIdx}`,
250
+ ok,
251
+ statusCode: response.statusCode,
252
+ error: ok ? undefined : `Power cycle failed (${response.statusCode}).`
253
+ });
254
+ } catch (error) {
255
+ portResults.push({
256
+ portIdx,
257
+ portName: normalizeString(port.name) || `Port ${portIdx}`,
258
+ ok: false,
259
+ error: String(error && error.message ? error.message : error)
260
+ });
261
+ }
262
+ }
263
+
264
+ const failedPorts = portResults.filter((entry) => !entry.ok);
265
+ return {
266
+ ...base,
267
+ ok: failedPorts.length === 0,
268
+ portsCycled: portResults.length - failedPorts.length,
269
+ portsFailed: failedPorts.length,
270
+ ports: portResults,
271
+ error: failedPorts.length > 0
272
+ ? `${failedPorts.length} of ${portResults.length} port(s) failed.`
273
+ : undefined
274
+ };
275
+ }
276
+
277
+ function refreshProgressStatus(done, total) {
278
+ const label = node.operation === "powerCyclePoe" ? "power cycle" : "restart";
279
+ setNodeStatus({
280
+ fill: "blue",
281
+ shape: "dot",
282
+ text: `${label} ${done}/${total}`
283
+ });
284
+ }
285
+
286
+ async function invoke(send) {
287
+ if (!node.server) {
288
+ throw new Error("Unifi Network configuration is missing.");
289
+ }
290
+ if (typeof node.server.executeNetworkRequest !== "function") {
291
+ throw new Error("This node requires the UniFi Network configuration helper.");
292
+ }
293
+ if (!Array.isArray(node.deviceIds) || node.deviceIds.length === 0) {
294
+ throw new Error("No devices selected. Open the node and choose at least one device.");
295
+ }
296
+
297
+ const total = node.deviceIds.length;
298
+ let completed = 0;
299
+ refreshProgressStatus(0, total);
300
+
301
+ const worker = node.operation === "powerCyclePoe"
302
+ ? powerCycleDevicePorts
303
+ : restartDevice;
304
+
305
+ const results = await runWithConcurrency(node.deviceIds, DEFAULT_CONCURRENCY, async (deviceId) => {
306
+ const result = await worker(deviceId);
307
+ completed += 1;
308
+ refreshProgressStatus(completed, total);
309
+ return result;
310
+ });
311
+
312
+ const succeeded = results.filter((entry) => entry && entry.ok).length;
313
+ const failed = results.length - succeeded;
314
+ const nodeName = resolveNodeName(node.name);
315
+
316
+ const output = {
317
+ topic: nodeName || undefined,
318
+ eventName: node.operation,
319
+ payload: {
320
+ operation: node.operation,
321
+ total: results.length,
322
+ succeeded,
323
+ failed,
324
+ results
325
+ }
326
+ };
327
+ attachDetails(output, {
328
+ unifiNetworkRestart: {
329
+ nodeType: "network-restart",
330
+ name: nodeName || undefined,
331
+ operation: node.operation,
332
+ total: results.length,
333
+ succeeded,
334
+ failed
335
+ }
336
+ });
337
+
338
+ if (failed === 0) {
339
+ setNodeStatus({ fill: "green", shape: "dot", text: `${succeeded}/${results.length} ok` });
340
+ } else if (succeeded === 0) {
341
+ setNodeStatus({ fill: "red", shape: "ring", text: `0/${results.length} ok` });
342
+ } else {
343
+ setNodeStatus({ fill: "yellow", shape: "ring", text: `${succeeded}/${results.length} ok` });
344
+ }
345
+
346
+ send([output, null]);
347
+ }
348
+
349
+ node.on("input", async function(msg, send, done) {
350
+ send = send || function() {
351
+ node.send.apply(node, arguments);
352
+ };
353
+
354
+ try {
355
+ await invoke(send);
356
+ if (typeof done === "function") {
357
+ done();
358
+ }
359
+ } catch (error) {
360
+ setNodeStatus({ fill: "red", shape: "ring", text: "error" });
361
+ node.send([null, buildErrorOutputMessage(error, node.name)]);
362
+ if (typeof done === "function") {
363
+ done(error);
364
+ } else {
365
+ node.error(error);
366
+ }
367
+ }
368
+ });
369
+
370
+ if (!node.server) {
371
+ setNodeStatus({ fill: "red", shape: "ring", text: "no config" });
372
+ } else if (!Array.isArray(node.deviceIds) || node.deviceIds.length === 0) {
373
+ setNodeStatus({ fill: "grey", shape: "ring", text: "select devices" });
374
+ } else {
375
+ const label = node.operation === "powerCyclePoe" ? "power cycle" : "restart";
376
+ setNodeStatus({ fill: "grey", shape: "ring", text: `ready (${node.deviceIds.length} ${label})` });
377
+ }
378
+ }
379
+
380
+ RED.nodes.registerType("unifi-network-restart", UnifiNetworkRestartNode);
381
+ };
@@ -679,7 +679,17 @@ function summarizeDevice(deviceType, device) {
679
679
  || item.status === "OFFLINE"
680
680
  || item.status === "offline"
681
681
  || String(item.state || "").trim().toLowerCase() === "offline";
682
- const clientName = stripOfflineTag(String(item.hostname || item.name || item.displayName || item.macAddress || resourceId || "Client"));
682
+ // Prefer the user-defined alias (e.g. "iPhone di Massimo") over the
683
+ // device-reported hostname, matching the legacy known-client summary.
684
+ const clientName = stripOfflineTag(String(
685
+ item.name
686
+ || item.displayName
687
+ || item.display_name
688
+ || item.hostname
689
+ || item.macAddress
690
+ || resourceId
691
+ || "Client"
692
+ ));
683
693
 
684
694
  return {
685
695
  id: scopedId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-red-contrib-unifi-ultimate",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "Node-RED nodes for Ubiquiti UniFi integrations, including UniFi Protect, UniFi Access, and UniFi Network.",
5
5
  "files": [
6
6
  "nodes/",
@@ -41,12 +41,13 @@
41
41
  "unifi-network-config": "nodes/unifi-network-config.js",
42
42
  "unifi-network-device": "nodes/unifi-network-device.js",
43
43
  "unifi-network-presence": "nodes/unifi-network-presence.js",
44
+ "unifi-network-restart": "nodes/unifi-network-restart.js",
44
45
  "unifi-protect-config": "nodes/unifi-protect-config.js",
45
46
  "unifi-protect-device": "nodes/unifi-protect-device.js"
46
47
  }
47
48
  },
48
49
  "scripts": {
49
- "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
50
+ "test": "node --check nodes/unifi-access-config.js && node --check nodes/unifi-access-device.js && node --check nodes/unifi-network-config.js && node --check nodes/unifi-network-control-poe.js && node --check nodes/unifi-network-device.js && node --check nodes/unifi-network-presence.js && node --check nodes/unifi-network-restart.js && node --check nodes/unifi-protect-config.js && node --check nodes/unifi-protect-device.js && node --check nodes/utils/common-utils.js && node --check nodes/utils/http-response-utils.js && node --check nodes/utils/unifi-access-utils.js && node --check nodes/utils/unifi-access-device-registry.js && node --check nodes/utils/unifi-network-utils.js && node --check nodes/utils/unifi-network-device-registry.js && node --check nodes/utils/unifi-protect-utils.js && node --check nodes/utils/unifi-protect-field-metadata.js && node --check nodes/utils/unifi-protect-device-registry.js && node --check scripts/unifi-registry-discovery-common.js && node --check scripts/discover-unifi-network-registry.js && node --check scripts/discover-unifi-protect-registry.js && node --check scripts/discover-unifi-access-registry.js && jest",
50
51
  "registry:discover:network": "node scripts/discover-unifi-network-registry.js",
51
52
  "registry:discover:protect": "node scripts/discover-unifi-protect-registry.js",
52
53
  "registry:discover:access": "node scripts/discover-unifi-access-registry.js"