Node.js, MQTT and Websockets29 Jan 2011
For a while I've been looking at how to bridge the MQTT protocol and websockets to make it easier to build web applications using data broadcast in MQTT streams. In the past I used python and mod_pywebsocket along with mosquitto python libraries however this was cumbersome and difficult to install. Here I present a simple solution using node.js to interact with mosquitto MQTT clients. Node.js lends itself to working well with messaging systems like MQTT and websockets due to its event driven nature. I'm also in love with node.js at the moment!
This is much simpler than previous attempts and I put the initial test together in less than ten minutes.
PrerequisitesObviously you'll need to have node.js and mosquitto installed and also the node library node-websocket-server (which can easily be installed using npm). All my work was tested under ubuntu but there is no reason why it wouldn't work on OSX or even cygwin. To test you'll need a websocket compatible browser such as recent versions of chrome.
System Structuremosquittopub and mosquittosub are command line MQTT clients supplied with the mosquitto MQTT broker, here mosquitto_sub will be called using node.js as child processes, events are generated on output from the process. The data is then captured and broadcast over a websocket. In this case a simple jquery page is used to display the broadcast messages but in a real application there would be more client side processing to make a useful application.
Simple Server Side Subscriber Code
This example subscribes to the topic "test" and broadcasts all messages on this topic over the websocket on port 8000.
This is a bare bones page which prints out messages received over the websocket.
This example is of little practical use on its own however it could easily be the basis of a flashy home monitoring system. Publishing MQTT messages could be easily achieved by calling mosquitto_pub in the child process.