Getting state & attributes from an unconnectable device to HA REST API

I have a device that intentionally cannot be reached from the network that Home Assistant is running in. However, the device itself is able to contact HA address, and therefore I’d like to get the availability and some data from it logged into HA.

I have attempted to solve this by making the device POST to HA’s REST API / Websocket (what ever it is called) simply running a curl script on the device. This works fine, however, still seems to be only half the solution since I can obviously never get the state to flip to not_home / unavailable since there is no mechanism to change state when the device happens to drop offline.

I have browsed the forum and found some solution to use separate py script in HA to flip the state time to time but I’m not a fan of something that custom & complicated. There must be something simpler, right?

Adding a separate template sensor with time_pattern trigger could be another way but apparently the device class cannot be a device_tracker anymore (which I would prefer).

Any other ideas, or how should I approach this whole problem differently?


The update script running on device:

#!/bin/sh
myip=$(/sbin/ifconfig vlan1 | grep -i mask | awk '{print $2}'| cut -f2 -d:)
update=$(date +%Y-%m-%dT%H:%M:%S)
somedata=...
curl -X POST -H "Authorization: Bearer THEREALLYLONGSECRETKEY" \
  -H "Content-Type: application/json" \
  -d '{"state": "home", "attributes": {"ip": "'"$myip"'", "data": "'"$somedata"'", "last_connection": "'"$update"'"}}' \
  http://123.123.123.123:8123/api/states/device_tracker.mydevice

(with the ever changing “update” attribute included in the POST this device_tracker will always refresh its last_updated attribute)

Separate sensor to get the state to change when there has been no contact for a while, using the last_updated attribute (my custom last_connection would likely work just the same):

template:
    - trigger:
        - platform: time_pattern
          minutes: "/5"
      sensor:
        - name: mydevice_just_the_state
          state: '{% if (as_timestamp(now())-as_timestamp(states.device_tracker.mydevice.last_updated)) > 180 %}not_home{% else %}home{% endif %}'

(should perhaps put here something else than home / not_home, or just binary_sensor with on / off would do as well)

If you’re using MQTT already and the device can access it, you could use that instead. An MQTT sensor can have a expire_after property.

So, for example, your device could publish with:

mosquitto_pub -h mqtt-server -u username -p password -t my/topic/of/choice -m "On (or whatever payload you want)"

Not using MQTT for anything atm, and a little unsure if I’d like to set one up just for this. But that expire_after thing seems exactly what I’m looking for. Too bad if there is nothing like it available for other sensors / device_trackers.