how to toggle the state of a light or switch for Alexa in Home Assistant

Toggling a light switch means that a press of the switch will turn the light off or on depending it what it was last doing.

There is nothing clever about that but if I was the push button on a remote control, I’d wonder whether to send an ‘on’ or an ‘off’ signal to the light? Indeed you often find that a switch press can only do an ‘on’ or an ‘off’. Amazon’s Alexa allows you to make routines that will turn lights on or off. What Alexa can’t do (as of 2021) is to tell the light to do the opposite of what it was last doing. This is ridiculous but the way to work round this in Home Assistant is to create a script that toggles the light. You then ‘expose’ that switch to Alexa. Exposing the switch means that you make the script available to Alexa which can then in turn make it run and toggle the light. It’s totally mad, I know.

See Automated Home Party – toggle lights and switches

Use the emulated Hue component and create a light that toggles

Go to the file editor in the Home Assistant frontend. You start by ‘exposing’ your scripts to Alexa.

  • In File editor open your configuration.yaml and add the code below
  • Save the edits and completely shut down and restart the Raspberry Pi
emulated_hue: 
  host_ip: 192.168.1.X 
# this is the IP of your own Home Assistant 
  listen_port: 80 
# advertise_ip: 192.168.1.X
# the above line isn't required as of 2021
  off_maps_to_on_domains: 
    - script 
  exposed_domains: 
#   - light 
    - switch 
    - script 
# below you can selectively list the script/s (example below)you want to 'expose'   
  entities:
     script.1605808203118:
       name: "zoom lighting"
       hidden: false
     script.toggle_cupboard_light:
       name: "toggle cupboard light"
       hidden: false
 expose_by_default: false
# If expose by default is true you risk adding an unmanageable number of entities 
# to ALEXA. Read the Emulated hue doc if you want to expose just the entities/domains you need as above.

Create a script to act as a light toggle

toggle_cupboard_light:
   alias: toggle cupboard light
   sequence:
 service: light.toggle
 target:
   entity_id: light.cupboard
 delay:
   hours: 0
   minutes: 0
   seconds: 5
   milliseconds: 0
 mode: single 

Create a routine in Amazon Alexa

  • Outline:
    • Go to the Alexa app and find ‘Routines’. Create a new routine
    • Decide on the trigger event eg you press an Echo button or say something
    • Under add action > Smart Home > Control device. Find your script called ‘toggle cupboard lights’
  • For the detail on using Alexa see Automated Home Party – toggle lights and switches.




Leave a Reply

Your email address will not be published. Required fields are marked *