Wait for state change for light turn_on/turn_off methods

I have written an integration which calls and external API to trigger a turn_on or turn_off (through a PyPi library), but the state doesn’t update immediately through the API.

I get a success message back from the API for the service call to change the state, but Home Assistant doesn’t get the actual state change update for several seconds (up to 45 seconds) from the API when updating the data coordinator.

Anyone have any idea how to wait for the state to change before updating the state in Home Assistant? I can’t find any real examples where this is an issue with other integrations, but I’m sure it must exist.


light behaviour
This is the behaviour I’m seeing. But I have implemented a wait for the async_track_state_changed_event which is doing as expected in the turn_on and turn_off methods.

Here’s what is happening:
Hit the switch in Lovelace to turn_off the lights which calls the turn_off method of the entity.

I have confirmed through logging that the turn_off method calls the API to issue the command, then waits for the state to change through async_track_state_change_event, then isues the self.async_schedule_update_ha_state()

In Lovelace, the switch turns off momentarily, then flips back on because the state reported by the data update coordinator still shows ON from the API status returned.

Once the state change happens in the API status, the switch turns back off reflecting the updated state.