mynodes / msg-status / msg-status.js
1 contributor
60 lines | 1.799kb
module.exports = function(RED) {
  function MsgStatusNode(config) {
    RED.nodes.createNode(this, config);
    var node = this;

    // Configuration
    node.msgPath = (config.msgPath || "").trim();
    node.prefix = (config.prefix || "").trim();
    node.suffix = (config.suffix || "").trim();
    node.shape = config.shape || "dot";
    node.fill = config.fill || "blue";
    node.showTime = config.showTime !== false;

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

    function formatTime(date) {
      function pad(value) {
        return String(value).padStart(2, "0");
      }
      return [
        pad(date.getHours()),
        pad(date.getMinutes()),
        pad(date.getSeconds())
      ].join(":");
    }

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

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

        node.status({
          fill: node.fill,
          shape: node.shape,
          text: statusText
        });

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

      // Pass through the original message
      node.send(msg);
    });

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

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