Commit 5e466683 by Chavee Issariyapat

add mqtt client

parent e16883ec
require('dotenv').config();
const config = require('config');
const MQTTClient = require('./mqttclient');
let mqttclient = MQTTClient.create({
host: config.get('config.broker_uri'),
options: {
clientId: config.get('config.flowagent_id'),
username: config.get('config.flowagent_username'),
password: config.get('config.flowagent_password'),
keepalive: 30
}
});
mqttclient.connect();
module.exports.create = create
const MQTT = require('mqtt');
const events = require('events');
const MQTTClient = function(param = {}) {
this.client = null;
this.host = param.host;
this.options = param.options;
}
MQTTClient.prototype = new events.EventEmitter;
MQTTClient.prototype.connect = function() {
var that = this;
this.client = MQTT.connect(this.host, this.options || {});
this.client.on('connect', function() {
that.emit('connect');
});
this.client.on('disconnect', function() {
});
this.client.on('message', async function(topic, payload) {
that.emit('message', topic, payload);
});
this.client.on('error', function(error) {
console.log('MQClient Error:');
console.log(error);
});
}
MQTTClient.prototype.publish = function(topic, payload) {
this.client.publish(topic, payload);
}
function create(param) {
return new MQTTClient(param);
}
......@@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"start": "node index.js"
},
"repository": {
"type": "git",
......@@ -18,3 +18,4 @@
"mqtt": "^3.0.0"
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment