Get entity friendly name in function

Hi,

I have a function in which i want to check the status of a binary sensor, but also get the friendly name of that sensor. I can’t find any way to reference the entity.

I do have the entity ID i can pass, but not sure of the command required in order to query for the attribute. Any guidance or link to reference documentation, i’ve been searching for 2 hours.

I was hoping it’d be as simple as get.object[‘obj-id’].attributes.friendly_name

Many thanks in advance

https://zachowj.github.io/node-red-contrib-home-assistant-websocket/node/config-server.html#context-example

Thank you, but that doesn’t give me path to friendly name?

...
const entity = configCtx.states["switch.my_switch"];
msg.payload = entity.attributes.friendly_name;
return msg;
1 Like

Thank you @Kermit - That worked as expected.

For my benefit, is there somewhere documented you were able to find the tree entitiy.attributes.friendly_name - I am curious how you knew this was the location?

Put a debug node on and set it to the complete message as output.
Then look at the captured output and find you data.
To the right of it should be 3 smal icons.
One of these (I think it is the middle one) will copy the path to your clipboard.

I’m sharing something weird that happened around getting the friendly_name because it took me a bit to resolve. I had everything working and then suddenly started getting the following error when trying to retrieve states in the function node

"TypeError: Cannot read properties of undefined (reading 'states')"

“Get Friendly Device Name” function:

const haCtx = global.get("homeassistant");
const configCtx = haCtx.homeAssistant;
const entity = configCtx.states[msg.topic];
msg.displayName = entity.attributes.friendly_name;
return msg;

The problem ended up being my HA server name in Node-Red. I had “Home Assistant Pi” as my server name and for some reason the script above worked fine, until it didn’t. The issue ended up being a Node-Red server name mismatch with the script. I ended up changing my server name to homeassistant and the line above to ...haCtx.homeassistant; and everything started working again.

I’m baffled because I didn’t haven’t my server in a year or so. Anyway, hopefully this helps the next person.