A simple MQTT cient on node.js

Background To visualize data send to MQTT broker from mbed, arduinos and clickers, and allow clients easy accesses to MQTT messaging system data, i was thinking to create a web page and put all messages up on it. A web page on Java script would be a good choice, but, there is no existing MQTT client written in java script, and i had little knowledge on how web server runs. Fortunately, adam introduced me node.js, server side javascript, which is excellent and surprisingly easy to create a web service. Then, a idea came to my mind, is writing a MQTT client or server on node.js possible?   Writing a new MQTT server would be complex and time consuming, so, i started to write a simple MQTT client runs on node.js. After few days of coding and tests, this little client is born.      Node_MQTT_Client This is simple MQTT client on node.js.

Limitation: 1. Only do QOs1 messaging. 2. Can not handle payloads larger than 128 byte. 3. Length for subscribe topic is limited to 128 bytes.

Example: This is simple program called 'loader.js', which create a MQTTClient instance and send “here is nodejs” to “node” after a session is opened with server. Then it display incoming data from topic “/mirror”.

var sys = require('sys'); var net = require('net'); var mqtt = require('./mqtt');

var client = new mqtt.MQTTClient(1883, '', 'mirror');     client.addListener('sessionOpened', function(){    client.subscribe('/mirror');    client.publish('node', 'here is nodejs'); });

client.addListener('mqttData', function(topic, payload){    sys.puts(topic+':'+payload); });   Test: The library has been tested on rsmb, mosquitto 0.9.1, nodejs 0.2.6.  

Resource: Codes for library and example program are attached below. Those codes can also be found at github: https://github.com/yilun/node_mqtt_client


Event: ‘sessionOpened’ Fired when a session with broker is opened sucesffully.

Event: ‘mqttData’ Fired when data is available for client, topic and payload have been extracted from data. client.addListener(‘mqttData’, function(topic, payload){


Event: ‘openSessionFailed’ Fired when a session can not be established.

Event: ‘connectTimeOut’ Fired when cant establish a connection with server.

MQTTClient(port, host, clientID); Construct a instance of mqtt client. @port: port number, like 1883. @host: server ip address. @clientID: client name for server.

subscribe(sub_topic); Subscribe to a topic. @sub_topic: topic to be subscribed.

publish(pub_topic, msg); Publish messages to a topic. @pub_topic: publish topics. @msg: payload data, can be anything, string, bytes.

disconnect(); Disconnect with server.

text/plain iconloader.js_.txt 445 bytes
text/plain iconmqtt.js_.txt 7.46 KB