Getting node-hid to work on Windows

The Window by Rohit Rath
The Window by Rohit Rath

I am the web developer who likes Windows. Yes, the only one.

I’m working on software to communicate with USB-connected devices, and most of our customers are Windows users. I have to admit, the more I’ve learned about the Windows OS, the more I appreciate it. I know, how can I consider myself a programmer at all if I actually like Windows? Yes, it’s quirky, but those quirks were earned by committing to backwards compatibility and trying (keyword) to create a natural experience for regular users. It’s not like any particular flavor of UNIX has a huge following.

I like other systems, too.

That said, I would really like it if my application (or at least the lower layers of it) were available on more systems, so I investigated NPM for packages that enable USB communication via Javascript. There are quite a few, but node-hid stood out to me because it wraps the HIDAPI library I was already using in my C# application. Other wrappers exist, like pull-hid and hidstream, but this seemed to me to be the easiest to use.

Installing and using node-hid is easy.

I was pleasantly surprised that npm install node-hid worked without problems. I had been conditioned by other packages with native Windows bindings to expect problems due to having Visual Studio 2013 installed instead of an older, more widely distributed platform. Many native bindings expect Visual Studio 2008 or older, but the node-hid contributors must keep their node-gyp skills sharpened.

Using the library is simple. require('node-hid') returns an HID class constructor and a devices() function. If you know a particular device is already connected, you can open it by simply running dev = new HID(vendorId, productId, serialNumber). The serial number is optional, and you can also provide a system path. The devices() function returns a list of device metadata objects that include vendor and product IDs, serial numbers, release numbers, and system paths. You can easily filter this list for a particular device family and pass the path property of a given device metadata object to the HID constructor.

Closing devices is hard.

The problem I ran into is that, while HID devices are easy to open, they can be a pain to close. This comes down to an issue with how read threads are managed on different platforms at the native HID layer. On Mac and on Linux systems with libusb installed, the hidapi actively manages asynchronous read threads to prevent any problems when closing a device handle. On other systems, particularly Windows XP, this is not supported. The library should be available to everyone, and while Microsoft has stopped supporting XP, a lot of potential customers still use it.

The issue is that as long as a read thread is waiting for device data, the operating system can’t close the device handle. The node-hid library will go ahead and set the pointer to this handle to null when you call dev.close(), but the handle is still there waiting for data from the physical device. Naturally, any further attempt to communicate with the device (calling dev.write() for example) at this results in a null reference error, and Node crashes.

The solution

I got on the node-hid Google group to see who else had this problem, and I got some great advice from member Chris Teague, who pointed out that if you can get the device to send one last signal before closing, the read thread will exit and the device will close properly. Here’s what that code looks like:

Basically, you have to remove the “data” event listener, then write any message to the device that will begin a response, and then close it. Trying other orders of operation didn’t work for me on all systems. This does.


HIDAPI is a great open-source C library for simplifying cross-platform HID communication. The HID device class is great because most systems will accept HID devices with no special drivers, meaning you don’t have to get a special Microsoft or Apple stamp to avoid “Unsafe driver detected” messages when your users try to connect to them. For Windows 8 and above, users won’t even see an option to “connect to the device anyway” without booting their system into a special mode. The node-hid package expands the usefulness of HIDAPI by making it easy to create and install multi-platform applications and services that help users connect to new devices. I think this will become more important in the future as the “maker revolution” expands and more single-purpose consumer devices come to market. Of course, the wireless Internet of Things may render some USB connections unnecessary, but I think there will always be a use for low-power wired communication.

In Defense of Angular Providers

I’m still a learner at Angular (aren’t we all?), but overall I’ve had a pleasant experience with the framework. I feel like it’s easier to compose solutions with the framework than without it. I wouldn’t consider myself a cheerleader for the framework, but when I ran across this blog post, I felt a little bit annoyed. Clearly, the tone of the article is intended to be a bit harsh in a humorous way. That didn’t stop me from feeling a bit slighted by the title. Are Angular developers really ruining the experience of the language?

Rob’s tirade comes to a close when he brings up the following quote from this StackOverflow answer:

But, why CarProviderProvider instead of CarProvider

The code in question is:

On the surface, this is silly, right? Why should I have to repeat the word provider like that? Actually, you don’t. The reason CarProviderProvider exists is because the example is showing the difference between defining a service and a provider. When creating an actual service using the app.provider function, you would just use the name of the service. Here’s what I mean:

You’ll notice that I gave a name to the function stored in the $get property. This can help tremendously when debugging services. Also, I made the configurable value private while exposing a setter. This is because providers should only be configured once per module, and that configuration happens before any services are instantiated using app.config. The above definition would allow the use of a foo service without configuration, or by specifying configuration like so:

The Angular framework sometimes appears to be performing magic tricks and creating objects from out of nowhere, but as AJ O’Neal once demonstrated, it’s really just string manipulation coupled with a brilliant application of Javascript’s bind and apply functions. The important thing is that, by passing a constructor and a name to app.provider, you are defining a service provider that can be configured before the service is instantiated. Does every service need to be configurable? No, just like every app doesn’t need an MVC framework. Technically, no one needs a framework, but using one doesn’t automatically ruin the joy of development for everyone else, does it?

Literally the first AngularJS app everyone writes

So, I’m a fan of Javascript frameworks. I don’t know if that’s a controversial opinion or not. I’m in the camp of people who don’t believe they should write everything from scratch (well, obviously, since this is a WordPress site).

There are a lot of great frameworks. My personal favorite so far is AngularJS from the Google people. This is not a religious statement. I’ve written some StackOverflow answers about JQuery and pondered about new offerings like ReactJS. For me, for now, I like Angular.

Why Angular?

Probably my favorite thing about the Angular framework is that it clearly delineates the various pieces of code without making any assumptions about what they should be. EmberJS also has a very intuitive distinction between Models, Views, and Controllers, but I feel like Ember demands more rigidity on the server side. In other words, Ember’s conventions seem more inflexible to me, and that’s difficult since my web host is pretty exclusively a PHP machine. Maybe it’s just that I happened across Angular first, and “got it” more quickly. I could be convinced either way.

So what’s the first app?

One of the most radical properties of Angular is that you don’t actually have to write any Javascript to do basic manipulation on a page. The easiest example of this is a simple tip calculator, where you type in the dollar amount of your bill and the percent you’d like to tip, and the total bill is calculated automagically:

Your bill:

Your tip (%):

Total: {{ bill * (1 + tip * 0.01) | currency}}

The code for that little bit of mastery:

<style>.ng-cloak {display:none;}</style>
<div ng-cloak ng-app ng-init="bill=0;tip=0">
  <p>Your bill: <input type="text" name="bill" ng-model="bill"/></p>
  <p>Your tip (%): <input type="text" name="tip" ng-model="tip"/></p>
  <p>Total: {{ bill * (1 + tip * 0.01) | currency }}</p>
<script src=""></script>

What’s going on?

Basically, Angular is all about managing data in a given context, called a scope. The ng-app directive creates a new scope, and the ng-model directives declare variables within that scope. Those variables are initialized by the ng-init directive so that the “Total” expression has valid input at the start. Without that, the “Total” area would read “NaN” until the user writes numbers into the fields. The expression for total is just the basic tip formula piped through the built-in currency filter. One cool thing about this filter is that it automatically adjusts to the user’s locale, meaning UK users will see “£” while US users see “$”.

But how does it work?

Ultimately string manipulation. Javascript can do anything to the page it wants, including parsing the page for expressions delimited by curly braces ({{ and }}) and replacing them with calculated values in scope. This is exactly the kind of code best left to the experts, in my opinion. The last bit of trickery is preventing users from seeing the curly brace expressions while the Angular library loads and does its work. That bit is handled by the ng-cloak directive, which, unlike the other ones in this example, was declared as a CSS class. In general, angular directives come in three varieties: elements, properties, and classes. That’s right, you can create your own HTML elements using Angular directives, and that’s awesome! Most of the directives displayed here were properties like ng-app and ng-model="bill". The third type lets us sneak under the radar by declaring a CSS style on the page to initially hide the element (display:none). When the angular directive kicks in, it immediately removes the ng-cloak class to reveal the Angular-powered elements underneath.

Didn’t Google already explain this more clearly?

Yes, they did! However, I thought I’d take this opportunity to prove to myself that A) I understand it well enough to explain it and B) I can demonstrate single-page apps on my WordPress site. Mission accomplished.

Hello again, world!

I once told a friend about a Xanga blog I was running at the time, and she just laughed and said, “You and your websites!”

I was stunned. I never thought of myself as owning a website before. I managed profiles (at that time) on Xanga (since abandoned), Google, Facebook, and LinkedIn (hadn’t heard of Twitter yet), but I always thought owning a real personal website was either too expensive or too much work.

Fast-forward a few years, and my life has now brought me to a point where I feel it is too expensive not to run my own site. Here are my top 5 reasons why:

5. Basically, I’m a developer now

My official title at Ludlum Measurements, Inc. is “Project Engineer”, which means I take primary responsibility for the development and production of new and existing products assigned to me. That said, what I end up actually doing for 40+ hours a week is a mix of desktop application and firmware development.

In today’s job climate, it’s best to keep abreast of new opportunities as they arrive. After all, people who change jobs every two years earn more than those who stay put. Most employers of developers, especially web developers, would expect a potential new hire to maintain a personal website.

4. I’m already hosting and maintaining other sites

Through Walke Designs, I’m already managing other web pages. So far, these are all WordPress sites (like this one). Our service provider is very accommodating and inexpensive (thanks JustHost!), and as long as you don’t do anything funny like try to install Laravel, NodeJS, and Rails 4 (guilty), they allow a lot of storage and bandwidth at a flat rate. Thus, the only cost to me to run my own site is the domain name, which is really very inexpensive compared to anything at all. You can barely get milk and eggs without spending $15 now. Compared to what I spend every month for my smartphone data plan, it’s basically free.

3. I like to rant

Technically, I could log in to the Walke Designs blog and post whatever I want. However, I don’t think it’s appropriate to use a business site to talk about personal issues, projects, or political thoughts. I think about those subjects a lot, and while I feel free to express those thoughts on Facebook and Twitter, the blog format is better suited for collecting and sharing these thoughts in a coherent, non-invasive way.

2. I like to code

Honestly, I feel a bit ashamed to be relying on a “batteries included” framework like WordPress to publish my blog. I feel like I should be able to code the whole thing in PHP-HTML-JS-CSS (JustHost pretty much just likes PHP on the server side, not my favorite). However, as I was sketching out how I would design the site, I realized that pretty much everything I wanted on the backend would just be replicating what WordPress already does for free. With that in mind, I decided to publish the main site the easy way and add flair later my customizing themes and adding JS modules to individual pages when appropriate. This site will be the perfect playground for that kind of experimentation, as it won’t interfere with the professional sites I host, but it will still be live and public. In other words, I like the pressure, but not too much pressure.

1. I want to give back

I’m continually inspired by my coding heroes who blog, including personal acquaintances like Bryan Hughes (@nebrius) and slightly more public figures like Charles Max Wood (@cmaxw) and Saron Yitbarek (@saronyitbarek). Saron and her CodeNewbie group are especially inspiring, because she’s been programming for many fewer years than I have, but she’s already blown me away in terms of making a real impact in industry.

I feel like the common thread among these individuals is that they each decided at some point in their careers to make an effort to connect with other people who were interested in writing code by sharing their own thoughts and experiences. I get so much from listening to Charles Max Wood’s 10 or so podcasts every week (most notably Ruby Rogues and Javascript Jabber), and they would never exist if the panelists on those shows all waited until they were millionaires with several decades of professional experience under their belts before they joined the conversation. Yes, some of the panelists have been around the block a few times, but not all, and the diversity of the panels is a big part of the value of those podcasts.

So, this is me, looking to do my part to join the conversation after a few years of relative silence. Me and my websites, right?