leng-yue / py-scrcpy-client

An easy to use python scrcpy client
https://leng-yue.github.io/py-scrcpy-client/
MIT License
283 stars 71 forks source link

[Help] How to attach a callback to a disconnect event? #38

Closed FieryRMS closed 1 year ago

FieryRMS commented 1 year ago

How do I detect when a device is disconnected? The scrcpy program is able to tell when it gets disconnected and closes the stream with a log WARN: Device disconnected. But when I disconnect when using the python client, the frame feed just stops and there are no logs. I tried using adb.wait_for but it is a blocking function.

leng-yue commented 1 year ago

Previously, the following code will throw an error: https://github.com/leng-yue/py-scrcpy-client/blob/c40f6e350b01c2ee23b1ffcdec57455d0012df46/scrcpy/core.py#L231
However, I noticed that if you start the scrcpy client in a daemon thread, there is no way to understand if the client is disconnected. So I fixed it in v0.4.6. In this version, the self.alive will be set to false when disconnected. https://github.com/leng-yue/py-scrcpy-client/blob/01b2e653f9796f200951a2d1d5edaa54d3c16197/scrcpy/core.py#L244

If there is any bug, feel free to ask.

FieryRMS commented 1 year ago

Running the below code always prints True, even when I remove the phone from my laptop.

import scrcpy

client = scrcpy.Client()
client.start(threaded=True)

while(1):
    print(client.alive)
leng-yue commented 1 year ago

Which version are u using?

FieryRMS commented 1 year ago

0.4.6

leng-yue commented 1 year ago

The video stream may be empty if a user is not active. For example, some devices won't send a new frame if you don't click the screen for a while. And when the device is disconnected, didn't your video stream raise an IO Error, like BrokenPipe?

FieryRMS commented 1 year ago

Yes, what you describe does happen on my phone. I am using a Galaxy A20s, and not touching the screen for a while stops triggering the EVENT_FRAME event, but I noticed that it throws an BlockingIOError on self.__video_socket.recv until I do. No error was raised, it just stops calling my on_frame function.

leng-yue commented 1 year ago

Sounds good, I left some comments on your PR :)