Thursday, January 21, 2016

Howto: Node-RED Change Hue Lights Temporarily On Door Open

We fitted a LightwaveRF magnetic sensor to a door to detect whether it is open or closed. The main driver behind this was to increase the level of the hallway lights for a predetermined period of time whenever the door was opened. Since we’re using coloured lights it makes sense to put the light back to how it was once the time period as elapsed. 

Node-RED does not offer a node as a means of storing state between, but it does offer functions which have access to a context object which can be used to store state between flows. 

I’ve created a flow which listens to the `domoticz/out` MQTT topic filters messages based on their Domoticz IDX value and furthers filters on the door switches `nvalue` where 1 indicates door open and 0 indicates door closed. 


On Door Open:
  1. Retrieve state of current light and if nothing already stored, store the current bulb state in the context. 
  2. Change the state of the bulb to a bright white. 
  3. Reset the timer in place if a door close event was received whilst the light is already bright. This would occur if the door is opened again whilst the light is in a brightened state. By not replacing the stored light state, we also avoid overwriting the original colour with the temporary brighter state. 

On Door Close:
  1. Instruct the ‘Record or Despatch’ node to restore the original state which sends the original light colour to the timer. 
  2. If the timer has expired, the original state is sent onto the hallway bulb
  3. A reset context message sent to the ‘Record or Despatch’ node to clear any saved light state. 

The ‘Record or Despatch’ node is a function with the following code:

if (msg.restore) {
    node.send({payload: context.previousState});
} if (msg.reset) {
    delete context.previousState;  
} else {
    if (!context.previousState) {
        context.previousState = msg.payload;
    }
}


Feel free to download the full flow here: 

No comments: