How to get item state in JSrule javascript automation

  • Platform information:
    • Hardware: Raspberry PI 4
    • OS: Raspbian (latest version)
    • openHAB version: 3.2
  • Issue of the topic: How to get item state in a JSRule automation

Is it possible to read item state in a JSRule automation ?
Right now, I have this script, which works but is bulcky

rules.JSRule({
  name: 'draadloze schakelaar slaapkamer 4 - AAN',
  triggers: [triggers.ItemCommandTrigger('vlg_cocoSchakelaar', 'ON')],
  execute: data => {
    items.getItem("vlg_slpk_stefaan").sendCommand("ON")
  }
})

rules.JSRule({
  name: 'draadloze schakelaar slaapkamer 4 - UIT',
  triggers: [triggers.ItemCommandTrigger('vlg_cocoSchakelaar', 'OFF')],
  execute: data => {
    items.getItem("vlg_slpk_stefaan").sendCommand("OFF")
  }
})

I would like to rewrite the script by getting the new item state from the switch sensor and sending it to the actuator, something like this

rules.JSRule({
  name: 'draadloze schakelaar slaapkamer 4',
  triggers: [triggers.ItemCommandTrigger('vlg_cocoSchakelaar')],
  execute: data => {
    const status = items.getItem("vlg_slpk_stefaan").status
    console.log(status)
  }
})

However,

  • items.getItem("vlg_slpk_stefaan").status() throws
  • items.getItem("vlg_slpk_stefaan").status is undefined
  • data looks like below, allthough there is a newState property, it is null
{
  "eventType": "command",
  "triggerType": "ItemCommandTrigger",
  "receivedCommand": {},
  "oldState": "null",
  "newState": "null",
  "itemName": "vlg_cocoSchakelaar"
}

Any ideas ?

You should try items.getItem("vlg_slpk_stefaan").state instead of status

1 Like

Found the correct script after some intensive debugging.
I document it here in case someone else has the same problem

rules.JSRule({
  name: 'draadloze schakelaar slaapkamer 4',
  triggers: [triggers.ItemStateUpdateTrigger('vlg_cocoSchakelaar')],
  execute: data => {
    let switchItem = items.getItem('vlg_cocoSchakelaar')
    let switchNewStatus = switchItem.state.toString()
    console.log(`switchNewStatus = '${switchNewStatus}'`)
    items.getItem("vlg_slpk_stefaan").sendCommand(switchNewStatus)
  }
})

@csowada That was the problem indeed. I also had to change the trigger into ItemStateUpdateTrigger otherwise I would always get the previous state.
Is there a way to get the new command state with ItemCommandTrigger ?

@csowada never mind, I found it : data.payload.value