Archive for July, 2008

Howto: Talk to arbitrary USB devices with Processing (1.0 Beta)

I’ve been playing with the Processing language (http://processing.org) a little bit and liking it so far. For anyone not familiar, it’s a Java-based rapid-prototyping language that includes very friendly libraries for graphics, sound, video and select hardware (e.g. serial port). One thing I couldn’t find much info on was talking to arbitrary USB devices (not USB-to-serial based gadgets, but sending and receiving raw packet-level data).

Anyway, I found a solution that works in Processing with only minimal tweaking. You need:

Processing (of course) – http://www.processing.org
libusb or libusb-win32 – http://libusb-win32.sourceforge.net (Windows) or http://libusb.wiki.sourceforge.net/ (Linux)
Libusb Java wrapper – http://libusbjava.sourceforge.net/wp/

I only tried this on Windows so far, so the following assumes a Windows installation.

(I know, wrappers upon wrappers. So in the end you end up with device -> OS -> libusb -> libusbjava native DLL -> libusbjava JNI wrapper -> Processing. Probably not the most efficient approach in the world, but in the era of multi-GHz machines I’m not sweating too hard about it :-)

Follow the author’s recommendations on setting up libusb-win32 for your device, if it’s not already been done. Then, (for Windows users) extract the LibusbJava.dll file and drop it somewhere Processing/Windows can find it. The author recommends \Windows\System or equivalent; if this seems a bit forward, dropping it in the same directory as processing.exe works fine too.

Finally, making the library appear for Processing: create a new folder(-nest) for it in Processing’s libraries folder (blahblah\processing-0135\libraries\libusbjava\library), and drop the .jar file in it. Rename it to something more sane; Processing doesn’t seem to like all those extra dots and numerals. After renaming the .jar file sanely and restarting Processing, it will appear in the Sketch->Import Library menu. Clicking on the menu item automagically fishes out the correct class names and adds the appropriate (import…) lines to your sketch. From here on out, programming for the libusbjava wrapper appears to follow the actual libusb API pretty closely.

Here’s the program I tested it with. All it does is connect to a Rez/Drmn trance vibrator, send a USB packet to turn the motor on at about 2/3 intensity, then exit.


import ch.ntb.usb.testApp.*; // these four lines were automatically added by clicking it
import ch.ntb.usb.*; // on Processing's Sketch -> Import Library menu item
import ch.ntb.usb.usbView.*; // ...
import ch.ntb.usb.logger.*; // Some of these can probably be removed safely.

void setup()
{
noLoop();
}

void draw()
{
LibusbJava.usb_init(); // required inits for libusb-win32
LibusbJava.usb_find_busses(); //
LibusbJava.usb_find_devices(); //

// retrieve a object tree representing the bus with its devices and
// descriptors
Usb_Bus bus = LibusbJava.usb_get_busses();

// Find a specific USB device on the bus (by its VID/PID) and return a handle to the device in 'dev'
// This diverges a bit from native libusb-win32 code in that you don't have to loop through all the devices/busses searching for it.
Device dev = USB.getDevice((short) 0x0b49, (short) 0x064f); // VID/PID combination of Drmn' Trance Vibe device

// Note: Since this is just a quick n dirty "hey, is this possible?" test, I've added no error checking whatsoever.
// For anything more than a tightly-controlled quick hack / demo, you will want to do so!! (for starters, check if the device was found at all...)

try {
// data to write to the device. I don't want to write any data, so leaving this array empty.
byte[] data = new byte[] {};
// data read from the device
byte[] readData = new byte[data.length];

// open the device with configuration 1, interface 0 and without
// altinterface
// this will initialise Libusb for you
dev.open(1, 0, -1);

// ^^ Note, this may also diverge from native libusb-win32; I've never seen the choice of "-1" for alt. interface before (I assume it's interpreted as "any/all/none/don't-care"), but it seems to work.

// This device uses Control messages on endpoint 0. The following packet turns ON the motor at about 2/3 intensity (0xAA).

// Fields are: Request type (0x41-Out+Write), bRequest, WValue, wIndex, byte[] data, size, timeout, bool reopenOnTimeout
dev.controlMsg(0x41, 0x00, 0xAAAA, 0x0000, data, 0, 1000, false);

// The "reopenOnTimeout" field is a new one. It sounds either flaky-hardware-friendly or extremely dangerous.

// ok, motor turned on! I'm satisfied that you can control arbitrary USB devices from Processing at the raw (bulk/interrupt) packet level, so this is as far as I go for now.

// close the device
dev.close();
} catch (USBException e) {
// if an exception occures during connect or read/write an exception
// is thrown
e.printStackTrace();
}
}

House wiring, A Beautiful Mind style

Our power went out sometime in the last couple days’ raging thunderstorms and reset all the computers/clocks in the house, so I figured before I reset them, this was an excuse to do something I’ve been meaning to do for a long time: map out the breaker box. (Exciting, ya? Well, this anti-electrocution research is a dependency to a few other tasks I’ve been Meaning To Do, like replace a dimmer with a regular old light switch in preparation for energy-saver CFL bulbs, and relocate the bathroom light switch from in-the-hallway-behind-a-door to in the bathroom where it belongs.)

Basically, this process involves flipping each breaker one at a time, and running around the house plugging a lamp into every outlet to see which ones went out. It’s not a bad source of exercise, when you’re done dragging furniture from in front of them. :-)

