Tux

...making Linux just a little more fun!

2-cent tip: finding a USB device with Perl

Samuel Bisbee-vonKaufmann [sbisbee at computervip.com]


Sat, 29 Dec 2007 06:05:08 +0000

Greetings,

I got a USB toy for Christmas that didn't have a *nix client. After some detective work I found a Perl module that did what I needed, except that the module tried to access the toy with specific vendor and product ids. For whatever reason my toy's ids did not match, so I modified the module to search for my device. [1]

The first step is to find the product name for your device. This is easily done with `lsusb` on the command line.

Next, break our your text editor and write some code. Remember, because Perl uses libusb you will have to run your code as root; if you get errors about being unable to access the device, then this is probably the cause.

Here is the code that I used (was inside a sub, hence the use of 'return'):

my $usb = Device::USB->new;
my $dev;
foreach($usb->list_devices())
{
  $dev = $usb->find_device($_->idVendor(), $_->idProduct()) and last if $_->product() eq "YOUR PRODUCT'S NAME FROM lsusb";
}
 
return -1 if !$dev;
This code iterates over the buses, checking each product's name for our device's name from `lsusb`. If the device is found, then it will store the handler in '$dev' and break out of the loop, else it will bubble the error up by returning a negative value. When the device is found you would claim and control it as normal (example in the 'new()' sub from http://search.cpan.org/src/PEN/Device-USB-MissileLauncher-RocketBaby-1.00/lib/Device/USB/MissileLauncher/RocketBaby.pm).

If you are interested, I was playing with Device::USB::MissileLauncher::RocketBaby (http://search.cpan.org/~pen/Device-USB-MissileLauncher-RocketBaby-1.00/lib/Device/USB/MissileLauncher/RocketBaby.pm).

[1] It turns out that my USB toy uses the same ids; I probably just tried to run the code when the device was unplugged. Oh well, at least I got to learn how Perl interfaces with [USB] devices.

-- 
Sam Bisbee

Top    Back


Ben Okopnik [ben at linuxgazette.net]


Sat, 29 Dec 2007 09:30:46 -0500

On Sat, Dec 29, 2007 at 06:05:08AM +0000, Samuel Bisbee-vonKaufmann wrote:

> 
> Here is the code that I used (was inside a sub, hence the use of 'return'): 

Perl doesn't require an explicit 'return' from subs; the return of a sub, unless an explicit return is forced, is the last item evaluated. As well, "-1" is not a typical error value; instead, you'd usually return a null and use a simple logical test to report it (unless you're a diehard C or Java programmer, in which case you have an excuse to use '-1'. :)

sub uppercase {	
	# Silly example: returns an UPPERCASE version of supplied param,
	# null if no param is supplied
	uc $_[0] if $_[0];
}
 
die "Error!\n" unless $allcaps = uppercase("hello");
print $allcaps;
-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

Top    Back


Samuel Bisbee-vonKaufmann [sbisbee at computervip.com]


Fri, 04 Jan 2008 16:53:18 +0000

>On Sat, Dec 29, 2007 at 06:05:08AM +0000, Samuel Bisbee-vonKaufmann wrote:
>> 
>> Here is the code that I used (was inside a sub, hence the use of 'return'): 
>
>Perl doesn't require an explicit 'return' from subs; the return of a
>sub, unless an explicit return is forced, is the last item evaluated.
>As well, "-1" is not a typical error value; instead, you'd usually
>return a null and use a simple logical test to report it (unless you're
>a diehard C or Java programmer, in which case you have an excuse to use
>'-1'. :)
>

How long have you been looking at my Perl code? And which school of syntax was I brought up in, much to your chagrin? :-) I should start prefacing all my Perl code with a comment block on how I appreciate that Perl is good for certain tasks, but its mission to build in a natural obfuscation algorithm by using ... unique ... syntax is ridiculous.

>``
>sub uppercase {	
>	# Silly example: returns an UPPERCASE version of supplied param,
>	# null if no param is supplied
>	uc $_[0] if $_[0];
>}
>
>die "Error!\n" unless $allcaps = uppercase("hello");
>print $allcaps;
>''
> 

Preference in return codes aside, it feels weird to see a function/method/sub/* that doesn't clearly return anything. Just because code can be written shorter doesn't mean it should be (see Code Golf).

p.s. Sorry, I forgot to run my Perl code through the LG Perl compiler - `#!/usr/bin/bens-brain` - before posting it. ;-)

-- 
Sam Bisbee

Top    Back


Ben Okopnik [ben at linuxgazette.net]


Fri, 4 Jan 2008 13:45:13 -0500

On Fri, Jan 04, 2008 at 04:53:18PM +0000, Samuel Bisbee-vonKaufmann wrote:

> >On Sat, Dec 29, 2007 at 06:05:08AM +0000, Samuel Bisbee-vonKaufmann wrote:
> >> 
> >> Here is the code that I used (was inside a sub, hence the use of 'return'): 
> >
> >Perl doesn't require an explicit 'return' from subs; the return of a
> >sub, unless an explicit return is forced, is the last item evaluated.
> >As well, "-1" is not a typical error value; instead, you'd usually
> >return a null and use a simple logical test to report it (unless you're
> >a diehard C or Java programmer, in which case you have an excuse to use
> >'-1'. :)
> 
> How long have you been looking at my Perl code? And which school of
> syntax was I brought up in, much to your chagrin? :-) 

Lost causes are my favorite time-wasting exercise, Sam. Besides, I already said you had an excuse. :)

> I should start
> prefacing all my Perl code with a comment block on how I appreciate
> that Perl is good for certain tasks, but its mission to build in a
> natural obfuscation algorithm by using ... unique ... syntax is
> ridiculous. 

Every language has its own ("unique") syntax; Perl's makes many things easier (for example, by recognizing the obvious fact that every subroutine returns something - and that it usually does so at the end of the code block.) Just because you originally learned to code in a way that intentionally makes things more difficult doesn't mean that you have to stay that way: initially, you learned to eat by shoving your hands and face into your food [1], but I've seen you use a fork and even a spoon. Semi-successfully, anyway. :) [1] Watching my little boy eat - Michael isn't up to table manners quite yet - naturally makes my thoughts turn in this direction. However, imagining little Sam with his face smeared with mashed potatoes would make anyone wish for high levels of abstraction and LONG chains of pointers to distant objects...

> >``
> >sub uppercase {	
> >	# Silly example: returns an UPPERCASE version of supplied param,
> >	# null if no param is supplied
> >	uc $_[0] if $_[0];
> >}
> >
> >die "Error!\n" unless $allcaps = uppercase("hello");
> >print $allcaps;
> >''
> 
> Preference in return codes aside, it feels weird to see a
> function/method/sub/* that doesn't clearly return anything. 

I'm sure that snorting your pudding felt natural at one point too. I hope it doesn't any longer. It's just a matter of learning what's appropriate in a given environment.

> Just
> because code can be written shorter doesn't mean it should be (see
> Code Golf).

By the same token, writing code with extra noise, cargo-cult coding, and lots of unnecessary punctuation only obfuscates it. Well-written code is easy to read - and typical C or Java code fails that test, mostly by using 5x the verbiage to obscure the actual work that's being done.

open F, "file.txt" or die "file.txt: $!\n";
``` #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { FILE *f_out; if (!(f_out = fopen("file.txt", "r"))) { perror("file.txt"); exit(1); } } '''

To me, the Perl version is much more readable.

> p.s. Sorry, I forgot to run my Perl code through the LG Perl compiler
> - `#!/usr/bin/bens-brain` - before posting it. ;-)

Sam, when you post sub-optimal code - no matter what the language - people here are going to comment on it (if they're familiar with the language, that is.) That's pretty standard here in TAG, and it makes for a good learning opportunity: note that René's response, when the code in his recent post was corrected, consisted of cheerfulness and gratitude. You should learn from that. Ditch the bitching and say "thanks" instead.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

Top    Back


Thomas Adam [thomas at edulinux.homeunix.org]


Fri, 4 Jan 2008 18:51:13 +0000

On Fri, Jan 04, 2008 at 01:45:13PM -0500, Ben Okopnik wrote:

> ```
> #include <stdlib.h>
> #include <stdio.h>
> 
> int main(int argc, char *argv[]) {
>     FILE *f_out;
>     if (!(f_out = fopen("file.txt", "r"))) {
>          perror("file.txt");
>         exit(1);
> 	}
> }
> '''

To me, there ought to be a:

return( EXIT_SUCCESS );
In there, somewhere.

> To me, the Perl version is much more readable.

Yeah, it is.

> You should learn from that. Ditch the bitching and say "thanks" instead.

So in light of that, can I say, "you're welcome"? :)

-- 
Thomas Adam
"It was the cruelest game I've ever played and it's played inside my head."
-- "Hush The Warmth", Gorky's Zygotic Mynci.

Top    Back


Ben Okopnik [ben at linuxgazette.net]


Fri, 4 Jan 2008 14:58:00 -0500

On Fri, Jan 04, 2008 at 06:51:13PM +0000, Thomas Adam wrote:

> On Fri, Jan 04, 2008 at 01:45:13PM -0500, Ben Okopnik wrote:
> > ```
> > #include <stdlib.h>
> > #include <stdio.h>
> > 
> > int main(int argc, char *argv[]) {
> >     FILE *f_out;
> >     if (!(f_out = fopen("file.txt", "r"))) {
> >          perror("file.txt");
> >         exit(1);
> > 	}
> > }
> > '''
> 
> To me, there ought to be a:
> 
> ``
> return( EXIT_SUCCESS );
> ''
> 
> In there, somewhere.

Sure, makes sense - although it compiles just fine without it.

> > To me, the Perl version is much more readable.
> 
> Yeah, it is.
> 
> > You should learn from that. Ditch the bitching and say "thanks" instead.
> 
> So in light of that, can I say, "you're welcome"?  :)

Sure - you're welcome to it. :) Kibitzing is always welcome - especially given the old USENET rule about spelling flames.

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

Top    Back


Samuel Bisbee-vonKaufmann [sbisbee at computervip.com]


Fri, 04 Jan 2008 20:39:50 +0000

>On Fri, Jan 04, 2008 at 04:53:18PM +0000, Samuel Bisbee-vonKaufmann wrote:
>> >On Sat, Dec 29, 2007 at 06:05:08AM +0000, Samuel Bisbee-vonKaufmann wrote:
>> I should start
>> prefacing all my Perl code with a comment block on how I appreciate
>> that Perl is good for certain tasks, but its mission to build in a
>> natural obfuscation algorithm by using ... unique ... syntax is
>> ridiculous. 
>
>Every language has its own ("unique") syntax; Perl's makes many things
>easier 

Yes, those are the certain tasks that I referred to.

>(for example, by recognizing the obvious fact that every
>subroutine returns something - and that it usually does so at the end
>of the code block.) Just because you originally learned to code in a way
>that intentionally makes things more difficult doesn't mean that you
>have to stay that way: 

Well, saying that it makes things intentionally harder is akin to my joke about Perl's creators making their syntax intentionally obfuscate.

>initially, you learned to eat by shoving your
>hands and face into your food [1], but I've seen you use a fork and even
>a spoon. Semi-successfully, anyway. :)
> 

As I recall you were the one using the spoon, having ordered incorrectly at The Union Oyster House. Speaking of which, will Sun be calling on The Manual Writer to impart his wisdom on non-spoon using engineers anytime soon? Oyster House had the 2lb lobsters a few weeks ago and they made me think of you, in that crustacean ("hard shelled" being synonymous with "Russian") sort of way.

>Sam, when you post sub-optimal code - no matter what the language -
>people here are going to comment on it (if they're familiar with the
>language, that is.) That's pretty standard here in TAG, and it makes for
>a good learning opportunity: note that René's response, when the code in
>his recent post was corrected, consisted of cheerfulness and gratitude.
>You should learn from that. Ditch the bitching and say "thanks" instead.

Sorry, I meant it in a cheerful manner, calling back to all those times in the past that I asked you for assistance in my Perl coding. I probably should have added more signals in my original text.

-- 
Sam Bisbee

Top    Back


Ben Okopnik [ben at linuxgazette.net]


Fri, 4 Jan 2008 22:12:31 -0500

On Fri, Jan 04, 2008 at 08:39:50PM +0000, Samuel Bisbee-vonKaufmann wrote:

> >On Fri, Jan 04, 2008 at 04:53:18PM +0000, Ben wrote:
> 
> >(for example, by recognizing the obvious fact that every
> >subroutine returns something - and that it usually does so at the end
> >of the code block.) Just because you originally learned to code in a way
> >that intentionally makes things more difficult doesn't mean that you
> >have to stay that way: 
> 
> Well, saying that it makes things intentionally harder is akin to my
> joke about Perl's creators making their syntax intentionally
> obfuscate. 

Yep; it was intended that way. :)

> >initially, you learned to eat by shoving your
> >hands and face into your food [1], but I've seen you use a fork and even
> >a spoon. Semi-successfully, anyway. :)
> 
> As I recall you were the one using the spoon, having ordered
> incorrectly at The Union Oyster House. 

My mental defensive mechanisms have already done me the favor of blanking out that experience; I can only surmise that it must have been horrendous. What is it with you Boston people, anyway? You've got an ocean full of perfectly good fish, and what do you do with it? Something that I have to work to forget. Sheesh...

(Admittedly, given that I consider "weird" to be a positive modifier when I'm ordering food, "failures" of that sort are my own responsibility. In that part of the NorthEast, though, they consider "bland" as some sort of virtue - so there's necessarily going to be conflict. To Sam's credit, he's managed to entertain me and Kat both - and we've enjoyed most things that we ordered there. But it's still fun to twit him about it. :)

> Speaking of which, will Sun be
> calling on The Manual Writer to impart his wisdom on non-spoon using
> engineers anytime soon? Oyster House had the 2lb lobsters a few weeks
> ago and they made me think of you, in that crustacean ("hard shelled"
> being synonymous with "Russian") sort of way.

As opposed to what, the soft-shelled but hard-headed residents of Hull? These days, I'm still imparting my wisdom in reasonably small chunks; the manual-writing deal hasn't happened yet, but I still haven't given up on it. Besides, the manual on spoon management has been around for a while now.

http://www.butyoudontlooksick.com/navigation/BYDLS-TheSpoonTheory.pdf

:)

(Seriously - a good read, and a neatly-encapsulated life concept. Well worth keeping in your mental toolbox.)

> >Sam, when you post sub-optimal code - no matter what the language -
> >people here are going to comment on it (if they're familiar with the
> >language, that is.) That's pretty standard here in TAG, and it makes for
> >a good learning opportunity: note that René's response, when the code in
> >his recent post was corrected, consisted of cheerfulness and gratitude.
> >You should learn from that. Ditch the bitching and say "thanks" instead.
> 
> Sorry, I meant it in a cheerful manner, calling back to all those
> times in the past that I asked you for assistance in my Perl coding. I
> probably should have added more signals in my original text.

Happens all the time - see Shannon's Theorem, and don't worry about it. I wasn't upset or even annoyed; apologies if I gave the opposite impression. Besides, I chew your ear off just for the fun of it - just like you do mine. :)

-- 
* Ben Okopnik * Editor-in-Chief, Linux Gazette * http://LinuxGazette.NET *

Top    Back