2023.7: Responding services

Not sure why it’s being characterized as “trickery”.

What petro suggested leverages the strengths of a Trigger-based Template Sensor, namely the ability to set its state, and/or attributes, to whatever you want via any kind of trigger. In other words, the example is using a Trigger-based Template Sensor the way it’s meant to be used.

The example ‘publishes’ the data via a custom event:

      - event: chatgpt_response
        event_data:
          entity_id: "{{ trigger.entity_id }}"
          response: "{{ chatgpt.response.speech.plain.speech }}"

The Trigger -based Template Sensor ‘subscribes’ to the custom event and receives the data (via trigger.event.data.response):

      - platform: event
        event_type: chatgpt_response
        event_data:
          entity_id: media_player.volumio_2

The Trigger-based Template Sensor uses the received data to set the value of one of its attributes. Easy-peasy (and that value survives a restart).


FWIW, what petro suggested is something I first discovered from these examples by CentralCommand and TheFes:

It’s a pattern I have also employed to fulfill other applications that require storing a value in a sensor’s attribute (with and without the use of custom events). Examples:

Message Queue

Last Ten Motion Detectors

Bad Shutdown Sensor

Song History

It’s a useful design pattern and far from being ‘trickery’.


Your proposed new service call, input_text.set_attribute, would probably need to be called multiple times, once for each attribute you wanted to set … unless it supported setting multiple attributes at once. Here’s a mockup of what the service call could look like:

service: input_text.set_attribute
target:
  entity_id: "input_text.{{ trigger.to_state.object_id }}"
data:
   attribute: album_description
   state: "{{ chatgpt.response.speech.plain.speech }}"

The main difference is that creating an Input Text is admittedly easier than a Trigger-based Template Sensor. Unless there’s an existing Feature Request, feel free to post a request for this new service call.

5 Likes