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