Advertisement
Guest User

Untitled

a guest
Mar 29th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mqtt = require('mqtt');
  2. var db = require('./db');
  3. var topic_klima = 'esp/klima'; //subscribe to all topics with #
  4. var topic_onoff = 'esp/onoff'; //subscribe to all topics with #
  5. var Broker_URL = 'mqtt://m24.cloudmqtt.com';
  6.  
  7.  
  8. var options = {
  9.   clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
  10.   port: 16646,
  11.   username: 'myuser',
  12.   password: 'mypass',
  13.   keepalive: 60
  14. };
  15.  
  16. var client = mqtt.connect(Broker_URL, options);
  17. client.on('connect', mqtt_connect_onoff);
  18. client.on('connect', mqtt_connect_klima);
  19.  
  20. client.on('message', mqtt_messsageReceived);
  21. client.on('reconnect', mqtt_reconnect);
  22. client.on('close', mqtt_close);
  23.  
  24. function mqtt_connect_onoff() {
  25.   console.log("Connecting MQTT to onoff");
  26.   client.subscribe(topic_onoff);
  27.   console.log("Subscribed to " + topic_onoff);
  28. };
  29.  
  30. function mqtt_connect_klima() {
  31.   console.log("Connecting MQTT to klima");
  32.   client.subscribe(topic_klima);
  33.   console.log("Subscribed to " + topic_klima);
  34. };
  35.  
  36.  
  37. function mqtt_reconnect(err) {
  38.   console.log("Reconnect MQTT");
  39.   if (err) { console.log(err); }
  40.   client = mqtt.connect(Broker_URL, options);
  41. };
  42.  
  43. //receive a message from MQTT broker
  44. function mqtt_messsageReceived_klima(topic_klima, message, packet) {
  45.   var message_str = message.toString(); //convert byte array to string
  46.   var obj = JSON.parse(message_str);
  47.   console.log(obj);
  48.  
  49.   if (message_str.length == 0) {
  50.     console.log("Invalid payload");
  51.   } else {
  52.     if (obj.topic == "esp/klima") {
  53.       db.insertKlima(obj.temperatur, obj.luftfeuchte);
  54.       console.log("Inserted klima")
  55.     }
  56.   }
  57. };
  58.  
  59. //receive a message from MQTT broker
  60. function mqtt_messsageReceived(topic, message, packet) {
  61.   var message_str = message.toString(); //convert byte array to string
  62.   var obj = JSON.parse(message_str);
  63.  
  64.   if (message_str.length == 0) {
  65.     console.log("Invalid payload");
  66.   } else {
  67.     if (obj.topic == "esp/onoff") {
  68.       db.insertOnoff(obj.lampe, obj.zuluft, obj.abluft, obj.umluft);
  69.       console.log("Inserted onoff")
  70.     }
  71.     if (obj.topic == "esp/klima") {
  72.       db.insertKlima(obj.temperatur, obj.luftfeuchte);
  73.       console.log("Inserted klima")
  74.     }
  75.   }
  76. };
  77.  
  78. function mqtt_close() {
  79.   console.log("Close MQTT");
  80. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement