usb automatic detection in python for linux env

只愿长相守 提交于 2019-12-04 05:52:09

问题


I'm using polling command(glob('/dev/tty[A-Za-z]*')) in python to detect usb devices connected to my linux pc in regular interval for my application. Is there any way to detect usb devices connected automatically?


回答1:


Here is a start. You can find your usb vendor here. You got to code yourself a current_list_usb, set a time interval to check so you can compare and see if a new device is attached or not. Some code to use when importing usb module:

import usb, usb.core, usb.util, usb.backend.libusb1

...snippet...

#    usb.core.find()
# find our device

dev = usb.core.find(idVendor= ...., idProduct= ....)
#dev_1 = usb.util.find_descriptor(cfg, find_all =True)

# was it found?
if dev is None:
    raise ValueError('Device not found')

#x = dev.set_configuration()
#print (dev)
#print (help(usb.core))
if usb.core.find(find_all=True, bDeviceClass=7) is None:
    raise ValueError('No printer found')



回答2:


The normal way to do this is to make a udev rule that tells your program a new tty exists.

A custom udev rule may look something like this(let's call it /etc/udev/rules.d/50-custom-tty.rules:

KERNEL=="ttyUSB[0-9]+", RUN+="/usr/bin/my-program"

Here's a good guide on writing udev rules.

In this case, the program /usr/bin/my-program will run whenever a new ttyUSB device is created in /dev; udev will set a bunch of environment variables to tell you exactly what was just plugged in. You can then notify your main program that a new ttyUSB exists, and it should use it. Note that whatever program you run should be small, as otherwise the udev daemon will kill it if it takes too long.




回答3:


I'd suggest using libudev and creating a udev monitor object to detect hotplugged devices. Here is a starting point for you to learn about libudev and its monitor feature:

https://www.freedesktop.org/software/systemd/man/libudev.html

There might be a good Python library already that wraps udev so you can use its features without writing C code.



来源:https://stackoverflow.com/questions/47857410/usb-automatic-detection-in-python-for-linux-env

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!