How to update a sensor from an automation?

I retrieve events from calendars and need to put them into a sensor(*) which is then retrieved by an unrelated application via a WebSocket connection to HA.

The way I do this today is rather convoluted (but it works)

  • I call the list_events service and set the response field
  • I raise an event with this response field contents (calendarResponseEvent)
  • I configured in configuration.yaml
  - trigger:
    - platform: event
      event_type: calendarResponseEvent
    sensor:
      - name: calendarW
        unique_id: calendarW
        state: "{{ trigger.event.data.response.events | count() }}"
        attributes:
          calendar_response: "{{ trigger.event.data.response }}"
        icon: mdi:calendar

This ultimately sets the sensor to the number of calendar entries, and its attributes to the future calendar entries

I will be switching from list_events to get_events (list_events is deprecated) so I decided to simplify all of this because it took me a shameful time to understand what was going on with the calendar sensor (I set it up a year or two ago and forgot in the meantime what I did)

My question: is there a way to directly populate a sensor from within an automation with the content of the answer of a service? (by “directly” I mean within the automation itself). I would create the sensor as a sensor template helper (I think)


(*) any better ideas are welcome

You could use a calendar trigger and use an input_text helper to store the entry:

alias: "[Reminder] [SMS] Calendar"
description: ""
trigger:
  - platform: calendar
    event: start
    offset: "-22:0:0"
    entity_id: calendar.my_google_calendar
condition: []
action:
  - service: input_text.set_value
    metadata: {}
    data:
      value: Reminder - {{ trigger.calendar_event.summary }} tomorrow
    target:
      entity_id: input_text.calendar_event
mode: queued

The offset triggers the automation 22 hours before the event.

I need to retrieve all events between “now” and “now+2 days” so there will be multiple entries. I run my automation every minute.

I would ditch the automation entirely and do everything from your trigger-based template sensor. You can change the trigger to a time pattern (every minute if that is what you want).
Add an actions section to your template sensor and you can call the get_events service from there. Then you can use that response to populate an attribute of that same sensor.

The docs walk through a similar example for calling a weather forecast service:

2 Likes

This is an excellent idea - thank you.

I was fixed on finding a solution through the GUI (I am moving as much as possible there) and did not investigate enough what I can do in configuration.yaml