node-red-contrib-unifi-ultimate 0.1.0-beta.1

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.
@@ -0,0 +1,316 @@
1
+ "use strict";
2
+
3
+ const {
4
+ getDeviceTypeDefinition,
5
+ getCapabilityDefinition,
6
+ buildCapabilityRequest,
7
+ composeCapabilityExecution,
8
+ resolveObservableState,
9
+ resolveObservableEventValue
10
+ } = require("./utils/unifi-protect-device-registry");
11
+
12
+ function resolveDeviceType(configuredDeviceType, msg) {
13
+ return String(msg.deviceType || configuredDeviceType || "").trim();
14
+ }
15
+
16
+ function resolveDeviceId(configuredDeviceId, msg) {
17
+ return String(msg.deviceId || msg.resourceId || configuredDeviceId || "").trim();
18
+ }
19
+
20
+ function resolveCapabilityId(configuredCapabilityId, msg) {
21
+ return String(msg.capability || configuredCapabilityId || "observe").trim();
22
+ }
23
+
24
+ function parseCapabilityConfig(value) {
25
+ if (value && typeof value === "object" && !Array.isArray(value)) {
26
+ return value;
27
+ }
28
+
29
+ if (typeof value !== "string" || value.trim() === "") {
30
+ return {};
31
+ }
32
+
33
+ try {
34
+ const parsed = JSON.parse(value);
35
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
36
+ ? parsed
37
+ : {};
38
+ } catch (error) {
39
+ return {};
40
+ }
41
+ }
42
+
43
+ function resolveCapabilityConfig(configuredCapabilityConfig, msg) {
44
+ if (msg && msg.capabilityConfig && typeof msg.capabilityConfig === "object" && !Array.isArray(msg.capabilityConfig)) {
45
+ return msg.capabilityConfig;
46
+ }
47
+
48
+ return parseCapabilityConfig(configuredCapabilityConfig);
49
+ }
50
+
51
+ function buildNodeStatus(deviceType, payload) {
52
+ const label = payload && payload.name ? payload.name : deviceType;
53
+ const state = payload && payload.state ? payload.state : "ready";
54
+ return `${label} ${state}`;
55
+ }
56
+
57
+ module.exports = function(RED) {
58
+ function UnifiProtectDeviceNode(config) {
59
+ RED.nodes.createNode(this, config);
60
+
61
+ const node = this;
62
+ node.name = config.name;
63
+ node.server = RED.nodes.getNode(config.server);
64
+ node.deviceType = config.deviceType || "";
65
+ node.deviceId = config.deviceId || "";
66
+ node.capability = config.capability || "observe";
67
+ node.capabilityConfig = config.capabilityConfig || "{}";
68
+ node.timeout = Number(config.timeout) > 0 ? Number(config.timeout) : 15000;
69
+ node.currentDevice = null;
70
+ node.currentObservableValue = false;
71
+ node.isObserving = false;
72
+
73
+ function sendOutputs(send, stateMsg, eventMsg) {
74
+ send([stateMsg || null, eventMsg || null]);
75
+ }
76
+
77
+ function buildBaseMetadata(deviceType, deviceId, capabilityId, extra) {
78
+ return {
79
+ nodeType: "device",
80
+ deviceType,
81
+ deviceId,
82
+ capability: capabilityId,
83
+ ...(extra || {})
84
+ };
85
+ }
86
+
87
+ function buildObservedStateMessage(deviceType, deviceId, capabilityConfig, payload, source, extra) {
88
+ const observable = String(capabilityConfig.observable || "").trim();
89
+ if (observable) {
90
+ const observableValue = resolveObservableState(deviceType, payload, observable, node.currentObservableValue);
91
+ node.currentObservableValue = Boolean(observableValue);
92
+
93
+ return {
94
+ payload: node.currentObservableValue,
95
+ RAW: {
96
+ device: payload,
97
+ observable,
98
+ source: source || "observe",
99
+ ...(extra || {})
100
+ },
101
+ device: payload,
102
+ unifiProtect: buildBaseMetadata(deviceType, deviceId, "observe", {
103
+ source: source || "observe",
104
+ observable,
105
+ ...(extra || {})
106
+ })
107
+ };
108
+ }
109
+
110
+ return {
111
+ payload,
112
+ device: payload,
113
+ unifiProtect: buildBaseMetadata(deviceType, deviceId, "observe", { source: source || "observe", ...(extra || {}) })
114
+ };
115
+ }
116
+
117
+ async function fetchDeviceState(deviceType, deviceId, capabilityConfig, send, source) {
118
+ const payload = await node.server.fetchDeviceByTypeAndId(deviceType, deviceId);
119
+ node.currentDevice = payload;
120
+
121
+ const stateMsg = buildObservedStateMessage(deviceType, deviceId, capabilityConfig, payload, source);
122
+
123
+ node.status({ fill: "green", shape: "dot", text: buildNodeStatus(deviceType, payload) });
124
+ sendOutputs(send, stateMsg, null);
125
+ }
126
+
127
+ async function invokeCapability(msg, send) {
128
+ if (!node.server) {
129
+ throw new Error("Unifi Protect configuration is missing.");
130
+ }
131
+
132
+ const deviceType = resolveDeviceType(node.deviceType, msg);
133
+ const deviceId = resolveDeviceId(node.deviceId, msg);
134
+ const capabilityId = resolveCapabilityId(node.capability, msg);
135
+ const capabilityConfig = resolveCapabilityConfig(node.capabilityConfig, msg);
136
+ if (!getDeviceTypeDefinition(deviceType)) {
137
+ throw new Error(`Unsupported device type: ${deviceType || "(empty)"}`);
138
+ }
139
+
140
+ const capability = getCapabilityDefinition(deviceType, capabilityId);
141
+ if (!capability) {
142
+ throw new Error(`Unsupported capability '${capabilityId}' for device type '${deviceType}'.`);
143
+ }
144
+
145
+ if (capability.mode === "observe") {
146
+ await fetchDeviceState(deviceType, deviceId, capabilityConfig, send, "manual-refresh");
147
+ return;
148
+ }
149
+
150
+ const execution = composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, msg);
151
+ const request = buildCapabilityRequest(deviceType, capabilityId, deviceId, execution.params);
152
+
153
+ node.status({ fill: "blue", shape: "dot", text: `${capability.label}` });
154
+
155
+ const response = await node.server.apiRequest({
156
+ path: request.path,
157
+ method: request.method,
158
+ query: execution.query,
159
+ headers: execution.headers,
160
+ payload: execution.payload,
161
+ timeout: node.timeout
162
+ });
163
+
164
+ if (response.statusCode < 200 || response.statusCode >= 300) {
165
+ node.status({ fill: "yellow", shape: "ring", text: `${response.statusCode}` });
166
+ throw new Error(`UniFi Protect request failed with status ${response.statusCode}`);
167
+ }
168
+
169
+ if (response.payload && typeof response.payload === "object" && !Array.isArray(response.payload)) {
170
+ node.currentDevice = response.payload;
171
+ }
172
+
173
+ const stateMsg = RED.util.cloneMessage(msg);
174
+ stateMsg.payload = response.payload;
175
+ stateMsg.statusCode = response.statusCode;
176
+ stateMsg.headers = response.headers;
177
+ stateMsg.device = node.currentDevice;
178
+ stateMsg.unifiProtect = buildBaseMetadata(deviceType, deviceId, capabilityId, {
179
+ source: "request",
180
+ method: request.method,
181
+ path: request.path,
182
+ capabilityConfig
183
+ });
184
+
185
+ node.status({ fill: "green", shape: "dot", text: `${capability.label}` });
186
+ sendOutputs(send, stateMsg, null);
187
+ }
188
+
189
+ function shouldObserveConfiguredDevice() {
190
+ return node.server && node.capability === "observe" && node.deviceType && node.deviceId;
191
+ }
192
+
193
+ function startObservation() {
194
+ if (!shouldObserveConfiguredDevice() || node.isObserving) {
195
+ return;
196
+ }
197
+
198
+ node.server.removeClient(node);
199
+ node.server.addClient(node);
200
+ node.isObserving = true;
201
+
202
+ fetchDeviceState(node.deviceType, node.deviceId, parseCapabilityConfig(node.capabilityConfig), node.send.bind(node), "startup").catch(() => {
203
+ });
204
+ }
205
+
206
+ node.on("input", async function(msg, send, done) {
207
+ send = send || function() {
208
+ node.send.apply(node, arguments);
209
+ };
210
+
211
+ try {
212
+ await invokeCapability(msg, send);
213
+ done();
214
+ } catch (error) {
215
+ node.status({ fill: "red", shape: "ring", text: "error" });
216
+ done(error);
217
+ }
218
+ });
219
+
220
+ node.handleProtectDeviceUpdate = (update) => {
221
+ try {
222
+ const item = update && update.item;
223
+ if (!item || !node.isObserving) {
224
+ return;
225
+ }
226
+
227
+ const deviceDefinition = getDeviceTypeDefinition(node.deviceType);
228
+ if (!deviceDefinition || item.modelKey !== deviceDefinition.modelKey || item.id !== node.deviceId) {
229
+ return;
230
+ }
231
+
232
+ node.currentDevice = item;
233
+ const capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
234
+ node.status({ fill: "green", shape: "dot", text: buildNodeStatus(node.deviceType, item) });
235
+ sendOutputs(node.send.bind(node), buildObservedStateMessage(
236
+ node.deviceType,
237
+ node.deviceId,
238
+ capabilityConfig,
239
+ item,
240
+ "devices",
241
+ { updateType: update.type || "" }
242
+ ), null);
243
+ } catch (error) {
244
+ }
245
+ };
246
+
247
+ node.handleProtectEventUpdate = (update) => {
248
+ try {
249
+ const item = update && update.item;
250
+ if (!item || item.modelKey !== "event" || !node.isObserving || item.device !== node.deviceId) {
251
+ return;
252
+ }
253
+
254
+ const capabilityConfig = parseCapabilityConfig(node.capabilityConfig);
255
+ const observable = String(capabilityConfig.observable || "").trim();
256
+ if (observable) {
257
+ const observation = resolveObservableEventValue(node.deviceType, item, observable);
258
+ if (observation.matched) {
259
+ node.currentObservableValue = Boolean(observation.value);
260
+ node.status({ fill: "blue", shape: "ring", text: `${item.type || "event"}` });
261
+ sendOutputs(node.send.bind(node), {
262
+ payload: node.currentObservableValue,
263
+ RAW: {
264
+ device: node.currentDevice,
265
+ event: item,
266
+ observable,
267
+ source: "events"
268
+ },
269
+ device: node.currentDevice,
270
+ unifiProtect: buildBaseMetadata(node.deviceType, node.deviceId, "observe", {
271
+ source: "events",
272
+ observable,
273
+ eventType: item.type || "",
274
+ updateType: update.type || ""
275
+ })
276
+ }, null);
277
+ return;
278
+ }
279
+ }
280
+
281
+ node.status({ fill: "blue", shape: "ring", text: `${item.type || "event"}` });
282
+ sendOutputs(node.send.bind(node), null, {
283
+ payload: {
284
+ device: node.currentDevice,
285
+ event: item
286
+ },
287
+ device: node.currentDevice,
288
+ unifiProtect: buildBaseMetadata(node.deviceType, node.deviceId, "observe", {
289
+ source: "events",
290
+ eventType: item.type || "",
291
+ updateType: update.type || ""
292
+ })
293
+ });
294
+ } catch (error) {
295
+ }
296
+ };
297
+
298
+ if (!node.server) {
299
+ node.status({ fill: "red", shape: "ring", text: "config missing" });
300
+ } else if (node.capability === "observe" && (!node.deviceType || !node.deviceId)) {
301
+ node.status({ fill: "yellow", shape: "ring", text: "select device" });
302
+ } else {
303
+ startObservation();
304
+ }
305
+
306
+ node.on("close", function(done) {
307
+ if (node.server && typeof node.server.removeClient === "function") {
308
+ node.server.removeClient(node);
309
+ }
310
+ node.isObserving = false;
311
+ done();
312
+ });
313
+ }
314
+
315
+ RED.nodes.registerType("unifi-protect-device", UnifiProtectDeviceNode);
316
+ };