What to use - 'device' or 'state'?

Hi guys,

Sorry if this question was already asked and answered but if not, maybe someome could explain me please what is the “correct” way of using ‘device’ and ‘state’ and when each one should be used?

I discovered that now we can have two (at least) ways of triggering an automation - either when ‘device’ chages its state or when a ’ state/entity’ changes one of its attributes. It almost sounds like the same but it is not.

I spent quite a bit of time trying to do a very simple thing - create automation that creates a persistent notification with button’s name once that button is pressed.

I used {{ trigger }} to do that but it failed all the time, untill I changed from ‘device’ to ‘state’. Trying to see what was going on I created a simple automation:

alias: TEST2
description: ""
trigger:
  - platform: device
    domain: mqtt
    device_id: 239cc94c0346316a08c08086840d7320
    type: action
    subtype: single
    discovery_id: 0x00158d0001eb9b6b action_single
    enabled: true
  - platform: state
    entity_id:
      - sensor.0x00158d0001eb9b6b_action
    attribute: action
    to: single
condition: []
action:
  - service: persistent_notification.create
    metadata: {}
    data:
      message: Sensor {{ trigger }} triggered!
    enabled: true
mode: single

and I got this:

Sensor {'id': '0', 'idx': '0', 'alias': None, 'platform': 'mqtt', 'topic': 'zigbee2mqtt/0x00158d0001eb9b6b/action', 'payload': 'single', 'qos': 0, 'description': 'mqtt topic zigbee2mqtt/0x00158d0001eb9b6b/action'} triggered!


Sensor {'id': '1', 'idx': '1', 'alias': None, 'platform': 'state', 'entity_id': 'sensor.0x00158d0001eb9b6b_action', 'from_state': <state sensor.0x00158d0001eb9b6b_action=; action=, battery=100, device_temperature=33, last_seen=2024-04-06T20:46:07+10:00, linkquality=116, power=57, power_outage_count=3332, temperature=21, voltage=3335, icon=mdi:gesture-double-tap, friendly_name=Test Xiaomi Square Button action @ 2024-04-06T20:46:07.300020+10:00>, 'to_state': <state sensor.0x00158d0001eb9b6b_action=single; action=single, battery=100, device_temperature=33, elapsed=984432, last_seen=2024-04-06T21:02:31+10:00, linkquality=142, power=57, power_outage_count=3332, temperature=21, voltage=3335, icon=mdi:gesture-double-tap, friendly_name=Test Xiaomi Square Button action @ 2024-04-06T21:02:31.730553+10:00>, 'for': None, 'attribute': 'action', 'description': 'state of sensor.0x00158d0001eb9b6b_action'} triggered!

The first part came from ‘device’ and the second part was from ‘state’.

Now I realized why my automation did not work as intended when I was using ‘device’ as a trigger. But now the question is - why do we ever have ‘device’ if all of that and much more could be achieved by using ‘state’ ?
I assume there is a reason for that so could someone tell me please why we have a ‘device’ in HA and how/when to use it??

Thank you!

3 Likes

Great article, the one you mentioned, definitely what I was looking for, thank you!!