How to get displayState for item in JS automation?

Has an item

Number:Pressure Equipment_WaterIn_Pressure "Pressure [%.2f bar]" <pipe_leak> (Home, Equipment_WaterIn) ["Measurement", "Pressure"]

JS:

        items.getItem('Equipment_WaterIn_Pressure').postUpdate('231000 Pa');

        console.log(items.getItem('Equipment_WaterIn_Pressure').state); // 231000 Pa
        console.log(items.getItem('Equipment_WaterIn_Pressure').rawItem.getStateDescription().pattern); // %.2f bar
        console.log(items.getItem('Equipment_WaterIn_Pressure').rawState.getUnit().getSymbol()); // Pa
        console.log(items.getItem('Equipment_WaterIn_Pressure').rawState.format(items.getItem('Equipment_WaterIn_Pressure').rawItem.getStateDescription().pattern)); // 231000.00 bar WTF :)
        console.log(items.getItem('Equipment_WaterIn_Pressure').displayState); // undefined

// how to get '2.31 bar' in JS rule?

Firstly, that Item doesn’t define a displayState as written (maybe you set the metadata in the UI?).

Secondly, I’m not certain displayState exists outside of MainUI. If it does the following is probably what will retrieve it.

items.getItem('MyItem').rawItem.getStateDescription();

does not work.
console.log(items.getItem(‘Equipment_WaterIn_Pressure’).rawItem.getStateDescription());

// outputs
StateDescription [minimum=null, maximum=null, step=null, pattern=%.2f bar, readOnly=false, channelStateOptions=[]]

OK, that’s the metadata you defined for the State Description. In that case it cannot be done. The state description is something that only gets created in MainUI.

You could maybe manage something using java.lang.String.format, passing the “pattern” field as the format and the .rawState and the thing to be formatted, but you’ll have to do all sorts of parsing and extra work to handle Items with units.

oh, bad news for me ( Maybe You has some draft code to do that?

Another approach is to do what the UIs do - use HTTP to get the Item properties via REST API as JSON, and parse out the ‘display state’ element.

No, I don’t. It’s very rare that the pretty formatted state of the Item matters in a rule. About the only time I can think of where it’d be useful is logs, and who really cares that the logs are not “pretty”.

Item’s value notification in home family telegram bot. Need to display fancy formatted values

2 Likes

Hello,

I have exactly the same need, doing generic rules to push notifications.
I’m searching for a way to avoid duplicated code, and state description pattern seemed to be a good start.

Do you know if there is a easy way (except HTTP / REST) to use getDisplayState from SseItemStatesEventBuilder ?

Currently when a door is open, voice assistant says “door blabla is ON” not really “nice” :slight_smile: