Custom Entity / State in Home Assistant#

Warning

🔥 highly experimental stuff here 😅

Idea: Instead of using Baby Buddy [1], create an entity named baby and set its state accordingly, i.e. one of

  • sleep

  • eat

  • drink

  • piss

  • shit

  • play

Create the Entity#

Settings > Devices & Services > Helpers > Template

  • template a sensor

  • Name: baby

  • State template: the literal string idle

Get API Key#

/profile > Security > Long-lived access tokens: Create Token

  • name: e.g. felix@locutus

Set State via REST API#

https://developers.home-assistant.io/docs/api/rest/

TOKEN=
curl \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"state": "sleep"}' \
  http://localhost:8123/api/states/sensor.baby

Set State via Button#

That’s not the way Home Assistant thinks about things (sensors provide state), so we have to work around that.

Enable python script integration: configuration.yaml

python_script:
mkdir config/python_scripts
cat <<'EOF' > config/python_scripts/set_state.py
entity = data['entity_id']
hass.states.set(entity, data['state'])
EOF

Add Button, set YAML:

square: true
type: grid
cards:
  - show_name: true
    show_icon: true
    name: sleep
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: sleep
      target: {}
    icon: mdi:baby-face-outline
  - show_name: true
    show_icon: true
    name: eat
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: eat
      target: {}
    icon: mdi:baby-face-outline
  - show_name: true
    show_icon: true
    name: drink
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: drink
      target: {}
    icon: mdi:baby-face-outline
  - show_name: true
    show_icon: true
    name: poop
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: poop
      target: {}
    icon: mdi:baby-face-outline
  - show_name: true
    show_icon: true
    name: play
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: play
      target: {}
    icon: mdi:baby-face-outline
  - show_name: true
    show_icon: true
    name: cry
    type: button
    tap_action:
      action: call-service
      service: python_script.set_state
      data:
        entity_id: sensor.baby
        state: cry
      target: {}
    icon: mdi:baby-face-outline
columns: 3

Sources#

Next Steps#

  • reduce duplication (jinja for-loop)

  • get name from button (if that’s even possible)

  • think of / find something better than this hack ;)