I’ve been using Home Assistant for a while now for a heap of different things but 1 thing that I found it was missing was being about to have a light or fan or something like that turn off after a given amount of time.
So, I made an automation to do just that and thought I’d share it in case others want to do something similar or people have better ways of doing it.
The goal was to have a card in a dashboard where I have a list of entities, a time input and a button and it would start a timer to turn off the device after that amount of time. (Useful for a bedroom fan or heater during the night)
Doesn’t look super pretty but here it is:
This consists of 3 helper entities:
- Automation: Switch Selection - This is a Dropdown type helper that lists the different entities I want to select from (using their entity Ids as the values)
- Automation: Switch Time - A Number entity that will determine the number of minutes for the timer.
- Automation: Button Timer - A button entity to trigger the automation
From there I wired it all up with Nodered
- automation_button_changed - This is the trigger node for when the button state changes
- switch_selection - Current state node to get the value of the “Automation: Switch Selection” helper entity
- switch_timer - Current state node to get the value of the “Automation: Switch Time” helper entity
- timer_delay_calc - Function node that calculates the time in milliseconds (for use with the delay node) and gets the domain of the switch entity (since we have to call different services for light, fan, switch, etc.)
- delay - Delay node to wait the selected time as passed in by the function node above
- turn_off - HA Call Service node to turn off the selected entity
The first 3 nodes are pretty straight forward, make sure you assign the states to different output properties so they don’t overwrite each other. (I used selection
and timer
for the different entity states).
The function node is simple, multiply the timer value by 60000 (to convert a number into the ms in that many minutes) then split the selection string on the .
and set that to a domain property.
var ms = msg.timer * 60000;
msg.delay = ms;
msg.domain = msg.selection.split(".")[0];
return msg;
The delay node then has an option for “Override delay with msg.delay” which is selected to tell the node to use the delay property that we calculated above.
Lastly the Call service node, her I set the Domain to {{domain}}
so that it injects the calculated domain value from our funciton node, Service set to turn_off
(this service is the same for all domains) then the entity I set to {{selection}}
which is the value from our selection helper containing the entity Id we want to switch off.
Let me know what you think about this little automation and if you have done something similar in a different way.