twrecked / hass-virtual

Virtual Components for Home Assistant
GNU General Public License v3.0
167 stars 28 forks source link

Access binary sensor via api, not working #102

Closed Outsidewall closed 5 months ago

Outsidewall commented 5 months ago

Hello,

This is might be just my understanding of how the HA api works, however, I have a small bit a python that, operates a virtaul switch, works fine, see output below and then attempts to set a binary_sensor, this fails, <400> again see output below.

image

Here is the virtual.yaml file

version: 1 devices: Occupied:

twrecked commented 5 months ago

You need to use the virtual.turn_on service. Home Assistant sensors are read-only by design.

See the single line at the bottom of this section. (And I just noticed the docs aren't great on this. I'll try to make some time to improve them.)

Outsidewall commented 5 months ago

Given up on trying set the sensor via the api/restful interface. Is there away from mqtt? so far no joy here either.

twrecked commented 5 months ago

It works here for me:

Get the state:

curl \
  -H "Authorization: Bearer whatever-it-was" \
  -H "Content-Type: application/json" \
  https://localhost:8123/api/states/binary_sensor.mezzanine_motion_motion

{"entity_id":"binary_sensor.mezzanine_motion_motion","state":"off","attributes":{"persistent":true,"available":true,"device_class":"motion","friendly_name":"Mezzanine Motion motion"},"last_changed":"2024-06-06T22:27:54.757155+00:00","last_reported":"2024-06-06T22:27:54.757155+00:00","last_updated":"2024-06-06T22:27:54.757155+00:00","context":{"id":"01HZQTMV85ST05CHTCFP06V2P6","parent_id":null,"user_id":null}}

Toggle the state; you can also use virtual/turn_on and virtual/turn_off.

curl \
  -H "Authorization: Bearer whatever-it-was" \
  -H "Content-Type: application/json" \
  -d '{"entity_id": "binary_sensor.mezzanine_motion_motion"}' \
  https://localhost:8123/api/services/virtual/toggle

[]

Get the state again, it's now on:

curl \
  -H "Authorization: Bearer whatever-it-was" \
  -H "Content-Type: application/json" \
  https://localhost:8123/api/states/binary_sensor.mezzanine_motion_motion

{"entity_id":"binary_sensor.mezzanine_motion_motion","state":"on","attributes":{"persistent":true,"available":true,"device_class":"motion","friendly_name":"Mezzanine Motion motion"},"last_changed":"2024-06-06T22:28:06.283152+00:00","last_reported":"2024-06-06T22:28:06.283152+00:00","last_updated":"2024-06-06T22:28:06.283152+00:00","context":{"id":"01HZQTN6GBW674G51HZQKRVW7N","parent_id":null,"user_id":null}}
Outsidewall commented 5 months ago

Thank you for the details, seems I did not understand to use the /api/services/virtual call. I was trying /api/services/binary_sensor !