Newer Older
535 lines | 19.638kb
Bogdan Timofte authored 2 weeks ago
1
module.exports = function(RED) {
2
  function Z2MSNZB04PHomeBusNode(config) {
3
    RED.nodes.createNode(this, config);
4
    var node = this;
5

            
6
    node.adapterId = "z2m-snzb-04p";
7
    node.sourceTopic = "zigbee2mqtt/SNZB-04P/#";
8
    node.subscriptionStarted = false;
9
    node.startTimer = null;
10
    node.site = normalizeToken(config.site || config.mqttSite);
11
    node.legacyRoom = normalizeToken(config.mqttRoom);
12
    node.legacySensor = normalizeToken(config.mqttSensor);
13
    node.publishCache = Object.create(null);
14
    node.retainedCache = Object.create(null);
15
    node.seenOptionalCapabilities = Object.create(null);
16
    node.detectedDevices = Object.create(null);
17
    node.stats = {
18
      processed_inputs: 0,
19
      devices_detected: 0,
20
      home_messages: 0,
21
      last_messages: 0,
22
      meta_messages: 0,
23
      home_availability_messages: 0,
24
      operational_messages: 0,
25
      invalid_messages: 0,
26
      invalid_topics: 0,
27
      invalid_payloads: 0,
28
      unmapped_messages: 0,
29
      adapter_exceptions: 0,
30
      errors: 0,
31
      dlq: 0
32
    };
33
    node.statsPublishEvery = 25;
34
    node.batteryLowThreshold = Number(config.batteryLowThreshold);
35
    if (!Number.isFinite(node.batteryLowThreshold)) node.batteryLowThreshold = 20;
36

            
37
    var CAPABILITY_MAPPINGS = [
38
      {
39
        sourceSystem: "zigbee2mqtt",
40
        sourceTopicMatch: "zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>",
41
        sourceFields: ["contact"],
42
        targetBus: "home",
43
        targetCapability: "contact",
44
        core: true,
45
        stream: "value",
46
        payloadProfile: "scalar",
47
        dataType: "boolean",
48
        historianMode: "state",
49
        historianEnabled: true,
50
        read: function(payload) {
51
          return readBool(payload, this.sourceFields);
52
        }
53
      },
54
      {
55
        sourceSystem: "zigbee2mqtt",
56
        sourceTopicMatch: "zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>",
57
        sourceFields: ["battery"],
58
        targetBus: "home",
59
        targetCapability: "battery",
60
        core: true,
61
        stream: "value",
62
        payloadProfile: "scalar",
63
        dataType: "number",
64
        unit: "%",
65
        precision: 1,
66
        historianMode: "sample",
67
        historianEnabled: true,
68
        read: function(payload) {
69
          var value = readNumber(payload, this.sourceFields[0]);
70
          if (value === undefined) return undefined;
71
          return clamp(Math.round(value), 0, 100);
72
        }
73
      },
74
      {
75
        sourceSystem: "zigbee2mqtt",
76
        sourceTopicMatch: "zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>",
77
        sourceFields: ["battery_low", "batteryLow", "battery"],
78
        targetBus: "home",
79
        targetCapability: "battery_low",
80
        core: true,
81
        stream: "value",
82
        payloadProfile: "scalar",
83
        dataType: "boolean",
84
        historianMode: "state",
85
        historianEnabled: true,
86
        read: function(payload) {
87
          var raw = readBool(payload, this.sourceFields.slice(0, 2));
88
          if (raw !== undefined) return raw;
89
          var battery = readNumber(payload, this.sourceFields[2]);
90
          if (battery === undefined) return undefined;
91
          return battery <= node.batteryLowThreshold;
92
        }
93
      },
94
      {
95
        sourceSystem: "zigbee2mqtt",
96
        sourceTopicMatch: "zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>",
97
        sourceFields: ["voltage"],
98
        targetBus: "home",
99
        targetCapability: "voltage",
100
        core: false,
101
        stream: "value",
102
        payloadProfile: "scalar",
103
        dataType: "number",
104
        unit: "mV",
105
        precision: 1,
106
        historianMode: "sample",
107
        historianEnabled: true,
108
        read: function(payload) {
109
          return readNumber(payload, this.sourceFields[0]);
110
        }
111
      },
112
      {
113
        sourceSystem: "zigbee2mqtt",
114
        sourceTopicMatch: "zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>",
115
        sourceFields: ["tamper", "tampered", "tamper_alarm", "alarm_tamper"],
116
        targetBus: "home",
117
        targetCapability: "tamper",
118
        core: false,
119
        stream: "value",
120
        payloadProfile: "scalar",
121
        dataType: "boolean",
122
        historianMode: "state",
123
        historianEnabled: true,
124
        read: function(payload) {
125
          return readBool(payload, this.sourceFields);
126
        }
127
      }
128
    ];
129

            
130
    function normalizeToken(value) {
131
      if (value === undefined || value === null) return "";
132
      return String(value).trim();
133
    }
134

            
135
    function transliterate(value) {
136
      var s = normalizeToken(value);
137
      if (!s) return "";
138
      if (typeof s.normalize === "function") {
139
        s = s.normalize("NFKD").replace(/[\u0300-\u036f]/g, "");
140
      }
141
      return s;
142
    }
143

            
144
    function toKebabCase(value, fallback) {
145
      var s = transliterate(value).toLowerCase().replace(/[^a-z0-9]+/g, "-");
146
      s = s.replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-");
147
      return s || fallback || "";
148
    }
149

            
150
    function clamp(n, min, max) {
151
      return Math.max(min, Math.min(max, n));
152
    }
153

            
154
    function topicTokens(topic) {
155
      if (typeof topic !== "string") return [];
156
      return topic.split("/").map(function(token) { return token.trim(); }).filter(function(token) { return !!token; });
157
    }
158

            
159
    function asBool(value) {
160
      if (typeof value === "boolean") return value;
161
      if (typeof value === "number") return value !== 0;
162
      if (typeof value === "string") {
163
        var v = value.trim().toLowerCase();
164
        if (v === "true" || v === "1" || v === "on" || v === "yes" || v === "online") return true;
165
        if (v === "false" || v === "0" || v === "off" || v === "no" || v === "offline") return false;
166
      }
167
      return null;
168
    }
169

            
170
    function pickFirst(obj, keys) {
171
      if (!obj || typeof obj !== "object") return undefined;
172
      for (var i = 0; i < keys.length; i++) {
173
        if (Object.prototype.hasOwnProperty.call(obj, keys[i])) return obj[keys[i]];
174
      }
175
      return undefined;
176
    }
177

            
178
    function pickPath(obj, path) {
179
      if (!obj || typeof obj !== "object") return undefined;
180
      var parts = path.split(".");
181
      var current = obj;
182
      for (var i = 0; i < parts.length; i++) {
183
        if (!current || typeof current !== "object" || !Object.prototype.hasOwnProperty.call(current, parts[i])) return undefined;
184
        current = current[parts[i]];
185
      }
186
      return current;
187
    }
188

            
189
    function pickFirstPath(obj, paths) {
190
      for (var i = 0; i < paths.length; i++) {
191
        var value = pickPath(obj, paths[i]);
192
        if (value !== undefined && value !== null && normalizeToken(value) !== "") return value;
193
      }
194
      return undefined;
195
    }
196

            
197
    function readBool(payload, fields) {
198
      var raw = asBool(pickFirst(payload, fields));
199
      return raw === null ? undefined : raw;
200
    }
201

            
202
    function readNumber(payload, field) {
203
      if (!payload || typeof payload !== "object") return undefined;
204
      var value = payload[field];
205
      if (typeof value !== "number" || !isFinite(value)) return undefined;
206
      return Number(value);
207
    }
208

            
209
    function toIsoTimestamp(value) {
210
      if (value === undefined || value === null) return "";
211
      if (value instanceof Date && !isNaN(value.getTime())) return value.toISOString();
212
      if (typeof value === "number" && isFinite(value)) {
213
        var ms = value < 100000000000 ? value * 1000 : value;
214
        var dateFromNumber = new Date(ms);
215
        return isNaN(dateFromNumber.getTime()) ? "" : dateFromNumber.toISOString();
216
      }
217
      if (typeof value === "string") {
218
        var trimmed = value.trim();
219
        if (!trimmed) return "";
220
        if (/^\d+$/.test(trimmed)) return toIsoTimestamp(Number(trimmed));
221
        var dateFromString = new Date(trimmed);
222
        return isNaN(dateFromString.getTime()) ? "" : dateFromString.toISOString();
223
      }
224
      return "";
225
    }
226

            
227
    function canonicalSourceTopic(topic) {
228
      var t = normalizeToken(topic);
229
      if (!t) return "";
230
      if (/\/availability$/i.test(t)) return t.replace(/\/availability$/i, "");
231
      return t;
232
    }
233

            
234
    function inferFromTopic(topic) {
235
      var tokens = topicTokens(topic);
236
      var result = {
237
        deviceType: "",
238
        site: "",
239
        location: "",
240
        deviceId: "",
241
        friendlyName: "",
242
        isAvailabilityTopic: false
243
      };
244

            
245
      if (tokens.length >= 2 && tokens[0].toLowerCase() === "zigbee2mqtt") {
246
        result.deviceType = tokens[1];
247

            
248
        if (tokens.length >= 6 && tokens[5].toLowerCase() === "availability") {
249
          result.site = tokens[2];
250
          result.location = tokens[3];
251
          result.deviceId = tokens[4];
252
          result.friendlyName = tokens.slice(1, 5).join("/");
253
          result.isAvailabilityTopic = true;
254
          return result;
255
        }
256

            
257
        if (tokens.length >= 5 && tokens[4].toLowerCase() !== "availability") {
258
          result.site = tokens[2];
259
          result.location = tokens[3];
260
          result.deviceId = tokens[4];
261
          result.friendlyName = tokens.slice(1, 5).join("/");
262
          return result;
263
        }
264
      }
265

            
266
      return result;
267
    }
268

            
269
    function resolveIdentity(msg, payload) {
270
      var safeMsg = (msg && typeof msg === "object") ? msg : {};
271
      var inferred = inferFromTopic(safeMsg.topic);
272
      var siteRaw = inferred.site
273
        || normalizeToken(pickFirst(payload, ["site", "homeSite"]))
274
        || normalizeToken(pickFirst(safeMsg, ["site", "homeSite"]))
275
        || node.site
276
        || "";
277

            
278
      var locationRaw = inferred.location
279
        || normalizeToken(pickFirst(payload, ["location", "room", "homeLocation", "mqttRoom"]))
280
        || normalizeToken(pickFirst(safeMsg, ["location", "room", "homeLocation", "mqttRoom"]))
281
        || node.legacyRoom
282
        || "";
283

            
284
      var deviceRaw = inferred.deviceId
285
        || normalizeToken(pickFirst(payload, ["deviceId", "device_id", "sensor", "mqttSensor", "friendly_name", "friendlyName", "name", "device"]))
286
        || normalizeToken(pickFirst(safeMsg, ["deviceId", "device_id", "sensor", "mqttSensor"]))
287
        || node.legacySensor
288
        || inferred.friendlyName
289
        || inferred.deviceType;
290

            
291
      var displayName = normalizeToken(pickFirst(payload, ["display_name", "displayName", "friendly_name", "friendlyName", "name"]))
292
        || normalizeToken(pickFirst(safeMsg, ["display_name", "displayName", "friendly_name", "friendlyName", "name"]))
293
        || inferred.friendlyName
294
        || deviceRaw
295
        || "SNZB-04P";
296

            
297
      var sourceRef = normalizeToken(pickFirstPath(payload, ["source_ref", "sourceRef", "ieee_address", "ieeeAddr", "device.ieee_address", "device.ieeeAddr"]))
298
        || normalizeToken(pickFirstPath(safeMsg, ["source_ref", "sourceRef", "ieee_address", "ieeeAddr", "device.ieee_address", "device.ieeeAddr"]))
299
        || canonicalSourceTopic(safeMsg.topic)
300
        || inferred.friendlyName
301
        || inferred.deviceType
302
        || deviceRaw
303
        || "z2m-snzb-04p";
304

            
305
      return {
306
        site: toKebabCase(siteRaw, "unknown"),
307
        location: toKebabCase(locationRaw, "unknown"),
308
        deviceId: toKebabCase(deviceRaw, "snzb-04p"),
309
        displayName: displayName,
310
        sourceRef: sourceRef,
311
        sourceTopic: canonicalSourceTopic(safeMsg.topic),
312
        isAvailabilityTopic: inferred.isAvailabilityTopic
313
      };
314
    }
315

            
316
    function noteDevice(identity) {
317
      if (!identity) return;
318
      var key = identity.site + "/" + identity.location + "/" + identity.deviceId;
319
      if (node.detectedDevices[key]) return;
320
      node.detectedDevices[key] = true;
321
      node.stats.devices_detected += 1;
322
    }
323

            
324
    function validateInboundTopic(topic) {
325
      var rawTopic = normalizeToken(topic);
326
      if (!rawTopic) return { valid: false, reason: "Topic must be a non-empty string" };
327
      var tokens = rawTopic.split("/").map(function(token) { return token.trim(); });
328
      if (tokens.length < 5) {
329
        return { valid: false, reason: "Topic must match zigbee2mqtt/SNZB-04P/<site>/<location>/<device_id>[/availability]" };
330
      }
331
      if (tokens[0].toLowerCase() !== "zigbee2mqtt" || tokens[1].toLowerCase() !== "snzb-04p") {
332
        return { valid: false, reason: "Topic must start with zigbee2mqtt/SNZB-04P" };
333
      }
334
      if (!tokens[2] || !tokens[3] || !tokens[4]) {
335
        return { valid: false, reason: "Topic must contain non-empty site, location and device_id segments" };
336
      }
337
      if (tokens.length === 5) return { valid: true, isAvailabilityTopic: false };
338
      if (tokens.length === 6 && tokens[5].toLowerCase() === "availability") {
339
        return { valid: true, isAvailabilityTopic: true };
340
      }
341
      return { valid: false, reason: "Topic must not contain extra segments beyond an optional /availability suffix" };
342
    }
343

            
344
    function translatedMessageCount() {
345
      return node.stats.home_messages + node.stats.last_messages + node.stats.meta_messages + node.stats.home_availability_messages;
346
    }
347

            
348
    function updateNodeStatus(fill, shape, suffix) {
349
      var parts = [
350
        "dev " + node.stats.devices_detected,
351
        "in " + node.stats.processed_inputs,
352
        "tr " + translatedMessageCount()
353
      ];
354
      if (node.stats.operational_messages > 0) parts.push("op " + node.stats.operational_messages);
355
      if (node.stats.errors > 0) parts.push("err " + node.stats.errors);
356
      if (suffix) parts.push(suffix);
357
      node.status({ fill: fill, shape: shape, text: parts.join(" | ") });
358
    }
359

            
360
    function buildHomeTopic(identity, mapping, stream) {
361
      return identity.site + "/" + mapping.targetBus + "/" + identity.location + "/" + mapping.targetCapability + "/" + identity.deviceId + "/" + stream;
362
    }
363

            
364
    function buildSysTopic(site, stream) {
365
      return site + "/sys/adapter/" + node.adapterId + "/" + stream;
366
    }
367

            
368
    function makePublishMsg(topic, payload, retain) {
369
      return { topic: topic, payload: payload, qos: 1, retain: !!retain };
370
    }
371

            
372
    function makeSubscribeMsg(topic) {
373
      return {
374
        action: "subscribe",
375
        topic: [{
376
          topic: topic,
377
          qos: 2,
378
          rh: 0,
379
          rap: true
380
        }]
381
      };
382
    }
383

            
384
    function signature(value) {
385
      return JSON.stringify(value);
386
    }
387

            
388
    function shouldPublish(cacheKey, payload, retain) {
389
      var sig = signature(payload) + "::" + (retain ? "r" : "n");
390
      if (node.publishCache[cacheKey] === sig) return false;
391
      node.publishCache[cacheKey] = sig;
392
      return true;
393
    }
394

            
395
    function shouldPublishRetained(cacheKey, payload) {
396
      var sig = signature(payload);
397
      if (node.retainedCache[cacheKey] === sig) return false;
398
      node.retainedCache[cacheKey] = sig;
399
      return true;
400
    }
401

            
402
    function buildLastEnvelope(value, observedAt, quality) {
403
      return {
404
        value: value,
405
        observed_at: observedAt || new Date().toISOString(),
406
        quality: quality || "source"
407
      };
408
    }
409

            
410
    function emitCapability(out, identity, mapping, value, observedAt, quality) {
411
      var valueTopic = buildHomeTopic(identity, mapping, "value");
412
      var lastTopic = buildHomeTopic(identity, mapping, "last");
413
      var valueKey = valueTopic + "::value";
414
      var lastPayload = buildLastEnvelope(value, observedAt, quality);
415
      if (shouldPublish(valueKey, value, false)) {
416
        out.push(makePublishMsg(valueTopic, value, false));
417
        node.stats.home_messages += 1;
418
      }
419
      if (shouldPublishRetained(lastTopic, lastPayload)) {
420
        out.push(makePublishMsg(lastTopic, lastPayload, true));
421
        node.stats.last_messages += 1;
422
      }
423
      node.seenOptionalCapabilities[mapping.targetCapability] = true;
424
    }
425

            
426
    function emitMeta(out, identity, sourcePayload) {
427
      var topic = identity.site + "/home/" + identity.location + "/meta/" + identity.deviceId + "/last";
428
      var payload = {
429
        adapter_id: node.adapterId,
430
        device_type: "SNZB-04P",
431
        display_name: identity.displayName,
432
        source_ref: identity.sourceRef,
433
        source_topic: identity.sourceTopic
434
      };
435
      if (sourcePayload && sourcePayload.update) payload.update = sourcePayload.update;
436
      if (shouldPublishRetained(topic, payload)) {
437
        out.push(makePublishMsg(topic, payload, true));
438
        node.stats.meta_messages += 1;
439
      }
440
    }
441

            
442
    function emitAvailability(out, identity, online) {
443
      var topic = identity.site + "/home/" + identity.location + "/availability/" + identity.deviceId + "/last";
444
      var payload = online ? "online" : "offline";
445
      if (shouldPublishRetained(topic, payload)) {
446
        out.push(makePublishMsg(topic, payload, true));
447
        node.stats.home_availability_messages += 1;
448
      }
449
    }
450

            
451
    function emitOperational(out, site, stream, payload, retain) {
452
      out.push(makePublishMsg(buildSysTopic(site || "unknown", stream), payload, retain));
453
      node.stats.operational_messages += 1;
454
    }
455

            
456
    function processTelemetry(msg) {
457
      var out = [];
458
      var payload = (msg && typeof msg.payload === "object" && msg.payload && !Array.isArray(msg.payload)) ? msg.payload : null;
459
      if (!payload) {
460
        node.stats.invalid_payloads += 1;
461
        emitOperational(out, "unknown", "dlq", { reason: "invalid-payload", topic: msg && msg.topic }, false);
462
        return out;
463
      }
464

            
465
      var validity = validateInboundTopic(msg.topic);
466
      if (!validity.valid) {
467
        node.stats.invalid_topics += 1;
468
        emitOperational(out, "unknown", "dlq", { reason: validity.reason, topic: msg.topic }, false);
469
        return out;
470
      }
471

            
472
      var identity = resolveIdentity(msg, payload);
473
      noteDevice(identity);
474
      emitMeta(out, identity, payload);
475

            
476
      var observedAt = toIsoTimestamp(payload.last_seen) || new Date().toISOString();
477
      var quality = toIsoTimestamp(payload.last_seen) ? "source" : "estimated";
478

            
479
      for (var i = 0; i < CAPABILITY_MAPPINGS.length; i++) {
480
        var mapping = CAPABILITY_MAPPINGS[i];
481
        try {
482
          var value = mapping.read(payload);
483
          if (value === undefined) continue;
484
          emitCapability(out, identity, mapping, value, observedAt, quality);
485
        } catch (err) {
486
          node.stats.adapter_exceptions += 1;
487
          emitOperational(out, identity.site, "error", { capability: mapping.targetCapability, error: err.message }, false);
488
        }
489
      }
490

            
491
      if (validity.isAvailabilityTopic || payload.availability !== undefined || payload.online !== undefined) {
492
        var online = asBool(payload.online);
493
        if (online === null) online = asBool(payload.availability);
494
        if (online !== null) emitAvailability(out, identity, online);
495
      }
496

            
497
      return out;
498
    }
499

            
500
    function startSubscriptions() {
501
      if (node.subscriptionStarted) return;
502
      node.subscriptionStarted = true;
503
      node.send([null, makeSubscribeMsg(node.sourceTopic)]);
504
      updateNodeStatus("yellow", "ring", "subscribed");
505
    }
506

            
507
    node.on("input", function(msg, send, done) {
508
      send = send || function() { node.send.apply(node, arguments); };
509
      try {
510
        node.stats.processed_inputs += 1;
511
        var outputs = processTelemetry(msg);
512
        send([outputs, null]);
513
        updateNodeStatus(node.stats.errors ? "red" : "green", "dot");
514
        if (done) done();
515
      } catch (err) {
516
        node.stats.errors += 1;
517
        updateNodeStatus("red", "ring", err.message);
518
        if (done) done(err);
519
        else node.error(err, msg);
520
      }
521
    });
522

            
523
    node.on("close", function() {
524
      if (node.startTimer) {
525
        clearTimeout(node.startTimer);
526
        node.startTimer = null;
527
      }
528
    });
529

            
530
    node.startTimer = setTimeout(startSubscriptions, 250);
531
    updateNodeStatus("grey", "ring", "starting");
532
  }
533

            
534
  RED.nodes.registerType("z2m-snzb-04p-homebus", Z2MSNZB04PHomeBusNode);
535
};