Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mqtt = require('mqtt');
- var db = require('./db');
- var topic_klima = 'esp/klima'; //subscribe to all topics with #
- var topic_onoff = 'esp/onoff'; //subscribe to all topics with #
- var Broker_URL = 'mqtt://m24.cloudmqtt.com';
- var options = {
- clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
- port: 16646,
- username: 'myuser',
- password: 'mypass',
- keepalive: 60
- };
- var client = mqtt.connect(Broker_URL, options);
- client.on('connect', mqtt_connect_onoff);
- client.on('connect', mqtt_connect_klima);
- client.on('message', mqtt_messsageReceived);
- client.on('reconnect', mqtt_reconnect);
- client.on('close', mqtt_close);
- function mqtt_connect_onoff() {
- console.log("Connecting MQTT to onoff");
- client.subscribe(topic_onoff);
- console.log("Subscribed to " + topic_onoff);
- };
- function mqtt_connect_klima() {
- console.log("Connecting MQTT to klima");
- client.subscribe(topic_klima);
- console.log("Subscribed to " + topic_klima);
- };
- function mqtt_reconnect(err) {
- console.log("Reconnect MQTT");
- if (err) { console.log(err); }
- client = mqtt.connect(Broker_URL, options);
- };
- //receive a message from MQTT broker
- function mqtt_messsageReceived_klima(topic_klima, message, packet) {
- var message_str = message.toString(); //convert byte array to string
- var obj = JSON.parse(message_str);
- console.log(obj);
- if (message_str.length == 0) {
- console.log("Invalid payload");
- } else {
- if (obj.topic == "esp/klima") {
- db.insertKlima(obj.temperatur, obj.luftfeuchte);
- console.log("Inserted klima")
- }
- }
- };
- //receive a message from MQTT broker
- function mqtt_messsageReceived(topic, message, packet) {
- var message_str = message.toString(); //convert byte array to string
- var obj = JSON.parse(message_str);
- if (message_str.length == 0) {
- console.log("Invalid payload");
- } else {
- if (obj.topic == "esp/onoff") {
- db.insertOnoff(obj.lampe, obj.zuluft, obj.abluft, obj.umluft);
- console.log("Inserted onoff")
- }
- if (obj.topic == "esp/klima") {
- db.insertKlima(obj.temperatur, obj.luftfeuchte);
- console.log("Inserted klima")
- }
- }
- };
- function mqtt_close() {
- console.log("Close MQTT");
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement