How to access a sensor's state in an automation?

I receive MQTT messages with a specific payload and would like to start different automations depending on a subset of this payload.

The payload is of the form XXXXXXYYYYYY where

  • YYYYYY is the identificator of a switch (this is what I will match in a condition)
  • XXXXXX is unpredictable, changing and will be useful in state updates - it changes at every message (and therefore, when used as a state, changes the state)

In order to use it, I borrowed from @danpow solution and created a sensor in configuration.yaml which holds that payload:

sensor:
  # sensors to process MQTT messages from RF wall switches (keep the last 6 chars)
  # see https://community.home-assistant.io/t/extract-and-match-time-from-mqtt-payload-to-aid-automation/35546/2
  - platform: mqtt
    name: 'rf433_switch_payload_full'
    state_topic: 'rfbridge-1/rfin'

I expected to use this sensor later in a set of automations, such as

- id: 'wall_switch_ch2_lampe_pixar'
  alias: wall switch chambre 2 lampe pixar
  initial_state: True
  trigger:
    - platform: state
      entity_id: sensor.rf433_switch_payload_full
  condition:
    condition: template
    value_template: "{{ state_attr('sensor.rf433_switch_payload_full','state')[-6:] == '5976A1' }}"
  action:
    data:
      entity_id: light.ch1_lampe_bureau
    service: homeassistant.toggle

The value-template line creates all kind of errors when the automation is triggered.
I tried various incantations to retrieve the actual content of the sensor (that is, XXXXXXYYYYYY in the example above): sensor.rf433_switch_payload_full.state, state.sensor.rf433_switch_payload_full.state and others. Blindly, as I cannot peek at the actual object.

How can I access what I see as β€œState” in the entity sensor.rf433_switch_payload_full?

{{ states('sensor.rf433_switch_payload_full') }}
or
{{ states.sensor.rf433_switch_payload_full.state }}

Should give you the state.
Copy and paste the template in Dev Tools/Templates and you can play with it.

2 Likes

Thank you so much.

I was very close using state... instead of states... (which I could not find in the docs - it is probably somewhere but it did not jump to my face when searching).

For your bookmarks: :slightly_smiling_face:

I must be dumb (or the docs are organized in a way my brain cannot process). I read Conditions - Home Assistant and State objects - Home Assistant up and down and could not find what I was looking for.

Then comes your documentation which describes exactly what I needed. Thanks a lot.

This worked in my automation. Thanks for the solution.

  - data:
      message: 'Garage power: {{states.sensor.shelly1pm_energy_power.state}}W.'
      title: Garage Power Monitor
    service: notify.mobile_app_my_fon

Displays message: Garage power 12W.