Last active
April 9, 2022 16:33
-
-
Save tzechienchu/a875954586a484c0d535 to your computer and use it in GitHub Desktop.
MQTT Service Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mqtt = require('mqtt'); | |
var uuid = require('node-uuid'); | |
// Import events module | |
var events = require('events'); | |
var MQTTService = (function () { | |
var instance; | |
function init() { | |
const NOTIFICATION_MESSAGE = 'F9D4494D-62F8-4CBD-BCCA-CC3DB557276A' | |
const SYSTEM_MESSAGE = '0F9AEAF1-EF9C-4414-9C1C-959B2EFC41EF'; | |
const MQTT_SERVER = 'mqtt://54.249.44.123'; | |
var mqttOptions = { | |
port:1883, | |
username:'appuser', | |
password:'iloveapp', | |
clientId: 'serverjs_'+uuid.v1(), | |
clear:false | |
} | |
var eventEmitter = new events.EventEmitter(); | |
var MessageClient = mqtt.connect(MQTT_SERVER,mqttOptions); | |
MessageClient.on('connect', function () { | |
MessageClient.subscribe(SYSTEM_MESSAGE); | |
}); | |
MessageClient.on('message', function (topic, message) { | |
console.log(topic+'---'+message); | |
eventEmitter.emit(topic,message); | |
}); | |
//Public Method | |
return { | |
NOTIFICATION_MESSAGE:NOTIFICATION_MESSAGE, | |
SYSTEM_MESSAGE:SYSTEM_MESSAGE, | |
publishMessage : function(topic,msg) { | |
MessageClient.publish(topic,msg); | |
}, | |
listenTo : function(topic,lscb) { | |
console.log('add'); | |
eventEmitter.on(topic, lscb); | |
} | |
}; | |
}; | |
return { | |
getInstance: function () { | |
if ( !instance ) { | |
instance = init(); | |
} | |
return instance; | |
} | |
}; | |
})(); | |
module.exports = MQTTService; | |
//How to use it. | |
var mqttService = require('../../common/models/mqttService.js'); | |
var myMQTT = mqttService.getInstance(); | |
console.log(myMQTT.SYSTEM_MESSAGE); | |
myMQTT.listenTo(myMQTT.SYSTEM_MESSAGE,function(message){ | |
console.log('MQTT:'+message.toString()); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment