What is the update trigger for MQTT sensor based on a home assistant entity

I have a sensor in HA that is created by MQTT auto-discovery. However I am the one that created the auto-discovery data in my MQTT client, using the MQTT.Publish service. The unique thing about this sensor is that its state is set based upon a HA entity, as opposed to a MQTT topic. In other words, the value_template JSON key has a value that refers to a home assistant entity_id.

I thought everything was working, but the issue I’m having is long delays to the MQTT sensor after the HA sensor changes state.

Here is the data as it exists pulled from my MQTT server:

{
  "name": "Tesla Model 3 Location",
  "unique_id": "teslamate_cars_1_location/location",  
  "icon": "mdi:car",  
  "value_template": "{{ \"home\" if \"home\" in (states(\"sensor.tesla_model_3_geofence\") | lower) else \"not_home\" }}",
  "state_topic": "teslamate/cars/1/latitude",
  "json_attributes_template": "{{ { \"latitude\": value | float(0), \"longitude\": states(\"sensor.tesla_model_3_longitude\") | float(0) } | tojson }}",
  "json_attributes_topic": "teslamate/cars/1/latitude",
  "device": {
    "identifiers": ["teslamate/cars/1"],
    "name": "Tesla Model 3",
    "sw_version": "2023.12.1"
  }
}

Here is an image showing the issue. The “device_tracker.tesla_model_3_location” entity, which is auto-created by the MQTT data above, does not get its state updated for over 15 minutes after the sensor.tesla_model_3_geofence entity has a state change. Since the device tracker entity is tied to the state_topic teslamate/cars/1/latitude, I thought maybe it only gets updated when that topic has an update. But I graphed the sensor that is based on that topic, and it shows that it was updating right until the geofence changed.

So my ultimate question is: how can I force an update to the MQTT sensor so that it refreshes based on the latest status of the home assistant entity_id?

Answer to my own question:

What state is the geofence sensor in when it is not at home? Just observing that:

{{ "home" in "not_home" }}

returns true

Good point! The code did work though, because the geofence MQTT topic has an empty value when not in a defined geofence area, unlike a home assistant device_tracker entity which would show not_home. But there would be unintentional results if I would have defined a geofence region called “parents_home” for example.

I changed my code for a different reason but looking back at it now, it’s avoiding this issue:
value_template: \"home\" if value | lower == \"home\" else \"not_home\"

1 Like