Art of CodingBecause coding is a form of art

MQTT over WebSockets with Adhesion Posted on 17-04-2014 15:23:22 by Michiel

For a while I was looking for the best way to get information from MQTT to a web page for display. So I decided to make a 'proxy', which channels MQTT over WebSockets for use in the browser. I named it 'Adhesion'. It's now up on GitHub and available through npm.

Adhesion is an easy to use piece of code that consists of two parts; the server code, and the client code. The server code essentially channels all MQTT messages through WebSockets, and handles publish and subscribe commands.
The client code allows the client to subscribe to topics and publish messages on them. I tried to keep the syntax as close to the MQTT module for node.js as possible.

Installing

You can install Adhesion through npm, by simply calling npm install adhesion

Using Adhesion

Server Example

This example shows how to use the server. You can find this example in the examples folder also.
var Adhesion = require('../');

var server = new Adhesion.Server(9234, 1883, '192.168.2.3');
server.start();

var connections = 0;
server.on('online', function() {
    console.log('WebSocket is online!');
    server.on('connection', function() {
        console.log('Connection received...');
    });
});

Client Example

var ad = Adhesion('ws://localhost:8080');
ad.connect();
ad.on('error', function(error) {
    console.log('Got an error: %s!', error);
});
ad.on('connection', function() {
    console.log('Connection established!');
    ad.subscribe('/var/www/#');
    ad.publish('/var/www/etc', 'This works!');
});
ad.on('message', function(topic, message) {
    console.log(%s %s, topic, message);
});

To Do

  1. Better error/connection problem handling
  2. Support for the retain flag

I hope this module will be useful for you people out there!