Node-red home assistant states

I am trying to get the state of a home assistant binary sensor inside of a function node so I can do some basic if else comparison but not getting getting a value:

msg.BMS = msg.payload.result.deviceWapper.realTimeDataBMS;

if(msg.BMS == null || msg.BMS == 'undefined') {
    node.error("Could not get BMS details")
}

msg.pv = {};

msg.pv['bms_voltage'] = msg.BMS[0].value;
msg.pv['bms_current'] = msg.BMS[1].value;
msg.pv['bms_charge_current'] = msg.BMS[2].value;
msg.pv['bms_discharge_current'] = msg.BMS[3].value;

var bms_voltage = {
    payload: msg.pv.bms_voltage,
    topic: "home/solar/bms/voltage"
};

var bms_current = {
    payload: msg.pv.bms_current,
    topic: "home/solar/bms/current"
};

var bms_charge_current = {
    payload: msg.pv.bms_charge_current,
    topic: "home/solar/bms/charge_current"
};

var bms_discharge_current = {
    payload: msg.pv.bms_discharge_current,
    topic: "home/solar/bms/discharge_current"
};

var pizero2State = global.get("homeassistant.homeAssistant.states['binary_sensor.pi_zero_2'].state");
var piz = {
    payload: pizero2State,
    topic: "home/solar/bms/pizerotest"
};
return [[bms_voltage, bms_current, bms_charge_current, bms_discharge_current, piz],msg];

Basically that global.get is always undefined, not sure why

You need to get the “homeassistant” value from global, and then get properties off that. So:

var pizero2State = global.get("homeassistant").homeAssistant.states['binary_sensor.pi_zero_2'].state;

However, why not just have a “get state” node ahead of this one? This makes it clearer that your flow is using that value rather than hiding it away inside a function. You can change that node’s output to save payload and data into different properties of the message so you don’t overwrite existing values.

2 Likes

Was thinking that but there’s a bunch messages being passed around and no idea how to pass everything through:

“Good” nodes (my judgement here :slight_smile:) don’t touch other properties on the message, so if you use a “get state” node to store the data in “msg.dataPiZero2”, it should propagate all the way along your flow.

Yes I could do it like this
image
and then have true/false flows going out of it but I would need to double the amount of functions I have so it’s cleaner to do it as above.
Worked it out why the state wasn’t showing as well this needs to be ticked:
image