Check if a sensor is in a given state for a certain amount of time

In this example, we will learn how to create a rule that will check if a given sensor is a particular state or set of states for a certain amount of time. We will assume that this rule is the task specific, meaning that we want to avoid storing any particular state of a sensor in the time series database or the metadata store.

image

Note that we are using transition from the dice sensor, that will trigger script sensor only on the state change. Script sensor will capture the last state of the dice (using declarative binding) and will also store the time of the last change.

()=>{
  return {
    "lastState" : "${nodes.dice_1.state}",
    "time" : Date.now()
  }
}

Condition sensor, on the other hand, is polling to check whether the dice sensor state (which is stored in the script node), has been it this state (in this example STATE) longer than a threshold (declared as const THR):

(()=>{
const THR = 10000
const STATE = "ONE"
console.log("time", "${nodes.script_1.rawData.time}")
console.log("lastState", "${nodes.script_1.rawData.lastState}")
const time = Date.now() - ${nodes.script_1.rawData.time}
return STATE === "${nodes.script_1.rawData.lastState}" && time > THR
})()