Passing complex JSON objects to HA/Lovelace from Node Red

Hi,

I’m working on a system for car warmup where I enter a time (and a date) when I’d like to start the car into the UI, the system checks weather forecast for that time and selects how long the car should be warmed, and figures out the start and end time when to switch the relay for the plug on/off. As a future enhancement, there might be an estimate shown (based on spot electricity price) of how much the warmup will cost (so that I might choose another mode of transportation if possible, if cost is high).

Now, I have the data worked up into a neat little json package at node red, essentially containing most of the things I’d like to show in the UI (as read-only data):

  • The start of the warmup (if weather data is available for that time)
  • The end of the warmup
  • The forecasted temperature, if available,
  • The forecasted weather conditions (if it is snowing, reserve time for car cleanup…)
  • The estimated cost for the warmup

But the only way I know how to pass these pieces of data is to create a helper for each. And even then, there is going to be some pain involved, as you can’t make a datetime-helper to be “null” (I get an error when I try to set the timestamp as zero, which doesn’t make much sense to me as that should be a valid timestamp).

What I want - or think I want (for lack of imagination of a better solution) - is to pass a JSON object from Node RED to HA/Loveleace, and use something like this to render the HTML with Jinja2 template: GitHub - PiotrMachowski/Home-Assistant-Lovelace-HTML-Jinja2-Template-card: This card displays provided Jinja2 template as an HTML content of a card. It uses exactly the same engine as Home Assistant in Developer tools.

Is that possible? Is breaking every single piece of data to a helper the only way?

You can send the information to an entity node in nodered. Use the attributes section for each value. Then use a card in lovelace that shows the attributes of the entity.

2 Likes

Do what Mikefila says. Create an entity node (of type sensor) and send the state and the attributes from your Node-RED computation node to the entity node. It will appear in HA and you will be able to use those in templates and automations.

I would do it all in Node-RED honestly.

1 Like

Okay, thanks. I was toying around with the “sensor” node which I assume you mean (as the “entity” node is deprecated and replaced by the five different types of entity nodes, I think), but ended up with the impression it would not suit the purpose. But I’ll try again now that I know that would be the way to go.

Something like this:

[{"id":"25ef1c9c74581477","type":"ha-api","z":"be03f9025a1f137a","name":"sensor","server":"541ade28.b4a62","version":1,"debugenabled":false,"protocol":"http","method":"post","path":"/api/states/{{entity_id}}","data":"","dataType":"json","responseType":"json","outputProperties":[{"property":"payload","propertyType":"msg","value":"","valueType":"results"}],"x":875,"y":750,"wires":[[]]},{"id":"06ac8e03a8a85876","type":"function","z":"be03f9025a1f137a","name":"make final payload","func":"msg.entity_id = `sensor.test_entity2`;\n\nmsg.payload = {\n    data: {\n        state: 'On',\n        attributes: {\n            'name': 'test_entity2',\n            'attribute1': 'attribute_1',\n            'attribute2': 'attribute_2',\n            'attribute3': 'attribute_3',\n            'attribute4': 'attribute_4',\n            friendly_name: 'Test Entity 2',\n            icon: 'mdi:pulse'\n        }\n    }\n};\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":705,"y":750,"wires":[["25ef1c9c74581477","fee8ca78ceac8578"]]},{"id":"39963ed0628d85b4","type":"inject","z":"be03f9025a1f137a","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":525,"y":750,"wires":[["06ac8e03a8a85876"]]},{"id":"541ade28.b4a62","type":"server","name":"Home Assistant","version":5,"addon":true,"rejectUnauthorizedCerts":true,"ha_boolean":"","connectionDelay":false,"cacheJson":false,"heartbeat":false,"heartbeatInterval":"","areaSelector":"friendlyName","deviceSelector":"friendlyName","entitySelector":"friendlyName","statusSeparator":"at: ","statusYear":"hidden","statusMonth":"short","statusDay":"numeric","statusHourCycle":"h23","statusTimeFormat":"h:m","enableGlobalContextStore":true}]```
1 Like

Personally I’m not a big fan of the entity node, as I prefer all devices to be managed within HA. Instead I create an MQTT sensor in HA, and then have NR send the MQTT message. You can then pick up complex JSON data using json_attributes_topic. There are two main advantages to this approach: (1) you can set the retain flag so a restart of HA does not result in ‘unavailable’; and (2) you can easily see what data is being sent using something like MQTT Explorer.

1 Like

Thank you, @WallyR’s suggestion seems to be working (API call to /api/states/{{entity_id}}). Would not have thought of that, and I still was confused about how to configure the ‘sensor’ node (one of the new entity nodes).

Sadly if you are using node red, there is no way to create a sensor entity in HA and then update its state / attributes from NR.

My suggestion does that, but I am unsure how that sensor behaves when HA restarts and if HA saves its values and restores them under a restart.
I looks like the sensor is lost at HA restart and therefore their state is lost too.

Eh if HA restarts you can resubmit your sensor state and attributes from Node-RED by observing the Home Assistant start event.

[
    {
        "id": "06893efbb952d654",
        "type": "server-events",
        "z": "01a2a01f208f82a3",
        "name": "Home assistant start",
        "server": "47fda6e5630a2a77",
        "version": 2,
        "eventType": "home_assistant_client",
        "exposeToHomeAssistant": false,
        "haConfig": [
            {
                "property": "name",
                "value": ""
            },
            {
                "property": "icon",
                "value": ""
            }
        ],
        "waitForRunning": true,
        "outputProperties": [
            {
                "property": "payload",
                "propertyType": "msg",
                "value": "",
                "valueType": "eventData"
            },
            {
                "property": "topic",
                "propertyType": "msg",
                "value": "$outputData(\"eventData\").event_type",
                "valueType": "jsonata"
            }
        ],
        "x": 130,
        "y": 60,
        "wires": [
            [
                "3d9b1e42d6e72a03"
            ]
        ]
    },
    {
        "id": "47fda6e5630a2a77",
        "type": "server",
        "name": "Home Assistant",
        "version": 5,
        "addon": false,
        "rejectUnauthorizedCerts": false,
        "ha_boolean": "y|yes|true|on|home|open",
        "connectionDelay": true,
        "cacheJson": true,
        "heartbeat": false,
        "heartbeatInterval": "30",
        "areaSelector": "friendlyName",
        "deviceSelector": "friendlyName",
        "entitySelector": "friendlyName",
        "statusSeparator": ": ",
        "statusYear": "hidden",
        "statusMonth": "short",
        "statusDay": "numeric",
        "statusHourCycle": "default",
        "statusTimeFormat": "h:m:s.ms",
        "enableGlobalContextStore": true
    }
]

Good solution.
Thanks :smiley:

I’m confused by what you mean - if you create an MQTT entity in HA and then publish to that topic from NR you are then updating its state / attributes from NR.

My JSON example is for a node that uses the Node-RED Home Assistant WebSocket integration — it does not use MQTT at all.

MQTT has its uses — but in my view there’s no need to add an extra layer between Node-RED and HA, since both integrate directly.

I should have included the quote of what I was referring to (below). I was confused because the way it was worded seemed wrong to me, as you can do this - by using an MQTT sensor. No matter.

1 Like