Chinaunix首页 | 论坛 | 博客
  • 博客访问: 349511
  • 博文数量: 102
  • 博客积分: 3140
  • 博客等级: 中校
  • 技术积分: 680
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-28 11:44
个人简介

开阔未来

文章分类

全部博文(102)

文章存档

2015年(10)

2014年(1)

2013年(1)

2012年(4)

2011年(8)

2010年(24)

2009年(51)

2008年(3)

我的朋友

分类: 系统运维

2011-12-23 17:13:36

From:
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, '127.0.0.1', '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:

API

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
阅读(1775) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~