Hi all – looking for a bit of advice please…
I have a custom integration that reads data from a web API, and it’s working just fine via local polling. The API source is a file-download service that returns bandwidth use and can also return an array containing the current state of each file that’s being downloaded (in progress, completed, etc).
The Update() function does all the API-call work right there and then, and the user can amend SCAN_INTERVAL as required. Entity.should_poll is enabled by default so Home Assistant is periodically calling it (I think that’s how it works!)
I’d like to extend my integration with an event for when each file moves to ‘completed’ state. I could just check for that during the Update() phase, but it’s possible that the user might select a long update interval and I’ve got it in my head that I’d like the event to be raised by HA as soon as is practically possible, and not rely on the update interval. The web API doesn’t support creating Webhooks unfortunately so I’ll have to poll the current state, compare with the previous state and act appropriately.
After a bit of research and looking at the code in other integrations I believe I can see two ways of doing this:
- My integration owns all update timing by setting entity.should_poll to false, make use of the DataUpdateCoordinator function to get the file state info often (say every 10 seconds or so) and use that information to raise events as appropriate, but keep on using the user-defined SCAN_INTERVAL when updating the other sensors.
- Keep the integration’s should_poll to True, but use the Threading import to spin off a function that periodically and asynchronously does its own API call to the web service and raises events as required. Fortunately that function would be quite self-contained and doesn’t really need to interact with the rest of the code from what I’m thinking. Obviously I’d be responsible for thread management which is a little bit of an overhead, but not much I don’t think.
I haven’t tried either yet – I’m thinking that the Threading option is going to be the easiest to insert without significant code changes, but I’m not sure what the preferred ‘Home Assistant’ way is yet.
Thoughts?