Execute a function when connecting an android mobile to the pc with python linux

216 Views Asked by At

I want to execute a python function when detecting when I connect the mobile to the pc (in Transfer Files mode), I use linux mint, what I have tried so far has been thanks to the pyudev library:

from pyudev import Context, Monitor

context = Context()
monitor = Monitor.from_netlink(context)
for device in iter(monitor.poll, None):
    print(device.action)

When I connect the mobile in Transfer Files mode it shows me 6 outputs:

remove
unbind
remove
add
add
bind

And when I disconnect it shows me:

remove
unbind
remove
add
add
bind

Which is basically the same, I would also like to know how to filter if what has been connected is a USB, a removable disk or a mobile phone, for example, a library that I have also been trying to test is pymtp:

import pymtp

mtp = pymtp.MTP()
mtp.connect()

print("Device name:", mtp.get_devicename())

But apparently, it focuses more on connecting the device than notifying me when a new one has been connected, besides that code only returns:

Device 0 (VID=2717 and PID=ff40) is a Xiaomi Mi-2s (id2) (MTP).
Android device detected, assigning default bug flags
Device name: None
1

There are 1 best solutions below

0
Roland Smith On

Have a look at the filter_by or filter_by_tag methods of the Monitor.

With these filters you can ensure that you only receive events from the device you are interested in.