I originally posted this on Reddit and thought I’d share it here as well.
I was trying to work out how to make switches which are room aware when using Alexa. Lights can already be room aware - if you have lights in a group and add an Echo into the same group, you can just say “Alexa, turn on the lights” and it will turn on the lights in the same group as the Echo. However, this doesn’t seem to work for switches. I came up with this workaround. This is based on turning a television on or off, but can be adapted for other devices.
1) Follow the instructions at https://github.com/walthowd/ha-alexa-tts to set to the alexa_remote_control.sh script (you don’t need the alexa_wrapper.sh script unless you want to allow text-to-speech notifications to your Echo devices).
2) Define a sensor like this:
sensor:
- platform: command_line
name: Last Alexa Device
command: "/home/homeassistant/.homeassistant/alexa_remote_control.sh -lastalexa"
This sensor uses the -lastalexa option of the remote control script, which determines which Alexa device on your account was accessed most recently.
3) Create a template switch like this:
switch:
- platform: template
switches:
television:
friendly_name: "Television"
value_template: "off"
turn_on:
service: script.room_dependent_television
data:
state: on
turn_off:
service: script.room_dependent_television
data:
state: off
4) Create a script like this:
room_dependent_television:
sequence:
- service: homeassistant.update_entity # force update of sensor.last_alexa_device to determine which device this was requested from
data:
entity_id:
sensor.last_alexa_device
- service_template: >-
{% if state %}
homeassistant.turn_on
{% else %}
homeassistant.turn_off
{% endif %}
data_template:
entity_id: "switch.{{ states('sensor.last_alexa_device') | replace(' ','_') | lower }}_television"
Note: This script assumes that the individual televisions are controlled by switches named like switch. echo_device_name _television where echo_device_name is the name of the Echo device which should control that television with spaces replaced with underscores (e.g. “My Bedroom” becomes “switch.my_bedroom_television”). You could use logic in the data_template if this is not the case.