48 lines
1.1 KiB
JavaScript
48 lines
1.1 KiB
JavaScript
const mqtt = require('mqtt');
|
|
|
|
const em = require('events').EventEmitter;
|
|
const util = require('util');
|
|
const logger = require('log4js').getLogger('MQTT');
|
|
logger.level = 'trace';
|
|
|
|
const MqttController = function() {
|
|
const _this = this;
|
|
|
|
const options = {
|
|
'keepalive': 3600,
|
|
'clientId': 'aida',
|
|
'clean' : false
|
|
};
|
|
|
|
this.on('newListener', listener => {
|
|
logger.info(`Event Listener: ${ listener}`);
|
|
});
|
|
|
|
logger.debug('Trying to connect');
|
|
this.client = mqtt.connect('mqtt://192.168.1.156', options);
|
|
|
|
this.client.on('error', function(m) {
|
|
logger.error(m);
|
|
}.bind(this));
|
|
|
|
this.client.on('connect', function () {
|
|
logger.debug('MQTT Connected');
|
|
this.client.subscribe('bedroomTemp');
|
|
this.emit('found');
|
|
}.bind(this));
|
|
|
|
this.client.on('message', function (topic, message) {
|
|
// message is Buffer
|
|
const msg = message.toString();
|
|
const json = JSON.parse(msg);
|
|
// client.end()
|
|
this.emit(topic, json.temp);
|
|
}.bind(this));
|
|
|
|
return this;
|
|
};
|
|
|
|
util.inherits(MqttController, em);
|
|
|
|
module.exports = MqttController;
|