Can't Turn On/Off Switches/Lights Remotely

I have used the following code to remotely turn on a switch or light

    response = requests.post(
        eg.globals.haServer + '/states/switch.sump_pump_room_light_switch',
        headers={'Authorization': 'Bearer ' + eg.globals.haAuth, 'content-type': 'application/json'},
        data=json.dumps({'state': 'on', 'attributes': {'hidden': 'false', 'friendly_name': 'Sump Pump Room Light'}}))

While this will update the switch/light state within Lovelace and/or the Device State, the switch is not physically turn on. I have tried this with several switches and lights and the UI updates the new state none of these devices actually turn on/off.

If I change [switch.sump_pump_room_light_switch] within the above code to [binary_sensor.sump_pump_room_door_contact] and execute the code the HA automation below is executed:

  alias: 'Sump Pump Door.Open'
  trigger:
    platform: state
    entity_id: binary_sensor.sump_pump_room_door_contact
    to: 'on'

  action:
    - service: homeassistant.turn_on
      entity_id: switch.sump_pump_room_light_switch
    - service: shell_command.egmsgnopay
      data_template:
        message: 'HA.SumpPump.Sensor.contact.open'

This works fine and the light turns on.

My question is, why do I need to go thought this hoop by simulating a door opening to trigger an automation just to turn on the light? Why does the above code update the device state within HA but not turn on/off the physical device?

You are using the states endpoint, but you should use the services endpoint to actually call a service (e.g. turn light on). The states endpoint only sets the state of the device but that doesn’t do anything physically. See here for more details.

1 Like

Thank you. Worked like a charm…

    x = response = requests.post(
        eg.globals.haServer + '/services/switch/turn_on',
        headers={'Authorization': 'Bearer ' + eg.globals.haAuth, 'content-type': 'application/json'},
        data=json.dumps({'entity_id': 'switch.sump_pump_room_light_switch'}))
1 Like