Assigning State Attributes to Variables in Functions

Using Inject i’m able to trigger a get entities node that grabs sun.sun.

In the debug node, I can change msg.payload to msg.payload.0.attributes.elevation to filter out everything but the elevation.

How, in a function node, would I assign msg.payload.0.attriburtes.elevation to a variable?

var sunLevel = msg.payload.0.attributes.elevation; seems to be problematic because of the zero with a dot.

The end goal is to store the sun’s elevation in a global variable in NodeRED using:

var sunLevel = global.set('sunLevel', <elevation here>);   // and then
var whatever = global.get('sunLevel');
if (this or that) {
   whatever;
}

So, the syntax for:
var sunLevel = msg.payload.0.attributes.elevation; needs work…or I need to know how to write a function from scratch that can yank this information out of home assistant without using the get entities node.

EDIT: Looks like I figured this part out…is this the best way to do it? It seems to work.

const gHomeAssistant = global.get('homeassistant').homeAssistant;
msg.payload = gHomeAssistant.states[`sun.sun`].attributes.elevation;

Thanks!

1 Like