就让我来试试传说中最适用于IOT的MQTT协议。

安装

虽然搜索资料很多,但大多是MQTT的使用,尽管有搭建服务器的文章,但我感觉写的不太清楚,大多数文章选择了Mosquitto(也许是Eclipse大厂出品的原因)。
经过寻找,找到了Nodejs写的mosca,但在Pi上老是安装失败,翻了翻Issues,找到了同作者写的依赖性小,轻量化的aedes。

npm install aedes --save
//最小例子
var aedes = require('aedes')();
var server = require('net').createServer(aedes.handle);
server.listen(8266);

简单使用

将所有的订阅与推送保存到sqlite3数据库中:

//Nodejs
var aedes = require('aedes')();
var colors = require('colors');
var server = require('net').createServer(aedes.handle);
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('data.db');
var port = 8266;
//更多事件查看Github:https://github.com/mcollina/aedes
aedes.on('publish',function(packet,client) {
    if (client) {
        console.log('[ Publish ] CilentID:'.green,client.id,' Qos:'.green,packet.qos,' Data:[ '.green,String(packet.payload),' ]'.green);
        db.run("INSERT INTO publish (date,client_id,topic,data) VALUES (datetime('now'),?,?,?);",[client.id,packet.topic,String(packet.payload)]);
    }
});
aedes.on('subscribe', function (subscriptions, client) {
    if (client) {
        //subscriptions懒得历遍(一般情况同时只有一个吧)
        db.run("INSERT INTO subscribe (date,client_id,topic) VALUES (datetime('now'),?,?)",[client.id,subscriptions[0].topic]);
        console.log('[ Subscribe ] SubscripTions:'.green,subscriptions[0].topic,' Qos:'.green,subscriptions[0].qos,' CilentID:'.green,client.id);
    }
});
aedes.on('unsubscribe',function(unsubscriptions,client){
    if(client){
        //同理
        console.log('[ unSubscribe ] unSubscripTions:'.green,unsubscriptions[0],' CilentID:'.green,client.id);
        db.run("DELETE FROM subscribe WHERE client_id = ? AND topic = ?;",[client.id,unsubscriptions[0]])
    }
});
server.listen(port,function(){
    console.log('[ Server ] server listening on port'.green,port)
});

//Sqlite3
CREATE TABLE "publish" ( `date` TEXT NOT NULL, `client_id` TEXT NOT NULL, `topic` TEXT NOT NULL, `data` TEXT NOT NULL );
CREATE TABLE "subscribe" ( `date` TEXT NOT NULL, `client_id` TEXT NOT NULL, `topic` TEXT NOT NULL );

//Micropython for ESP8266
>>> from umqtt.simple import MQTTClient                                                                                                                                                                                    
>>> conn = MQTTClient('esp8266','192.168.1.64',8266)                             
>>> conn.connect()                                                              
0                                                                               
>>> conn.publish(b'/test',b'test')                                              
>>> conn.disconnect()                                                           
                                                                  

优缺点

  • 轻量化
  • 可以更好的结合业务逻辑
  • 不支持或不完全支持Qos2