Advertisement
Guest User

Untitled

a guest
May 5th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. var mosca = require('mosca');
  2. var mqtt = require('mqtt');
  3. var fs = require('fs');
  4. var path = require('path');
  5.  
  6. var settings = {
  7. port: 1883
  8. };
  9.  
  10. var server = new mosca.Server(settings);
  11.  
  12. var mqttClient;
  13.  
  14. server.on('clientConnected', function(client) {
  15. console.log('Client connected: ', client.id);
  16.  
  17. var CERT = fs.readFileSync(path.join(__dirname, '/cert.pem'));
  18.  
  19. var options = {
  20. port: '443',
  21. host: 'broker.xively.com',
  22. cert: CERT,
  23. rejectUnauthorized: true,
  24. protocol: 'mqtts',
  25. clientid: '4679a4f0-3ebf-4b77-b18c-470dfa0ad49f',
  26. username: '4679a4f0-3ebf-4b77-b18c-470dfa0ad49f',
  27. password: 'qZS6Qr2ijOQe3H3+l+QUm0gGTKydWtSlRBJR72mbUGs='
  28. }
  29.  
  30. mqttClient = mqtt.connect(options);
  31.  
  32. mqttClient.on('message', function (topic, message) {
  33. var message = {
  34. topic: topic,
  35. payload: message
  36. };
  37.  
  38. server.publish(message, function() {
  39. console.log('A message from Xively was published to local broker');
  40. });
  41. });
  42.  
  43. mqttClient.on('connect', function () {
  44. var message = {
  45. topic: 'local/xivelyReady',
  46. payload: 'xivelyReady'
  47. };
  48.  
  49. server.publish(message, function() {
  50. console.log('Xively is ready!');
  51. });
  52. });
  53. });
  54.  
  55. server.on('subscribed', function (topic, client) {
  56. if (topic !== 'local/xivelyReady') {
  57. mqttClient.subscribe(topic);
  58. console.log('Subscribed to Xively topic');
  59. }
  60. });
  61.  
  62. // fired when a message is received
  63. server.on('published', function(packet, client) {
  64. if (packet.topic.split('/')[0] === 'localXi') {
  65. mqttClient.publish(packet.topic.replace(/localXi/i, 'xi'), packet.payload);
  66. console.log('Message published to xively broker');
  67. }
  68. });
  69.  
  70. server.on('ready', setup);
  71.  
  72. // fired when the mqtt server is ready
  73. function setup() {
  74. console.log('Mosca server is up and running');
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement