document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. /* Pusher.js
  2. Server side node.js script that services real-time websocket requests
  3. Allows websocket connections to subscribe and publish to MQTT topics
  4. */
  5.  
  6. var sys = require(\'sys\');
  7. var net = require(\'net\');
  8. var mqtt = require(\'mqtt\');
  9.  
  10. // create a socket object that listens on port 5000
  11. var io = require(\'socket.io\').listen(5000);
  12.  
  13. // create an mqtt client object and connect to the mqtt broker
  14. var client = mqtt.connect(\'mqtt://192.168.1.116\');
  15.  
  16. io.sockets.on(\'connection\', function (socket) {
  17.     // socket connection indicates what mqtt topic to subscribe to in data.topic
  18.     socket.on(\'subscribe\', function (data) {
  19.         console.log(\'Subscribing to \'+data.topic);
  20.         socket.join(data.topic);
  21.         client.subscribe(data.topic);
  22.     });
  23.     // when socket connection publishes a message, forward that message
  24.     // the the mqtt broker
  25.     socket.on(\'publish\', function (data) {
  26.         console.log(\'Publishing to \'+data.topic);
  27.         client.publish(data.topic,data.payload);
  28.     });
  29. });
  30.  
  31. // listen to messages coming from the mqtt broker
  32. client.on(\'message\', function (topic, payload, packet) {
  33.     console.log(topic+\'=\'+payload);
  34.     io.sockets.emit(\'mqtt\',{\'topic\':String(topic),
  35.                             \'payload\':String(payload)});
  36. });
');