最近为了完成课程布置的任务,也是自己感兴趣,想搞个简单的物联网,不料碰到了mqtt这个坑(也不算是吧,看网上都实现好久了)到网上找搜,答案不少
用了EMQ的broker,但是就是不知道,怎么把客户端的数据扒到服务器上存储下来,着急啊。。emq这些开发我还在看。
直到看到了Nodejs实现mosca的broker,似是找到了宝藏一样。wiki的传送门:https://github.com/mcollina/mosca/wiki
但到最后我还是没有用他所支持的数据库mongo啥的,还是自己在外面套了一层mysql
贴个代码
var mosca = require('mosca');
var mysql = require('mysql');
//连接数据库
var connection = mysql.createConnection({
host : 'localhost',
user : '用户名',
password : '密码',
port: '3306',
database: 'demo',
});
connection.connect();
/////////
var MqttServer = new mosca.Server({
port: 1883
});
MqttServer.on('clientConnected', function(client){
console.log('client connected', client.id);
});
/**
* * 监听MQTT主题消息
* **/
MqttServer.on('ready', function(){
console.log('mqtt is running...');
//MqttServer.authenticate = authenticate;
});
MqttServer.on('published', function(packet, client) {
var topic = packet.topic;
var message=packet.payload;
var arr=message.toString().split("*");
var addSqltemp = 'INSERT INTO temperature(tempDevice, tempClient, tempValue) VALUES (?,?,?)';
var addSqlhumi = 'INSERT INTO humidity(humiDevice, humiClient, humiValue) VALUES (?,?,?)';
if(arr[2]=='1')
{
var tharr=arr[3].split("/");
var addSqlParamstemp = [arr[0],arr[1],tharr[0]];
var addSqlParamshumi = [arr[0],arr[1],tharr[1]];
console.log('paras',"deviceid="+arr[0]+",clientID="+arr[1]+",temprature="+tharr[0]+",humi="+tharr[1]);
connection.query(addSqlhumi,addSqlParamshumi,function (err, result) {
if(err)
{
console.log('[INSERT ERROR] - ',err.message);
return;
}
// console.log('--------------------------INSERT----------------------------');
// console.log('INSERT ID:',result.insertId);
// console.log('INSERT ID:',result);
// console.log('-----------------------------------------------------------------\n\n');
});
connection.query(addSqltemp,addSqlParamstemp,function (err, result) {
if(err)
{
console.log('[INSERT ERROR] - ',err.message);
return;
}
// console.log('--------------------------INSERT----------------------------');
// console.log('INSERT ID:',result.insertId);
// console.log('INSERT ID:',result);
// console.log('-----------------------------------------------------------------\n\n');
});
}
console.log('message-arrived--->','topic ='+topic+',message = '+ packet.payload.toString());
});
mark一下以防丢失