mynodes / msg-status / msg-status.js
Newer Older
60 lines | 1.799kb
Bogdan Timofte authored 2 weeks ago
1
module.exports = function(RED) {
2
  function MsgStatusNode(config) {
3
    RED.nodes.createNode(this, config);
4
    var node = this;
5

            
6
    // Configuration
7
    node.msgPath = (config.msgPath || "").trim();
8
    node.prefix = (config.prefix || "").trim();
9
    node.suffix = (config.suffix || "").trim();
10
    node.shape = config.shape || "dot";
11
    node.fill = config.fill || "blue";
12
    node.showTime = config.showTime !== false;
13

            
14
    if (!node.msgPath) {
15
      node.status({fill: "red", shape: "ring", text: "error: no path configured"});
16
      return;
17
    }
18

            
19
    function formatTime(date) {
20
      function pad(value) {
21
        return String(value).padStart(2, "0");
22
      }
23
      return [
24
        pad(date.getHours()),
25
        pad(date.getMinutes()),
26
        pad(date.getSeconds())
27
      ].join(":");
28
    }
29

            
30
    node.on("input", function(msg) {
31
      try {
32
        // Helper: get nested value from object using dot notation
33
        var value = RED.util.getMessageProperty(msg, node.msgPath);
34

            
35
        // Format status text
36
        var statusText = node.showTime ? formatTime(new Date()) + " " : "";
37
        if (node.prefix) statusText += node.prefix + " ";
38
        statusText += (value !== null && value !== undefined) ? String(value) : "null";
39
        if (node.suffix) statusText += " " + node.suffix;
40

            
41
        node.status({
42
          fill: node.fill,
43
          shape: node.shape,
44
          text: statusText
45
        });
46

            
47
      } catch (e) {
48
        node.status({fill: "red", shape: "ring", text: "error: " + e.message});
49
      }
50

            
51
      // Pass through the original message
52
      node.send(msg);
53
    });
54

            
55
    // On first deploy or config change, show initial status
56
    node.status({fill: node.fill, shape: node.shape, text: "waiting..."});
57
  }
58

            
59
  RED.nodes.registerType("msg-status", MsgStatusNode);
60
};