How to identify a disconnecting USB device using udev rules?

假如想象 提交于 2019-12-03 15:02:25

i'd suggest first thing check udev events on device "remove" event by running e.g. udevadm monitor --kernel --property --subsystem-match=usb and disconnecting your devices in turn and comparing outputs. Here on a single mouse disconnect i get two events:

KERNEL[6680.737678] remove   /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0 (usb)
ACTION=remove
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2/2-1.2:1.0
DEVTYPE=usb_interface
INTERFACE=3/1/2
MODALIAS=usb:v09DAp000Ad0034dc00dsc00dp00ic03isc01ip02in00
PRODUCT=9da/a/34
SEQNUM=2835
SUBSYSTEM=usb
TYPE=0/0/0

KERNEL[6680.739577] remove   /devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2 (usb)
ACTION=remove
BUSNUM=002
DEVNAME=/dev/bus/usb/002/006
DEVNUM=006
DEVPATH=/devices/pci0000:00/0000:00:1d.0/usb2/2-1/2-1.2
DEVTYPE=usb_device
MAJOR=189
MINOR=133
PRODUCT=9da/a/34
SEQNUM=2836
SUBSYSTEM=usb
TYPE=0/0/0

You can write your rule invoking a script which should do some job after examining some specific environment variable. A rule may be as simple as

SUBSYSTEM=="usb", ACTION=="remove", RUN+="/usr/local/sbin/usbdevgone.sh"

In your case i'd suggest checking $DEVPATH inside usbdevgone.sh as they should differ for your two otherwise identical devices. Also you may pass devpath (this is a path in /sys/ filesystem) as an argument to your script like this (see man udev for a list of available substitutions):

SUBSYSTEM=="usb", ACTION=="remove", RUN+="/usr/local/sbin/usbdevgone.sh $devpath"

Do not forget to notify udevd of your new or changed rule with udevadm control --reload-rules

Phil

I have run into the same problem in Linux. The information sent on a remove is minimal and cannot be used to uniquely identify the device being removed. I used to use the PHYDEVPATH (which is unique on plug in and unplug for a given machine and USB port), but very unfortunately, that has been deprecated in later versions of udev.

I was writing an application with similars features and I solved the problem implementing a daemon with the only mission of storing the udev_device connected. So when I detect some remove even from the udev_monitor I check for some device missing on the deamon's devices list. That what is missing is the device disconnected. That way I can obtain the data of disconnected devices.

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