postlund / pyatv

A client library for Apple TV and AirPlay devices
https://pyatv.dev
MIT License
838 stars 91 forks source link

Proper way to reconnect after ATV user change #2295

Closed JetA2 closed 5 months ago

JetA2 commented 7 months ago

What do you need help with?

Hi and thanks for an awesome library!

I've made a small Python service that listens for play state changes from my Apple TV 4K. It works great, but I noticed that no more status updates are sent when the user is changed on the ATV.

I connected a device listener and found that the connection_closed event is triggered when I switch users. My plan is to simply attempt to reconnect when this event is triggered and I'm wondering how to do this properly.

What is the state of the ATV object after this event is triggered? Can I use the same object to connect again? Do I have to recreate listeners? Or should I call close on the ATV object and start from the beginning?

Grateful for any help!

postlund commented 6 months ago

Sorry for the delay! After a disconnect, the atv object is put into a blocked state and you need to re-connect again. Calling any methods on the old object will result in BlockedStateError IIRC. So you will need to set up listeners and all of that again.

JetA2 commented 5 months ago

Yes, I ended up starting from scratch after a disconnect. Reconnecting straight away would sometimes throw ConnectionRefusedError or asyncio.TimeoutError so a few retries could be necessary.

Works great now, I'm using it to turn on/off the lights when pausing/playing. Very useful!