To do this in an app I use this code. As a beginner I’m not 100% sure this is the best way to do things, but it works. Note that above the service is “switch.turn_off” but in the code you simply use “turn_off”. It would be interesting if someone could provide clarity.
from appdaemon.plugins.hass import hassapi as hass
class ChangeStateTest(hass.Hass):
def initialize(self):
self.log("Initialising / reloading class ChangeStateTest")
athome_plug_entity = self.get_entity("switch.athom_plug_1")
athome_plug_state = athome_plug_entity.get_state(attribute="state")
self.log(f'athom plug state is {athome_plug_state} type {type(athome_plug_state)}')
if (athome_plug_state == 'off'):
self.log("Plug is off. Turning on")
athome_plug_entity.call_service('turn_on')
self.log("Plug turned on")
if (athome_plug_state == 'on'):
self.log("Plug is off. Turning off")
athome_plug_entity.call_service('turn_off')
self.log("Plug turned off")