|
Bogdan Timofte
authored
2 weeks ago
|
1
|
module.exports = function(RED) {
|
|
|
2
|
function Z2MSmartSocketHomeBusNode(config) {
|
|
|
3
|
RED.nodes.createNode(this, config);
|
|
|
4
|
var node = this;
|
|
|
5
|
|
|
|
6
|
node.adapterId = "z2m-smart-socket-homebus";
|
|
|
7
|
node.site = normalizeToken(config.site || config.mqttSite || "");
|
|
|
8
|
node.sourceModels = ["A1Z", "S60ZBTPF"];
|
|
|
9
|
node.sourceTopics = node.sourceModels.map(function(model) { return "zigbee2mqtt/" + model + "/#"; });
|
|
|
10
|
node.subscriptionStarted = false;
|
|
|
11
|
node.startTimer = null;
|
|
|
12
|
node.publishCache = Object.create(null);
|
|
|
13
|
node.retainedCache = Object.create(null);
|
|
|
14
|
node.deviceRegistry = Object.create(null);
|
|
|
15
|
node.statsPublishEvery = 25;
|
|
|
16
|
|
|
|
17
|
node.stats = {
|
|
|
18
|
processed_inputs: 0,
|
|
|
19
|
raw_inputs: 0,
|
|
|
20
|
command_inputs: 0,
|
|
|
21
|
devices_detected: 0,
|
|
|
22
|
home_messages: 0,
|
|
|
23
|
last_messages: 0,
|
|
|
24
|
meta_messages: 0,
|
|
|
25
|
home_availability_messages: 0,
|
|
|
26
|
raw_command_messages: 0,
|
|
|
27
|
operational_messages: 0,
|
|
|
28
|
invalid_messages: 0,
|
|
|
29
|
invalid_topics: 0,
|
|
|
30
|
invalid_payloads: 0,
|
|
|
31
|
unmapped_messages: 0,
|
|
|
32
|
unknown_devices: 0,
|
|
|
33
|
errors: 0,
|
|
|
34
|
dlq: 0
|
|
|
35
|
};
|
|
|
36
|
|
|
|
37
|
var HOME_MAPPINGS = [
|
|
|
38
|
{
|
|
|
39
|
targetCapability: "power",
|
|
|
40
|
core: true,
|
|
|
41
|
writable: true,
|
|
|
42
|
payloadProfile: "scalar",
|
|
|
43
|
dataType: "boolean",
|
|
|
44
|
historianMode: "state",
|
|
|
45
|
historianEnabled: true,
|
|
|
46
|
read: function(payload) {
|
|
|
47
|
var value = asSwitchState(payload.state);
|
|
|
48
|
return value === null ? undefined : value;
|
|
|
49
|
}
|
|
|
50
|
},
|
|
|
51
|
{
|
|
|
52
|
targetCapability: "power_restore_mode",
|
|
|
53
|
core: true,
|
|
|
54
|
payloadProfile: "scalar",
|
|
|
55
|
dataType: "string",
|
|
|
56
|
historianMode: "state",
|
|
|
57
|
historianEnabled: true,
|
|
|
58
|
read: function(payload, model) {
|
|
|
59
|
var raw = null;
|
|
|
60
|
if (model === "A1Z") raw = asLowerEnum(payload.power_outage_memory);
|
|
|
61
|
else if (model === "S60ZBTPF") raw = asLowerEnum(payload.power_on_behavior);
|
|
|
62
|
if (!raw) return undefined;
|
|
|
63
|
if (raw === "restore") return "previous";
|
|
|
64
|
return raw;
|
|
|
65
|
}
|
|
|
66
|
},
|
|
|
67
|
{
|
|
|
68
|
models: ["A1Z"],
|
|
|
69
|
targetCapability: "countdown",
|
|
|
70
|
core: false,
|
|
|
71
|
payloadProfile: "scalar",
|
|
|
72
|
dataType: "number",
|
|
|
73
|
unit: "s",
|
|
|
74
|
precision: 1,
|
|
|
75
|
historianMode: "sample",
|
|
|
76
|
historianEnabled: true,
|
|
|
77
|
read: function(payload) {
|
|
|
78
|
var value = asNumber(payload.countdown);
|
|
|
79
|
return value === null ? undefined : value;
|
|
|
80
|
}
|
|
|
81
|
},
|
|
|
82
|
{
|
|
|
83
|
models: ["A1Z"],
|
|
|
84
|
targetCapability: "lock",
|
|
|
85
|
core: false,
|
|
|
86
|
payloadProfile: "scalar",
|
|
|
87
|
dataType: "boolean",
|
|
|
88
|
historianMode: "state",
|
|
|
89
|
historianEnabled: true,
|
|
|
90
|
read: function(payload) {
|
|
|
91
|
var value = asLockState(payload.child_lock);
|
|
|
92
|
return value === null ? undefined : value;
|
|
|
93
|
}
|
|
|
94
|
},
|
|
|
95
|
{
|
|
|
96
|
models: ["A1Z"],
|
|
|
97
|
targetCapability: "indicator_mode",
|
|
|
98
|
core: false,
|
|
|
99
|
payloadProfile: "scalar",
|
|
|
100
|
dataType: "string",
|
|
|
101
|
historianMode: "state",
|
|
|
102
|
historianEnabled: true,
|
|
|
103
|
read: function(payload) {
|
|
|
104
|
var value = asLowerEnum(payload.indicator_mode);
|
|
|
105
|
return value || undefined;
|
|
|
106
|
}
|
|
|
107
|
},
|
|
|
108
|
{
|
|
|
109
|
models: ["A1Z"],
|
|
|
110
|
targetCapability: "button_mode",
|
|
|
111
|
core: false,
|
|
|
112
|
payloadProfile: "scalar",
|
|
|
113
|
dataType: "string",
|
|
|
114
|
historianMode: "state",
|
|
|
115
|
historianEnabled: true,
|
|
|
116
|
read: function(payload) {
|
|
|
117
|
var value = asLowerEnum(payload.switch_type_button);
|
|
|
118
|
return value || undefined;
|
|
|
119
|
}
|
|
|
120
|
},
|
|
|
121
|
{
|
|
|
122
|
models: ["S60ZBTPF"],
|
|
|
123
|
targetCapability: "protection_enabled",
|
|
|
124
|
core: false,
|
|
|
125
|
payloadProfile: "scalar",
|
|
|
126
|
dataType: "boolean",
|
|
|
127
|
historianMode: "state",
|
|
|
128
|
historianEnabled: true,
|
|
|
129
|
read: function(payload) {
|
|
|
130
|
var value = asBool(payload.outlet_control_protect);
|
|
|
131
|
return value === null ? undefined : value;
|
|
|
132
|
}
|
|
|
133
|
}
|
|
|
134
|
];
|
|
|
135
|
|
|
|
136
|
function normalizeToken(value) {
|
|
|
137
|
if (value === undefined || value === null) return "";
|
|
|
138
|
return String(value).trim();
|
|
|
139
|
}
|
|
|
140
|
|
|
|
141
|
function transliterate(value) {
|
|
|
142
|
var s = normalizeToken(value);
|
|
|
143
|
if (!s) return "";
|
|
|
144
|
if (typeof s.normalize === "function") {
|
|
|
145
|
s = s.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
|
|
|
146
|
}
|
|
|
147
|
return s;
|
|
|
148
|
}
|
|
|
149
|
|
|
|
150
|
function toKebabCase(value, fallback) {
|
|
|
151
|
var s = transliterate(value).toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
|
152
|
s = s.replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-");
|
|
|
153
|
return s || fallback || "";
|
|
|
154
|
}
|
|
|
155
|
|
|
|
156
|
function humanizeCapability(capability) {
|
|
|
157
|
return String(capability || "").replace(/_/g, " ").replace(/\b[a-z]/g, function(ch) { return ch.toUpperCase(); });
|
|
|
158
|
}
|
|
|
159
|
|
|
|
160
|
function asBool(value) {
|
|
|
161
|
if (typeof value === "boolean") return value;
|
|
|
162
|
if (typeof value === "number") return value !== 0;
|
|
|
163
|
if (typeof value === "string") {
|
|
|
164
|
var v = value.trim().toLowerCase();
|
|
|
165
|
if (v === "true" || v === "1" || v === "on" || v === "yes" || v === "online" || v === "lock" || v === "locked") return true;
|
|
|
166
|
if (v === "false" || v === "0" || v === "off" || v === "no" || v === "offline" || v === "unlock" || v === "unlocked") return false;
|
|
|
167
|
}
|
|
|
168
|
return null;
|
|
|
169
|
}
|
|
|
170
|
|
|
|
171
|
function asNumber(value) {
|
|
|
172
|
if (typeof value === "number" && isFinite(value)) return value;
|
|
|
173
|
if (typeof value === "string") {
|
|
|
174
|
var trimmed = value.trim();
|
|
|
175
|
if (!trimmed) return null;
|
|
|
176
|
var parsed = Number(trimmed);
|
|
|
177
|
if (isFinite(parsed)) return parsed;
|
|
|
178
|
}
|
|
|
179
|
return null;
|
|
|
180
|
}
|
|
|
181
|
|
|
|
182
|
function asLowerEnum(value) {
|
|
|
183
|
var s = normalizeToken(value).toLowerCase();
|
|
|
184
|
return s || null;
|
|
|
185
|
}
|
|
|
186
|
|
|
|
187
|
function asSwitchState(value) {
|
|
|
188
|
if (typeof value === "boolean") return value;
|
|
|
189
|
if (typeof value === "number") return value !== 0;
|
|
|
190
|
if (typeof value === "string") {
|
|
|
191
|
var v = value.trim().toLowerCase();
|
|
|
192
|
if (v === "on" || v === "true" || v === "1") return true;
|
|
|
193
|
if (v === "off" || v === "false" || v === "0") return false;
|
|
|
194
|
}
|
|
|
195
|
return null;
|
|
|
196
|
}
|
|
|
197
|
|
|
|
198
|
function asLockState(value) {
|
|
|
199
|
if (typeof value === "string") {
|
|
|
200
|
var v = value.trim().toLowerCase();
|
|
|
201
|
if (v === "lock" || v === "locked") return true;
|
|
|
202
|
if (v === "unlock" || v === "unlocked") return false;
|
|
|
203
|
}
|
|
|
204
|
return asBool(value);
|
|
|
205
|
}
|
|
|
206
|
|
|
|
207
|
function toIsoTimestamp(value) {
|
|
|
208
|
if (value === undefined || value === null || value === "") return "";
|
|
|
209
|
var parsed = new Date(value);
|
|
|
210
|
if (isNaN(parsed.getTime())) return "";
|
|
|
211
|
return parsed.toISOString();
|
|
|
212
|
}
|
|
|
213
|
|
|
|
214
|
function resolveObservation(msg, payloadObject) {
|
|
|
215
|
var observedAt = "";
|
|
|
216
|
if (payloadObject && typeof payloadObject === "object") {
|
|
|
217
|
observedAt = toIsoTimestamp(payloadObject.observed_at)
|
|
|
218
|
|| toIsoTimestamp(payloadObject.observedAt)
|
|
|
219
|
|| toIsoTimestamp(payloadObject.timestamp)
|
|
|
220
|
|| toIsoTimestamp(payloadObject.time)
|
|
|
221
|
|| toIsoTimestamp(payloadObject.ts)
|
|
|
222
|
|| toIsoTimestamp(payloadObject.last_seen);
|
|
|
223
|
}
|
|
|
224
|
|
|
|
225
|
if (!observedAt && msg && typeof msg === "object") {
|
|
|
226
|
observedAt = toIsoTimestamp(msg.observed_at)
|
|
|
227
|
|| toIsoTimestamp(msg.observedAt)
|
|
|
228
|
|| toIsoTimestamp(msg.timestamp)
|
|
|
229
|
|| toIsoTimestamp(msg.time)
|
|
|
230
|
|| toIsoTimestamp(msg.ts);
|
|
|
231
|
}
|
|
|
232
|
|
|
|
233
|
if (observedAt) {
|
|
|
234
|
return {
|
|
|
235
|
observedAt: observedAt,
|
|
|
236
|
quality: "good"
|
|
|
237
|
};
|
|
|
238
|
}
|
|
|
239
|
|
|
|
240
|
return {
|
|
|
241
|
observedAt: new Date().toISOString(),
|
|
|
242
|
quality: "estimated"
|
|
|
243
|
};
|
|
|
244
|
}
|
|
|
245
|
|
|
|
246
|
function supportsModel(mapping, model) {
|
|
|
247
|
if (!mapping.models || !mapping.models.length) return true;
|
|
|
248
|
return mapping.models.indexOf(model) >= 0;
|
|
|
249
|
}
|
|
|
250
|
|
|
|
251
|
function registryKey(site, location, deviceId) {
|
|
|
252
|
return [site || "", location || "", deviceId || ""].join("|");
|
|
|
253
|
}
|
|
|
254
|
|
|
|
255
|
function translatedMessageCount() {
|
|
|
256
|
return node.stats.home_messages
|
|
|
257
|
+ node.stats.last_messages
|
|
|
258
|
+ node.stats.meta_messages
|
|
|
259
|
+ node.stats.home_availability_messages
|
|
|
260
|
+ node.stats.raw_command_messages;
|
|
|
261
|
}
|
|
|
262
|
|
|
|
263
|
function makePublishMsg(topic, payload, retain) {
|
|
|
264
|
return {
|
|
|
265
|
topic: topic,
|
|
|
266
|
payload: payload,
|
|
|
267
|
qos: 1,
|
|
|
268
|
retain: !!retain
|
|
|
269
|
};
|
|
|
270
|
}
|
|
|
271
|
|
|
|
272
|
function makeSubscribeMsg(topic) {
|
|
|
273
|
return {
|
|
|
274
|
action: "subscribe",
|
|
|
275
|
topic: topic,
|
|
|
276
|
qos: 2,
|
|
|
277
|
rh: 0,
|
|
|
278
|
rap: true
|
|
|
279
|
};
|
|
|
280
|
}
|
|
|
281
|
|
|
|
282
|
function buildHomeTopic(identity, mapping, stream) {
|
|
|
283
|
return identity.site + "/home/" + identity.location + "/" + mapping.targetCapability + "/" + identity.deviceId + "/" + stream;
|
|
|
284
|
}
|
|
|
285
|
|
|
|
286
|
function buildSysTopic(site, stream) {
|
|
|
287
|
return site + "/sys/adapter/" + node.adapterId + "/" + stream;
|
|
|
288
|
}
|
|
|
289
|
|
|
|
290
|
function signature(value) {
|
|
|
291
|
return JSON.stringify(value);
|
|
|
292
|
}
|
|
|
293
|
|
|
|
294
|
function shouldPublishLive(cacheKey, payload) {
|
|
|
295
|
var sig = signature(payload);
|
|
|
296
|
if (node.publishCache[cacheKey] === sig) return false;
|
|
|
297
|
node.publishCache[cacheKey] = sig;
|
|
|
298
|
return true;
|
|
|
299
|
}
|
|
|
300
|
|
|
|
301
|
function shouldPublishRetained(cacheKey, payload) {
|
|
|
302
|
var sig = signature(payload);
|
|
|
303
|
if (node.retainedCache[cacheKey] === sig) return false;
|
|
|
304
|
node.retainedCache[cacheKey] = sig;
|
|
|
305
|
return true;
|
|
|
306
|
}
|
|
|
307
|
|
|
|
308
|
function buildLastPayload(value, observation) {
|
|
|
309
|
var payload = {
|
|
|
310
|
value: value,
|
|
|
311
|
observed_at: observation.observedAt
|
|
|
312
|
};
|
|
|
313
|
if (observation.quality && observation.quality !== "good") payload.quality = observation.quality;
|
|
|
314
|
return payload;
|
|
|
315
|
}
|
|
|
316
|
|
|
|
317
|
function buildMetaPayload(identity, mapping) {
|
|
|
318
|
var payload = {
|
|
|
319
|
schema_ref: "mqbus.home.v1",
|
|
|
320
|
payload_profile: mapping.payloadProfile || "scalar",
|
|
|
321
|
stream_payload_profiles: mapping.writable
|
|
|
322
|
? { value: "scalar", last: "envelope", set: "scalar" }
|
|
|
323
|
: { value: "scalar", last: "envelope" },
|
|
|
324
|
data_type: mapping.dataType,
|
|
|
325
|
adapter_id: node.adapterId,
|
|
|
326
|
source: "zigbee2mqtt",
|
|
|
327
|
source_ref: identity.sourceRef,
|
|
|
328
|
source_topic: identity.sourceTopic,
|
|
|
329
|
display_name: identity.displayName + " " + humanizeCapability(mapping.targetCapability),
|
|
|
330
|
tags: ["zigbee2mqtt", "smart-socket", identity.model.toLowerCase(), "home"],
|
|
|
331
|
historian: {
|
|
|
332
|
enabled: !!mapping.historianEnabled,
|
|
|
333
|
mode: mapping.historianMode
|
|
|
334
|
}
|
|
|
335
|
};
|
|
|
336
|
|
|
|
337
|
if (mapping.unit) payload.unit = mapping.unit;
|
|
|
338
|
if (mapping.precision !== undefined) payload.precision = mapping.precision;
|
|
|
339
|
if (mapping.writable) {
|
|
|
340
|
payload.writable = true;
|
|
|
341
|
payload.set_topic = buildHomeTopic(identity, mapping, "set");
|
|
|
342
|
}
|
|
|
343
|
|
|
|
344
|
return payload;
|
|
|
345
|
}
|
|
|
346
|
|
|
|
347
|
function enqueueHomeMeta(messages, identity, mapping) {
|
|
|
348
|
var topic = buildHomeTopic(identity, mapping, "meta");
|
|
|
349
|
var payload = buildMetaPayload(identity, mapping);
|
|
|
350
|
if (!shouldPublishRetained("meta:" + topic, payload)) return;
|
|
|
351
|
messages.push(makePublishMsg(topic, payload, true));
|
|
|
352
|
noteMessage("meta_messages");
|
|
|
353
|
}
|
|
|
354
|
|
|
|
355
|
function enqueueHomeAvailability(messages, identity, mapping, online) {
|
|
|
356
|
var topic = buildHomeTopic(identity, mapping, "availability");
|
|
|
357
|
var payload = online ? "online" : "offline";
|
|
|
358
|
if (!shouldPublishRetained("availability:" + topic, payload)) return;
|
|
|
359
|
messages.push(makePublishMsg(topic, payload, true));
|
|
|
360
|
noteMessage("home_availability_messages");
|
|
|
361
|
}
|
|
|
362
|
|
|
|
363
|
function enqueueHomeLast(messages, identity, mapping, value, observation) {
|
|
|
364
|
var topic = buildHomeTopic(identity, mapping, "last");
|
|
|
365
|
var payload = buildLastPayload(value, observation);
|
|
|
366
|
if (!shouldPublishRetained("last:" + topic, payload)) return;
|
|
|
367
|
messages.push(makePublishMsg(topic, payload, true));
|
|
|
368
|
noteMessage("last_messages");
|
|
|
369
|
}
|
|
|
370
|
|
|
|
371
|
function enqueueHomeValue(messages, identity, mapping, value) {
|
|
|
372
|
var topic = buildHomeTopic(identity, mapping, "value");
|
|
|
373
|
if (!shouldPublishLive("value:" + topic, value)) return;
|
|
|
374
|
messages.push(makePublishMsg(topic, value, false));
|
|
|
375
|
noteMessage("home_messages");
|
|
|
376
|
}
|
|
|
377
|
|
|
|
378
|
function enqueueAdapterAvailability(messages, site, online) {
|
|
|
379
|
var topic = buildSysTopic(site, "availability");
|
|
|
380
|
var payload = online ? "online" : "offline";
|
|
|
381
|
if (!shouldPublishRetained("sys:availability:" + topic, payload)) return;
|
|
|
382
|
messages.push(makePublishMsg(topic, payload, true));
|
|
|
383
|
noteMessage("operational_messages");
|
|
|
384
|
}
|
|
|
385
|
|
|
|
386
|
function enqueueAdapterStats(messages, site, force) {
|
|
|
387
|
if (!force && node.stats.processed_inputs !== 1 && (node.stats.processed_inputs % node.statsPublishEvery) !== 0) return;
|
|
|
388
|
var topic = buildSysTopic(site, "stats");
|
|
|
389
|
var payload = {
|
|
|
390
|
processed_inputs: node.stats.processed_inputs,
|
|
|
391
|
raw_inputs: node.stats.raw_inputs,
|
|
|
392
|
command_inputs: node.stats.command_inputs,
|
|
|
393
|
devices_detected: node.stats.devices_detected,
|
|
|
394
|
translated_messages: translatedMessageCount(),
|
|
|
395
|
home_messages: node.stats.home_messages,
|
|
|
396
|
last_messages: node.stats.last_messages,
|
|
|
397
|
meta_messages: node.stats.meta_messages,
|
|
|
398
|
home_availability_messages: node.stats.home_availability_messages,
|
|
|
399
|
raw_command_messages: node.stats.raw_command_messages,
|
|
|
400
|
operational_messages: node.stats.operational_messages,
|
|
|
401
|
invalid_messages: node.stats.invalid_messages,
|
|
|
402
|
invalid_topics: node.stats.invalid_topics,
|
|
|
403
|
invalid_payloads: node.stats.invalid_payloads,
|
|
|
404
|
unmapped_messages: node.stats.unmapped_messages,
|
|
|
405
|
unknown_devices: node.stats.unknown_devices,
|
|
|
406
|
errors: node.stats.errors,
|
|
|
407
|
dlq: node.stats.dlq
|
|
|
408
|
};
|
|
|
409
|
messages.push(makePublishMsg(topic, payload, true));
|
|
|
410
|
noteMessage("operational_messages");
|
|
|
411
|
}
|
|
|
412
|
|
|
|
413
|
function enqueueError(messages, site, code, reason, sourceTopic) {
|
|
|
414
|
var payload = {
|
|
|
415
|
code: code,
|
|
|
416
|
reason: reason,
|
|
|
417
|
source_topic: normalizeToken(sourceTopic),
|
|
|
418
|
adapter_id: node.adapterId
|
|
|
419
|
};
|
|
|
420
|
messages.push(makePublishMsg(buildSysTopic(site, "error"), payload, false));
|
|
|
421
|
if (code === "invalid_message") noteMessage("invalid_messages");
|
|
|
422
|
else if (code === "invalid_topic" || code === "unsupported_set") noteMessage("invalid_topics");
|
|
|
423
|
else if (code === "payload_not_object" || code === "invalid_availability_payload" || code === "invalid_command_payload") noteMessage("invalid_payloads");
|
|
|
424
|
else if (code === "no_mapped_fields") noteMessage("unmapped_messages");
|
|
|
425
|
else if (code === "unknown_device") noteMessage("unknown_devices");
|
|
|
426
|
noteMessage("errors");
|
|
|
427
|
noteMessage("operational_messages");
|
|
|
428
|
}
|
|
|
429
|
|
|
|
430
|
function enqueueDlq(messages, site, code, sourceTopic, rawPayload) {
|
|
|
431
|
var payload = {
|
|
|
432
|
code: code,
|
|
|
433
|
source_topic: normalizeToken(sourceTopic),
|
|
|
434
|
payload: rawPayload
|
|
|
435
|
};
|
|
|
436
|
messages.push(makePublishMsg(buildSysTopic(site, "dlq"), payload, false));
|
|
|
437
|
noteMessage("dlq");
|
|
|
438
|
noteMessage("operational_messages");
|
|
|
439
|
}
|
|
|
440
|
|
|
|
441
|
function noteMessage(kind) {
|
|
|
442
|
if (Object.prototype.hasOwnProperty.call(node.stats, kind)) {
|
|
|
443
|
node.stats[kind] += 1;
|
|
|
444
|
}
|
|
|
445
|
}
|
|
|
446
|
|
|
|
447
|
function summarizeForLog(value) {
|
|
|
448
|
if (value === undefined) return "undefined";
|
|
|
449
|
if (value === null) return "null";
|
|
|
450
|
if (typeof value === "string") return value.length > 180 ? value.slice(0, 177) + "..." : value;
|
|
|
451
|
try {
|
|
|
452
|
var serialized = JSON.stringify(value);
|
|
|
453
|
return serialized.length > 180 ? serialized.slice(0, 177) + "..." : serialized;
|
|
|
454
|
} catch (err) {
|
|
|
455
|
return String(value);
|
|
|
456
|
}
|
|
|
457
|
}
|
|
|
458
|
|
|
|
459
|
function logIssue(level, code, reason, msg, rawPayload) {
|
|
|
460
|
var parts = ["[" + node.adapterId + "]", code + ":", reason];
|
|
|
461
|
if (msg && typeof msg === "object" && normalizeToken(msg.topic)) {
|
|
|
462
|
parts.push("topic=" + normalizeToken(msg.topic));
|
|
|
463
|
}
|
|
|
464
|
if (rawPayload !== undefined) {
|
|
|
465
|
parts.push("payload=" + summarizeForLog(rawPayload));
|
|
|
466
|
}
|
|
|
467
|
var text = parts.join(" ");
|
|
|
468
|
if (level === "error") {
|
|
|
469
|
node.error(text, msg);
|
|
|
470
|
} else {
|
|
|
471
|
node.warn(text);
|
|
|
472
|
}
|
|
|
473
|
}
|
|
|
474
|
|
|
|
475
|
function parseRawTopic(topic) {
|
|
|
476
|
if (typeof topic !== "string") return null;
|
|
|
477
|
var tokens = topic.split("/").map(function(token) { return token.trim(); }).filter(function(token) { return !!token; });
|
|
|
478
|
if (tokens.length !== 5 && tokens.length !== 6) return null;
|
|
|
479
|
if (tokens[0].toLowerCase() !== "zigbee2mqtt") return null;
|
|
|
480
|
if (node.sourceModels.indexOf(tokens[1]) < 0) return null;
|
|
|
481
|
if (tokens.length === 6 && tokens[5].toLowerCase() !== "availability") return null;
|
|
|
482
|
return {
|
|
|
483
|
model: tokens[1],
|
|
|
484
|
site: toKebabCase(tokens[2], node.site || "unknown"),
|
|
|
485
|
location: toKebabCase(tokens[3], "unknown"),
|
|
|
486
|
deviceId: toKebabCase(tokens[4], tokens[1].toLowerCase()),
|
|
|
487
|
sourceTopic: tokens.slice(0, 5).join("/"),
|
|
|
488
|
availabilityTopic: tokens.length === 6
|
|
|
489
|
};
|
|
|
490
|
}
|
|
|
491
|
|
|
|
492
|
function parseSetTopic(topic) {
|
|
|
493
|
if (typeof topic !== "string") return null;
|
|
|
494
|
var tokens = topic.split("/").map(function(token) { return token.trim(); }).filter(function(token) { return !!token; });
|
|
|
495
|
if (tokens.length !== 6) return null;
|
|
|
496
|
if (tokens[1] !== "home") return null;
|
|
|
497
|
if (tokens[3] !== "power" || tokens[5] !== "set") return null;
|
|
|
498
|
return {
|
|
|
499
|
site: toKebabCase(tokens[0], node.site || "unknown"),
|
|
|
500
|
location: toKebabCase(tokens[2], "unknown"),
|
|
|
501
|
capability: tokens[3],
|
|
|
502
|
deviceId: toKebabCase(tokens[4], "socket")
|
|
|
503
|
};
|
|
|
504
|
}
|
|
|
505
|
|
|
|
506
|
function buildIdentity(parsed) {
|
|
|
507
|
return {
|
|
|
508
|
model: parsed.model,
|
|
|
509
|
site: parsed.site || node.site || "unknown",
|
|
|
510
|
location: parsed.location || "unknown",
|
|
|
511
|
deviceId: parsed.deviceId || parsed.model.toLowerCase(),
|
|
|
512
|
sourceRef: parsed.sourceTopic,
|
|
|
513
|
sourceTopic: parsed.sourceTopic,
|
|
|
514
|
displayName: [parsed.location || "unknown", parsed.deviceId || parsed.model.toLowerCase()].join(" ")
|
|
|
515
|
};
|
|
|
516
|
}
|
|
|
517
|
|
|
|
518
|
function noteDevice(identity) {
|
|
|
519
|
var key = registryKey(identity.site, identity.location, identity.deviceId);
|
|
|
520
|
if (!Object.prototype.hasOwnProperty.call(node.deviceRegistry, key)) {
|
|
|
521
|
node.stats.devices_detected += 1;
|
|
|
522
|
}
|
|
|
523
|
node.deviceRegistry[key] = {
|
|
|
524
|
site: identity.site,
|
|
|
525
|
location: identity.location,
|
|
|
526
|
deviceId: identity.deviceId,
|
|
|
527
|
model: identity.model,
|
|
|
528
|
sourceTopic: identity.sourceTopic,
|
|
|
529
|
sourceRef: identity.sourceRef
|
|
|
530
|
};
|
|
|
531
|
}
|
|
|
532
|
|
|
|
533
|
function lookupDevice(parsedSet) {
|
|
|
534
|
return node.deviceRegistry[registryKey(parsedSet.site, parsedSet.location, parsedSet.deviceId)] || null;
|
|
|
535
|
}
|
|
|
536
|
|
|
|
537
|
function activeMappings(model, payloadObject) {
|
|
|
538
|
var result = [];
|
|
|
539
|
for (var i = 0; i < HOME_MAPPINGS.length; i++) {
|
|
|
540
|
var mapping = HOME_MAPPINGS[i];
|
|
|
541
|
if (!supportsModel(mapping, model)) continue;
|
|
|
542
|
var value = payloadObject ? mapping.read(payloadObject, model) : undefined;
|
|
|
543
|
result.push({
|
|
|
544
|
mapping: mapping,
|
|
|
545
|
hasValue: value !== undefined,
|
|
|
546
|
value: value
|
|
|
547
|
});
|
|
|
548
|
}
|
|
|
549
|
return result;
|
|
|
550
|
}
|
|
|
551
|
|
|
|
552
|
function resolveOnlineState(payloadObject, availabilityValue) {
|
|
|
553
|
if (availabilityValue !== null && availabilityValue !== undefined) return !!availabilityValue;
|
|
|
554
|
if (!payloadObject) return true;
|
|
|
555
|
if (typeof payloadObject.availability === "string") {
|
|
|
556
|
return payloadObject.availability.trim().toLowerCase() !== "offline";
|
|
|
557
|
}
|
|
|
558
|
if (typeof payloadObject.online === "boolean") {
|
|
|
559
|
return payloadObject.online;
|
|
|
560
|
}
|
|
|
561
|
return true;
|
|
|
562
|
}
|
|
|
563
|
|
|
|
564
|
function housekeepingOnly(payloadObject) {
|
|
|
565
|
if (!payloadObject || typeof payloadObject !== "object") return false;
|
|
|
566
|
var keys = Object.keys(payloadObject);
|
|
|
567
|
if (!keys.length) return true;
|
|
|
568
|
for (var i = 0; i < keys.length; i++) {
|
|
|
569
|
if (["last_seen", "linkquality", "update", "availability", "online"].indexOf(keys[i]) < 0) return false;
|
|
|
570
|
}
|
|
|
571
|
return true;
|
|
|
572
|
}
|
|
|
573
|
|
|
|
574
|
function parsePowerCommand(payload) {
|
|
|
575
|
var value = payload;
|
|
|
576
|
var sourceTopicHint = "";
|
|
|
577
|
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
|
578
|
if (typeof value.source_topic === "string" && value.source_topic.trim()) sourceTopicHint = value.source_topic.trim();
|
|
|
579
|
else if (typeof value.source_ref === "string" && value.source_ref.trim()) sourceTopicHint = value.source_ref.trim();
|
|
|
580
|
if (Object.prototype.hasOwnProperty.call(value, "value")) value = value.value;
|
|
|
581
|
else if (Object.prototype.hasOwnProperty.call(value, "power")) value = value.power;
|
|
|
582
|
else if (Object.prototype.hasOwnProperty.call(value, "state")) value = value.state;
|
|
|
583
|
}
|
|
|
584
|
|
|
|
585
|
if (typeof value === "string" && value.trim().toLowerCase() === "toggle") {
|
|
|
586
|
return {
|
|
|
587
|
kind: "toggle",
|
|
|
588
|
sourceTopicHint: sourceTopicHint
|
|
|
589
|
};
|
|
|
590
|
}
|
|
|
591
|
|
|
|
592
|
var boolValue = asSwitchState(value);
|
|
|
593
|
if (boolValue === null) return null;
|
|
|
594
|
return {
|
|
|
595
|
kind: "state",
|
|
|
596
|
value: boolValue,
|
|
|
597
|
sourceTopicHint: sourceTopicHint
|
|
|
598
|
};
|
|
|
599
|
}
|
|
|
600
|
|
|
|
601
|
function statusText(prefix) {
|
|
|
602
|
return [
|
|
|
603
|
prefix || (node.subscriptionStarted ? "live" : "idle"),
|
|
|
604
|
"in:" + node.stats.processed_inputs,
|
|
|
605
|
"home:" + node.stats.home_messages,
|
|
|
606
|
"set:" + node.stats.raw_command_messages,
|
|
|
607
|
"err:" + node.stats.errors
|
|
|
608
|
].join(" ");
|
|
|
609
|
}
|
|
|
610
|
|
|
|
611
|
function updateNodeStatus(fill, shape, prefix) {
|
|
|
612
|
node.status({
|
|
|
613
|
fill: fill || (node.stats.errors ? "red" : "green"),
|
|
|
614
|
shape: shape || "dot",
|
|
|
615
|
text: statusText(prefix)
|
|
|
616
|
});
|
|
|
617
|
}
|
|
|
618
|
|
|
|
619
|
function flush(send, done, publishMessages, rawCommandMessages, controlMessages, error) {
|
|
|
620
|
send([
|
|
|
621
|
publishMessages.length ? publishMessages : null,
|
|
|
622
|
rawCommandMessages.length ? rawCommandMessages : null,
|
|
|
623
|
controlMessages.length ? controlMessages : null
|
|
|
624
|
]);
|
|
|
625
|
if (done) done(error);
|
|
|
626
|
}
|
|
|
627
|
|
|
|
628
|
function startSubscriptions() {
|
|
|
629
|
if (node.subscriptionStarted) return;
|
|
|
630
|
node.subscriptionStarted = true;
|
|
|
631
|
var controls = node.sourceTopics.map(function(topic) { return makeSubscribeMsg(topic); });
|
|
|
632
|
node.send([null, null, controls]);
|
|
|
633
|
updateNodeStatus("yellow", "dot", "subscribed");
|
|
|
634
|
}
|
|
|
635
|
|
|
|
636
|
node.on("input", function(msg, send, done) {
|
|
|
637
|
send = send || function() { node.send.apply(node, arguments); };
|
|
|
638
|
node.stats.processed_inputs += 1;
|
|
|
639
|
|
|
|
640
|
try {
|
|
|
641
|
if (!msg || typeof msg !== "object") {
|
|
|
642
|
var invalidMessages = [];
|
|
|
643
|
var invalidSite = node.site || "unknown";
|
|
|
644
|
enqueueAdapterAvailability(invalidMessages, invalidSite, true);
|
|
|
645
|
enqueueError(invalidMessages, invalidSite, "invalid_message", "Input must be an object", "");
|
|
|
646
|
enqueueDlq(invalidMessages, invalidSite, "invalid_message", "", null);
|
|
|
647
|
enqueueAdapterStats(invalidMessages, invalidSite, true);
|
|
|
648
|
logIssue("warn", "invalid_message", "Input must be an object", null, msg);
|
|
|
649
|
updateNodeStatus("yellow", "ring", "bad msg");
|
|
|
650
|
flush(send, done, invalidMessages, [], []);
|
|
|
651
|
return;
|
|
|
652
|
}
|
|
|
653
|
|
|
|
654
|
var publishMessages = [];
|
|
|
655
|
var rawCommandMessages = [];
|
|
|
656
|
var controlMessages = [];
|
|
|
657
|
var setTopic = parseSetTopic(msg.topic);
|
|
|
658
|
|
|
|
659
|
if (setTopic) {
|
|
|
660
|
node.stats.command_inputs += 1;
|
|
|
661
|
enqueueAdapterAvailability(publishMessages, setTopic.site, true);
|
|
|
662
|
|
|
|
663
|
var command = parsePowerCommand(msg.payload);
|
|
|
664
|
if (!command) {
|
|
|
665
|
enqueueError(publishMessages, setTopic.site, "invalid_command_payload", "Power set payload must be boolean, on/off, or toggle", msg.topic);
|
|
|
666
|
enqueueDlq(publishMessages, setTopic.site, "invalid_command_payload", msg.topic, msg.payload);
|
|
|
667
|
enqueueAdapterStats(publishMessages, setTopic.site, true);
|
|
|
668
|
logIssue("warn", "invalid_command_payload", "Power set payload must be boolean, on/off, or toggle", msg, msg.payload);
|
|
|
669
|
updateNodeStatus("yellow", "ring", "bad set");
|
|
|
670
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
671
|
return;
|
|
|
672
|
}
|
|
|
673
|
|
|
|
674
|
var registryEntry = lookupDevice(setTopic);
|
|
|
675
|
if (!registryEntry && command.sourceTopicHint) {
|
|
|
676
|
var hinted = parseRawTopic(command.sourceTopicHint);
|
|
|
677
|
if (hinted) {
|
|
|
678
|
registryEntry = {
|
|
|
679
|
site: hinted.site,
|
|
|
680
|
location: hinted.location,
|
|
|
681
|
deviceId: hinted.deviceId,
|
|
|
682
|
model: hinted.model,
|
|
|
683
|
sourceTopic: hinted.sourceTopic,
|
|
|
684
|
sourceRef: hinted.sourceTopic
|
|
|
685
|
};
|
|
|
686
|
}
|
|
|
687
|
}
|
|
|
688
|
|
|
|
689
|
if (!registryEntry) {
|
|
|
690
|
enqueueError(publishMessages, setTopic.site, "unknown_device", "No raw Zigbee2MQTT topic is known yet for this canonical power endpoint", msg.topic);
|
|
|
691
|
enqueueDlq(publishMessages, setTopic.site, "unknown_device", msg.topic, msg.payload);
|
|
|
692
|
enqueueAdapterStats(publishMessages, setTopic.site, true);
|
|
|
693
|
logIssue("warn", "unknown_device", "No raw Zigbee2MQTT topic is known yet for this canonical power endpoint", msg, msg.payload);
|
|
|
694
|
updateNodeStatus("yellow", "ring", "unknown device");
|
|
|
695
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
696
|
return;
|
|
|
697
|
}
|
|
|
698
|
|
|
|
699
|
rawCommandMessages.push(makePublishMsg(
|
|
|
700
|
registryEntry.sourceTopic + "/set",
|
|
|
701
|
command.kind === "toggle" ? { state: "TOGGLE" } : { state: command.value ? "ON" : "OFF" },
|
|
|
702
|
false
|
|
|
703
|
));
|
|
|
704
|
noteMessage("raw_command_messages");
|
|
|
705
|
enqueueAdapterStats(publishMessages, setTopic.site, false);
|
|
|
706
|
updateNodeStatus("green", "dot", "set->z2m");
|
|
|
707
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
708
|
return;
|
|
|
709
|
}
|
|
|
710
|
|
|
|
711
|
var parsed = parseRawTopic(msg.topic);
|
|
|
712
|
if (!parsed) {
|
|
|
713
|
var unknownSite = node.site || "unknown";
|
|
|
714
|
enqueueAdapterAvailability(publishMessages, unknownSite, true);
|
|
|
715
|
enqueueError(publishMessages, unknownSite, "invalid_topic", "Unsupported topic for smart socket homebus adapter", msg.topic);
|
|
|
716
|
enqueueDlq(publishMessages, unknownSite, "invalid_topic", msg.topic, msg.payload);
|
|
|
717
|
enqueueAdapterStats(publishMessages, unknownSite, true);
|
|
|
718
|
logIssue("warn", "invalid_topic", "Unsupported topic for smart socket homebus adapter", msg, msg.payload);
|
|
|
719
|
updateNodeStatus("yellow", "ring", "bad topic");
|
|
|
720
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
721
|
return;
|
|
|
722
|
}
|
|
|
723
|
|
|
|
724
|
node.stats.raw_inputs += 1;
|
|
|
725
|
var identity = buildIdentity(parsed);
|
|
|
726
|
noteDevice(identity);
|
|
|
727
|
enqueueAdapterAvailability(publishMessages, identity.site, true);
|
|
|
728
|
|
|
|
729
|
if (parsed.availabilityTopic) {
|
|
|
730
|
var availabilityValue = asBool(msg.payload);
|
|
|
731
|
if (availabilityValue === null) {
|
|
|
732
|
enqueueError(publishMessages, identity.site, "invalid_availability_payload", "Availability payload must be online/offline or boolean", msg.topic);
|
|
|
733
|
enqueueDlq(publishMessages, identity.site, "invalid_availability_payload", msg.topic, msg.payload);
|
|
|
734
|
enqueueAdapterStats(publishMessages, identity.site, true);
|
|
|
735
|
logIssue("warn", "invalid_availability_payload", "Availability payload must be online/offline or boolean", msg, msg.payload);
|
|
|
736
|
updateNodeStatus("yellow", "ring", "bad availability");
|
|
|
737
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
738
|
return;
|
|
|
739
|
}
|
|
|
740
|
|
|
|
741
|
var availabilityMappings = activeMappings(identity.model, null);
|
|
|
742
|
for (var i = 0; i < availabilityMappings.length; i++) {
|
|
|
743
|
enqueueHomeMeta(publishMessages, identity, availabilityMappings[i].mapping);
|
|
|
744
|
enqueueHomeAvailability(publishMessages, identity, availabilityMappings[i].mapping, availabilityValue);
|
|
|
745
|
}
|
|
|
746
|
|
|
|
747
|
enqueueAdapterStats(publishMessages, identity.site, false);
|
|
|
748
|
updateNodeStatus(availabilityValue ? "green" : "yellow", availabilityValue ? "dot" : "ring", availabilityValue ? "live" : "offline");
|
|
|
749
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
750
|
return;
|
|
|
751
|
}
|
|
|
752
|
|
|
|
753
|
var payloadObject = msg.payload && typeof msg.payload === "object" && !Array.isArray(msg.payload) ? msg.payload : null;
|
|
|
754
|
if (!payloadObject) {
|
|
|
755
|
enqueueError(publishMessages, identity.site, "payload_not_object", "Telemetry payload must be an object", msg.topic);
|
|
|
756
|
enqueueDlq(publishMessages, identity.site, "payload_not_object", msg.topic, msg.payload);
|
|
|
757
|
enqueueAdapterStats(publishMessages, identity.site, true);
|
|
|
758
|
logIssue("warn", "payload_not_object", "Telemetry payload must be an object", msg, msg.payload);
|
|
|
759
|
updateNodeStatus("yellow", "ring", "payload");
|
|
|
760
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
761
|
return;
|
|
|
762
|
}
|
|
|
763
|
|
|
|
764
|
var observation = resolveObservation(msg, payloadObject);
|
|
|
765
|
var online = resolveOnlineState(payloadObject, null);
|
|
|
766
|
var mappings = activeMappings(identity.model, payloadObject);
|
|
|
767
|
var hasMappedValue = false;
|
|
|
768
|
|
|
|
769
|
for (var j = 0; j < mappings.length; j++) {
|
|
|
770
|
enqueueHomeMeta(publishMessages, identity, mappings[j].mapping);
|
|
|
771
|
enqueueHomeAvailability(publishMessages, identity, mappings[j].mapping, online);
|
|
|
772
|
if (mappings[j].hasValue) {
|
|
|
773
|
hasMappedValue = true;
|
|
|
774
|
enqueueHomeLast(publishMessages, identity, mappings[j].mapping, mappings[j].value, observation);
|
|
|
775
|
enqueueHomeValue(publishMessages, identity, mappings[j].mapping, mappings[j].value);
|
|
|
776
|
}
|
|
|
777
|
}
|
|
|
778
|
|
|
|
779
|
if (!hasMappedValue && !housekeepingOnly(payloadObject)) {
|
|
|
780
|
enqueueError(publishMessages, identity.site, "no_mapped_fields", "Payload did not contain any supported smart socket HomeBus fields", msg.topic);
|
|
|
781
|
enqueueDlq(publishMessages, identity.site, "no_mapped_fields", msg.topic, payloadObject);
|
|
|
782
|
logIssue("warn", "no_mapped_fields", "Payload did not contain any supported smart socket HomeBus fields", msg, payloadObject);
|
|
|
783
|
}
|
|
|
784
|
|
|
|
785
|
enqueueAdapterStats(publishMessages, identity.site, false);
|
|
|
786
|
if (!hasMappedValue && !housekeepingOnly(payloadObject)) {
|
|
|
787
|
updateNodeStatus("yellow", "ring", "unmapped");
|
|
|
788
|
} else {
|
|
|
789
|
updateNodeStatus(online ? "green" : "yellow", online ? "dot" : "ring", online ? "live" : "offline");
|
|
|
790
|
}
|
|
|
791
|
flush(send, done, publishMessages, rawCommandMessages, controlMessages);
|
|
|
792
|
} catch (err) {
|
|
|
793
|
var site = node.site || "unknown";
|
|
|
794
|
var errorMessages = [];
|
|
|
795
|
enqueueAdapterAvailability(errorMessages, site, true);
|
|
|
796
|
enqueueError(errorMessages, site, "adapter_exception", err.message, msg && msg.topic);
|
|
|
797
|
enqueueAdapterStats(errorMessages, site, true);
|
|
|
798
|
logIssue("error", "adapter_exception", err.message, msg, msg && msg.payload);
|
|
|
799
|
updateNodeStatus("red", "ring", "error");
|
|
|
800
|
flush(send, done, errorMessages, [], [], err);
|
|
|
801
|
}
|
|
|
802
|
});
|
|
|
803
|
|
|
|
804
|
node.on("close", function() {
|
|
|
805
|
if (node.startTimer) {
|
|
|
806
|
clearTimeout(node.startTimer);
|
|
|
807
|
node.startTimer = null;
|
|
|
808
|
}
|
|
|
809
|
});
|
|
|
810
|
|
|
|
811
|
node.startTimer = setTimeout(startSubscriptions, 250);
|
|
|
812
|
updateNodeStatus("grey", "ring", "waiting");
|
|
|
813
|
}
|
|
|
814
|
|
|
|
815
|
RED.nodes.registerType("z2m-smart-socket-homebus", Z2MSmartSocketHomeBusNode);
|
|
|
816
|
};
|