Using libusb from python or ruby

May 28, 2013

Ruby: libusb

Do this:
gem install libusb
This gave me libusb-0.3.4, which works on top of libusb-1.0. It also has an alternate class that supports libusb-0.1, but you should take care to ignore this, it only serves as a place you can wander to in the documentation and get confused.

The documentation is pretty sketchy, and if you are not already very familiar with libusb C programming, this will be very hard.

There is also an older ruby gem "ruby-usb" that works only with libusb-0.1 and which you should absolutely avoid and ignore.

I was irritated that there is no method to loop through busses (like there is in native libusb). But frankly you can just use the command line "lsusb" to do most things I had in mind for this. Here is a script that does a fair imitation of lsusb:

#!/bin/ruby

require 'libusb'

usb = LIBUSB::Context.new

dev = usb.devices
dev.each { |d| puts d.inspect }

Python: pyusb

Even if you never intend to use python and pyusb, be sure and read this: In your python script, do "import usb.core", not "import usb". Apparently if you do the latter, you get usb.legacy and some old mode that you may as well not get tangled up with.

Python always drives me nuts with its brain-damaged indentation syntax, but it balances that weirdness with nice packages like this one, and a lot of people seem to like it.

Permission issues

You will probably have to run as the super user to have permission to access whatever devices these libraries need to access. This is certainly true with pyusb. If you really want to avoid this, you can set up special udev rules. Use lsusb to find out the vid and pid of your device. Then create a file named 50-gizmo.rules to the folder /etc/udev/rules.d that contains the following (assuming your user name is wally) :
SUBSYSTEM !="usb_device", ACTION !="add", GOTO="gizmo_rules_end"
SYSFS{idVendor} =="03eb", SYSFS{idProduct} =="204f", SYMLINK+="gizmo"
MODE="0666", OWNER="wally", GROUP="wally"
LABEL="gizmo_rules_end"

Feedback? Questions? Drop me a line!

Tom's Computer Info / tom@mmto.org