Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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());
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement