How to turn on a switch at nighttime via Home Assistant automations

My wife recently asked me if it would be possible to have her bedroom lamp turn on after the sun goes down to “make the house more cozy”. The answer, of course, is “for you, it is but a trifle”.

Home Assistant makes it easy to create “automations” or programs that run to control your house. Having a button on your phone or computer to turn lights on and off is fun, but having the lights automatically come on when the sun sets; that’s the power of home automation.

As you add more and more smart devices to your home, you can “chain” them together to create more useful automations.

There are graphical tools like NodeRED which can make it easier to build these automations graphically, but I have had success just updating the YAML files manually for now.

In this example, I’m going to show how to automate my downstairs lamp switches (really outlets) to automatically turn on when the sun sets (only when we are home).

Here are the major steps

  • Install smart switches and/or outlets in your home and link them to Home Assistant
  • Create “trackers” to determine when you are home or not
  • Add a “sun” component to Home Assistant to know when the sun rises and sets in your part of the world
  • Create a “lamps” group to enable you to control a group of lights that should be turned on at the same time
  • Create an “automation” to toggle the switches to “on” when the sun sets

Install smart switches and/or outlets in your home and link them to Home Assistant

Obviously, you must have some smart switches or outlets already installed in your home and configured in Home Assistant as the first step. See the below blog posts to learn how to do this.

Create “trackers” to determine when you are home or not

You need to set up a “tracker” to determine whether or not you are home. This is so that you can use this information later in the automation. The way this works is that your router knows when your phone is connected to the network. Therefore, Home Assistant can “query” your router to see if your phone (technically, the MAC address) is connected.

Your mileage may vary here. Home Assistant supports many routers, but not all. You should create a special account just for Home Assistant to use to login to your router, but the normal admin login will do in a pinch.

  • Open the device_tracker.yaml file and add the following.
  • platform: the type of router you have, refer to the Home Assistant list to see what to put here
  • host: the IP address of your router (may be for simple set-ups, login to your router to be sure)
  • username: the username to login to the router with
  • password: the password to use to login to the router
  • verify_ssl: if your router uses a SSL certificate to encrypt the admin page/data when logging in to the admin console, set this to true, false otherwise
- platform: !secret device_tracker_platform
  host: !secret device_tracker_host
  username: !secret device_tracker_username
  password: !secret device_tracker_password
  verify_ssl: !secret device_tracker_verify_ssl
  • Open the secrets.yaml file and add the following (note the names match what you defined before in the device_tracker.yaml file)
device_tracker_platform: unifi
device_tracker_username: dwight
device_tracker_password: dwightIsAwesome!
device_tracker_verify_ssl: false

Now you need to add some “known devices” to Home Assistant so it knows what to look for when determining whether or not you are home (based upon whether or not your phone is connected).

  • Open (or create) the known_devices.yaml file and add the following.
  • hide_if_away: hide this device if not at home (set to false, kind of defeats the purpose here)
  • mac: the MAC address (this is the unique network identifier for your device, look this up for your specific phone)
  • name: the friendly name you want for this device
  • picture: if you have a picture for this device or person, add the path here
  • track: set to true so we know where the device is
  hide_if_away: false
  mac: !secret known_devices_jordan_iphone_mac
  name: jordan iphone
  track: true
  hide_if_away: false
  mac: !secret known_devices_kristal_iphone_mac
  name: kristal iphone
  track: true
  • Add the needed keys to your secrets.yaml file (obviously, not my real MAC addresses)
known_devices_jordan_iphone_mac: 00:AA:11:BB:22:CC
known_devices_kristal_iphone_mac: 00:ZZ:11:YY:22:XX

Add a “sun” component to Home Assistant to know when the sun rises and sets in your part of the world

Home Assistant has a built-in “sun” component that can determine when the sun rises & sets based upon your location and this data can be used in automations.

The way this works is that you need to tell Home Assistant your latitude and longitude so it can send this data to the service that determines when the sun rises and sets.

  • Add the following code to your Home Assistant configuration.yaml file
  # Name of the location where Home Assistant is running
  name: Home
  # Location required to calculate the time the sun rises and sets
  latitude: !secret homeassistant_latitude
  longitude: !secret homeassistant_longitude
  # Impacts weather/sunrise data (altitude above sea level in meters)
  elevation: !secret homeassistant_elevation
# Track the sun

You will notice that I am “hiding” my latitude and longitude in a secrets.yaml file. Home Assistant uses this special file for things that should not be open (like passwords, my actual lat/long, MAC addresses, etc.) Naturally, this file should never be public (never uploaded to GitHub, for instance).

  • Open your secrets.yaml file (or create it if it doesn’t exist in the same directory as the configuration.yaml file)
  • Add the following items (note the names are the same as you put in the configuration.yaml file). This is obviously not my house 🙂
  • Save and close the file
homeassistant_latitude: 34.211001
homeassistant_longitude: -118.436418
homeassistant_elevation: 0

If you don’t know your lat/long and elevation, you can get this data from Google Maps. Just type in your address and it will show you the lat/long if you right-click on your home and select “What’s here“.

Create a “lamps” group to enable you to control a group of lights that should be turned on at the same time

  • Open the groups.yaml file and add the following.
  • Two groups are needed in my example because I want the lamps to show up in other nested groups in my GUI. You don’t necessarily have to have 2 groups.
  name: Lamps
    - switch.downstairs_office_lamp
    - switch.front_door_lamp
    - switch.living_room_lamp
    - switch.master_bedroom_kristal_lamp
  control: hidden
  name: Lamps
    - group.lamps_hidden
  view: yes

Create an “automation” to toggle the switches to “on” when the sun sets

  • Open the configuration.yaml file and add a line for automations and link it to a new automations.yaml file.
automation: !include automations.yaml
  • Open the automations.yaml file and add the following.
  • id: a unique identifier for this automation. I have several automations above this one, so mine is a7, configure as needed
  • alias: the name of the automation in the GUI
  • initial_state: whether or not the automation should be enabled on reboot of the Home Assistant
  • hide_entity: whether or not to hide this automation from the GUI
  • trigger: what causes this automation to kick off. In this case, I want it to fire 1 hour before sunset (so the house isn’t too dark at dusk)
  • condition: this is needed to ensure someone is home before the automation is enabled. I don’t want this automation to run if either me or my wife is not home (I could set up a separate “burglar deterrent” automation for running the lights when no one is home)
  • action: what the automation should do. In this case, I want Home Assistant to send the “turn_on” signal to the “lamps” group. This should toggle all of the lamps to on.
- id: a7
  alias: Turn on the lamps when the sun sets if someone is home
  initial_state: True
  hide_entity: False
    platform: sun
    event: sunset
    offset: "-1:00:00"
    condition: or
      - condition: state
        entity_id: 'device_tracker.jordan_iphone'
        state: 'home'
      - condition: state
        entity_id: 'device_tracker.kristal_iphone'
        state: 'home'
    entity_id: group.lamps
    service: homeassistant.turn_on

Now we can wait for sunset and see if it turns on. After it comes on, we can see the results in the Logbook.

  • Go to the Home Assistant homescreen and click on Logbook

As you can see, at 6:44 PM (1 hour before sunset when I am writing this), the automation “Turn on the lamps when the sun sets if someone is home” has been triggered. You then see all of the lamps & lights I have associated with this automation come on.

That’s all there is to it. Now the lamps will turn on in my house 1 hour before sunset.