Guest User

Untitled

a guest
Mar 20th, 2016
62
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mqtt = require('mqtt');
  2. var uuid = require('node-uuid');
  3.  
  4. // Import events module
  5. var events = require('events');
  6.  
  7. var MQTTService = (function () {
  8. var instance;
  9. function init() {
  10. const NOTIFICATION_MESSAGE = 'F9D4494D-62F8-4CBD-BCCA-CC3DB557276A'
  11. const SYSTEM_MESSAGE = '0F9AEAF1-EF9C-4414-9C1C-959B2EFC41EF';
  12. const MQTT_SERVER = 'mqtt://54.249.44.123';
  13.  
  14. var mqttOptions = {
  15. port:1883,
  16. username:'appuser',
  17. password:'iloveapp',
  18. clientId: 'serverjs_'+uuid.v1(),
  19. clear:false
  20. }
  21. var eventEmitter = new events.EventEmitter();
  22. var MessageClient = mqtt.connect(MQTT_SERVER,mqttOptions);
  23.  
  24. MessageClient.on('connect', function () {
  25. MessageClient.subscribe(SYSTEM_MESSAGE);
  26. });
  27.  
  28. MessageClient.on('message', function (topic, message) {
  29. console.log(topic+'---'+message);
  30. eventEmitter.emit(topic,message);
  31. });
  32.  
  33. //Public Method
  34. return {
  35. NOTIFICATION_MESSAGE:NOTIFICATION_MESSAGE,
  36. SYSTEM_MESSAGE:SYSTEM_MESSAGE,
  37.  
  38. publishMessage : function(topic,msg) {
  39. MessageClient.publish(topic,msg);
  40. },
  41. listenTo : function(topic,lscb) {
  42. console.log('add');
  43. eventEmitter.on(topic, lscb);
  44. }
  45. };
  46.  
  47. };
  48.  
  49. return {
  50. getInstance: function () {
  51.  
  52. if ( !instance ) {
  53. instance = init();
  54. }
  55. return instance;
  56. }
  57.  
  58. };
  59.  
  60. })();
  61.  
  62. module.exports = MQTTService;
  63.  
  64. //How to use it.
  65. var mqttService = require('../../common/models/mqttService.js');
  66.  
  67. var myMQTT = mqttService.getInstance();
  68.  
  69. console.log(myMQTT.SYSTEM_MESSAGE);
  70. myMQTT.listenTo(myMQTT.SYSTEM_MESSAGE,function(message){
  71. console.log('MQTT:'+message.toString());
  72. })
RAW Paste Data