So, as seems to be typical for New England houses, the arrangement of circuits around the house has proven more frightening than most Scary Movies. It’s clear that most of the wiring is an afterthought, and when they wanted to install, say, a new overhead basement light, they just grabbed whichever set of wires was closest and spliced it in. (Incidentally, one of the overhead basement lights is controlled by a switch in the kitchen – come on guys, that’s not even on the same floor!).

As an example, here is the layout of the 2nd floor. An unfilled square marks an outlet, a square with an X marks a switch, and a circle denotes a permanent/overhead light. The entire floor is on 2 of the 17 breakers, marked 3A and 4A here. Luckily, neither of these (unlike many of the others) spans multiple floors.

Breaker 3A controls all of one room (yay!), one of four outlets in my room plus the overhead light, one of two outlets in the other spare bedroom (plus its overhead light), and the hallway light. Don’t get me started on the one that controls the front porch light, the foyer light, the aforementioned basement light, the dining room light (but no outlets), and the one of three outlets in the living room that’s furthest away from any of those. :-p While some drive several rooms’ worth of hungry electrical devices, one controls only two small basement lights, and three (scattered throughout the panel) don’t appear to do anything at all.

Evil thought of the day…

When I noticed more and more Web sites trying to detect and block ‘bad’ or otherwise unprofitable users (e.g. those using ad- or popup-blockers, privacy tools, etc.), and banking sites like the one I use trying to detect potentially compromised machines, I thought, “How long will it be until some unnecessarily clever dickface just adds a script to all its pages that validates the page’s CRC/hash/checksum?” One possible embodiment is that the page’s content is encrypted and embedded as a page comment, along with a small Javascript that obtains the encrypted payload’s expected CRC from somewhere (e.g. loading it from another page on the site, or it’s embedded in this page in some obfuscated way), and validates that the page contents have not been modified/filtered. The payload is then decrypted and written to the page using document.write() or similar, displaying the content. There are many possible variations on this theme – e.g., using the CRC (etc.) itself as the decryption key or, rather than resort to encrypting the entire document, send it all as plain HTML, but with the important parts hidden using DHTML attributes/tricks. After validating a preferred user, the on-page script unhides the contents.

This would deeeeelight many money-grubbbers and most anyone with an MBA, by doing two things:
1) Reject anyone who doesn’t have JavaScript enabled (they’re obviously not here to make you money. They probably have images disabled too, the commie bastards.)
2) Reject anyone whose ad-blocker filtered something on the page, thus changing its contents and invalidating the CRC.

Anyway, I got bored and looked into it today to see how much work would be involved for a suitably motivated dickface. Although a document.write() function has been around for a bazillion years to let a JavaScript write new contents to a page, it turns out that there is no corresponding document.read() function! In other words, maybe a script can’t just slurp in and parse the raw contents of the page it’s on. Maybe THAT is why I’ve never seen this used before. Of course, Dickface can get around this in quite a number of ways, which I won’t detail here. For some of them he may have to be content with only validating specific elements, not the entire page. Fortunately, there are ways to filter adverts that don’t necessarily change the page contents as seen by client-side scripts.

* Obligatory warning: I am not a JavaScript programmer (and have been mostly out of the whole Webmastering gig in general for the last 5 years or so), and this is not JavaScripting advice. No blogger-client relationship exists here. Yadayadayada…

My Fossil Collection

Fossils in ironstone nodules I collected near my folks’ place on a strip-mine lake near the Mazon Creek in Grundy County near Morris, Illinois. This area is sometimes referred to as one of the Lagerstätten (i.e. mother lode) – one of few places on earth where conditions were just right to preserve a rich deposit of extremely well-preserved fossils. (Mine aren’t in the best shape, but a huge variety of detailed fossils have been found here, including soft-bodied animals such as the Tully monster.) More about the Mazon Creek area (Illinois State Museum). Even more (Wikipedia)

Of course, any assistance identifying these specimens would be greatly appreciated.


Photo Album


The Pomp Room

Near my parents’ house in IL.

Laugh, it’s funny (in Afrikaans, anyway – a good name for a place that might rent rooms – and companions – by the hour).

Couch denting at a 14th grade level

Some random observations on being back in my hometown for the week of the 4th…

I know it’s not the first time I’ve felt this way, but I was particularly amazed at how this place… no longer feels like home. Yeah, a few things have changed – buildings where there were no buildings before, a quadrupling of traffic density and more aggressive driving, mom-and-pops dearly departed – but that’s not what makes or breaks a place, it’s the people. And of relatively few people I knew here to begin with, most have kind of moved on.

So, of the people I called….

Da*: Didn’t return my voicemail, or previous call a couple months ago.

K*: I consider(ed?) him a good friend, so I ended up leaving repeated voicemails on both of his phones over the last several weeks, which went unreturned until Wed. morning or so. So, for the once-or-twice-a-year that we see one another, he proposed: “Yeah, let’s meet in the middle, at an Applebees or something over my lunch hour, near Fry’s Electronics, since I have to go buy an inverter there anyway. You like Fry’s, right? Maybe you could tell me which one to get.”. Then he buggered off, promising to call back around noon because he was arranging this at work on his desk phone, and a coworker was giving him the eye. So, needless to say, I wasn’t exactly plussed by this proposal. So, equally needless to say, this promised callback never happened, either. I left one further due-diligence voice mail (unreturned to date), but I’ve kind of relegated that whole business to the fuck-it bucket. There’s a fine (or not so) line between making extra effort to keep in touch with a good friend, and stalking someone who no longer considers you one.

I can’t be sure whether awkwardness surrounding the relationship between Da* and K* (mentioned previously) and its subsequent spectacular breakup, and my involuntary man-in-the-middle status, have anything to do with this, but suddenly not really wanting to be seen by either of them is statistically significant.

Nando: Did call back, but scheduling difficulties ensued. The night we both could do something, plans fizzled since neither of us had anyone else to bring along. Nando and I just staring at each other over an open fire sounded a little suboptimal (among other things)… I didn’t say as much, but he seemed to agree, ending the call saying he was going to call a few people and see what kind of posse could be rounded up. Not much of one, apparently, since I never heard back.

F*: Changed numbers since the last time I talked to him. Eventually met up, grabbed some brews and White Castle with him and D*, and headed home to enjoy them. Due to OCD-type issue (mentioned previously), I was holed up in a separate room most of the time as D* took his sweet time on those sliders. By the time I could re-enter society as it were, F* was asleep.

J* and E*: Actually returned my calls! We actually hung out! So, E* just graduated and is seeking a teaching job; J* got married this week. More on the wedding later.

B*: More like my brother’s friend, but anyway, we had this plan to go exploring Red Gate Woods, former site of Argonne Nat’l Laboratory and the first ever nuclear reactor. A carefully scheduled Sunday morning/early afternoon would allow this, a BBQ with my folks and aunt/uncle who were jonesing to BBQ with us, and busting ass for the airport. So, D* is getting calls at 2am from B* all hopped up about it. But then, Sunday morning rolls around and B* has disappeared off the face of the planet. Yeah, could have gone alone (if I knew this was going to happen ahead of time, which, given the luck with humans so far this week, I should have), but it wouldn’t be nearly as much fun. Ended up rejiggering the day to do the BBQ earlier and spend more time with the relatives.

So, other things I did this week in IL:

Hung out with family. Mostly my folks, but also an aunt and uncle from each side, and my “little” cousins. My folks took me to a new restaurant in the area that serves ALLIGATOR. Oh yeah, alligators are tasty.

Took a lot of pictures. Mostly nature, since I don’t like people chasing people around with a camera. I found what’s left of my old fossil collection back home and documented it. Identifying them is another story. ;-)

Got plenty of reading in. I know, not everybody takes vacation time to read, but there wasn’t all that much else to do. When I’m home (in Boston), I always have gf and/or some project to stay busy with, and so I never read.

Went to JLM’s (err… JLW’s, now) wedding. They had a traditional Catholic wedding, followed in the evening by a reception complete with open bar (w00t). Here, the entirety of the old LT photo club gang was reunited for the first time in ages(!) (even Ca*, who I haven’t seen in years). So we caught up, laughed and danced into the wee hours. Got a little bit of the usual pile of shit from my old man, wondering why I still hang out with these people, J* in particular, hinting that they’re not my intellectual peers and that there must be some romantic component in play (as.per.usual). I didn’t bother trying to validate my friend choices to him. As it happens though, J* is one of extremely few people who have never lied to me. In a world where most of the species is full of shit to some degree, this is meaningful – when you find people worthy of absolute trust, you hang onto them.

Enjoyed my brother’s pr0n collection, carefully stashed away across dozens of locations on my parents’ computer. “New Folder” indeed :-)

Brought back a few interesting plants that I will attempt to transplant and/or root, as the case may be. Specifically a ginkgo biloba tree, sassafrass, and a weird variegated thing that looks like it shouldn’t exist in the wild (outside of the tropics), but here it is.

I have a fridge compressor in my parents’ basement I wanted to bring back with me, but it a) isn’t worth the shipping from here to Boston (either UPS/etc. or the extra fees to have a checked bag on the plane, as of the day before I booked my flight, given the high likelihood of being damaged in transit), and b) in my carry-on, would look entirely too much like a (hollywood representation of a) bomb to a dead-end TSA screener wanting to be a hero. No 7-segment LED countdown, or indeed LEDs at all, but, you know, a big heavy sealed metal canister with wires and copper tubing protruding from it. For a moment visions of excitement danced in my head – a monumental overreaction, some mild police brutality followed by plaintiff status and press conferences where I talk about ’80s hairstyles – but it IS probably the last flight of the night, and my gf will be waiting to pick me up. That, and if I didn’t drain the oil from it as completely as I think I did, it could leak on my suit. Yeah, I am teh old.

Pictures will be uploaded…sometime!

Entropy Is

Destroying information. I’ve never had an easy time with this. Feeling in a productive mood the other day, I made a plan for my next side-project* (picking back up my interest in building gas discharge tubes, i.e. those decorative plasma globes, except doing it right this time), and set my sights on clearing some space in the basement, starting with several large, sealed boxes of stuff left behind by my ex when she left. I didn’t want to put them out with the trash since they probably contained all kinds of very personal information and things of value (sentimental, IP or otherwise), but at the same time, sort of dreaded opening them for this same reason. The majority of the contents turned out to be books, which were easy enough to process into a keeper pile, an ask-friends-if-they-want-it pile and a Goodwill pile. But also a bunch of notebooks, diaries, unreturned books from libraries I’ve never heard of, her high school yearbook… What does one do with all this stuff? Besides avoid the temptation to go poking through it of course**. The last thing I would want to do is give it over to her parents, or random tangentially-connected third parties to go poking thru. Chucking all the personal effects into the permanence of the trash is not an idea I like either, but I don’t really have better ones.

* ignoring for now the jillions of other half-finished projects yet to be worked on, when my interest in them renews
** except for one anti-anti-vegan political cartoon, marked for widespread distribution via “Top Secret Do Not Read” marked on the outside in cleartext English.

Camping in Maine

Kr* an I went camping/hiking in Acadia for this weekend…her first time in South Canada Maine. So we made camp on Friday evening, and ran up to the top of Cadillac Mtn. on Saturday, followed by a trip back down the steep side to Bubble Pond (~6mi). This was just after the Corporate Challenge (the run I do with the work crew once a year to remind myself how much I hate running), so I was a little bit sore. But this is a small price to pay for a weekend of campfires, meat on a stick and breathtaking views :-) We didn’t see anything from the actual top, since it was surrounded in thick fog by then, but there were plenty of great views on the way up. Sunday we set out for the logically-named Sand Beach and found a long trail along the ocean, leading to Thunder Hole, Otter Cliff and Otter Point. About 2 miles out is when it started to rain buckets :P Luckily, we had some dry clothes in the car.

[Pictures of Much Awesomeness]