Created
June 7, 2020 06:23
-
-
Save sarjsheff/79b5ab233371604239b2259275d389b8 to your computer and use it in GitHub Desktop.
Store tasmota mqtt events in GUN database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var Gun = require('gun'); | |
| const gun = Gun("http://localhost:8888/gun"); | |
| gun.get("switches").map().on(function(v, name) { | |
| console.log(name, v.status, v.power || "ON", v.temp || "?"); | |
| }) | |
| var mqtt = require('mqtt') | |
| var client = mqtt.connect('mqtt://localhost', { | |
| username: "sonoff", | |
| password: "password" | |
| }) | |
| client.on('connect', function() { | |
| console.log("connected"); | |
| client.subscribe('stat/#', function(err) { | |
| if (!err) { | |
| console.log("sub to state"); | |
| } else { | |
| console.log("Error", err); | |
| } | |
| }); | |
| client.subscribe('tele/#', function(err) { | |
| if (!err) { | |
| console.log("sub to tele"); | |
| } else { | |
| console.log("Error", err); | |
| } | |
| }); | |
| }); | |
| client.on('message', function(topic, message) { | |
| const t = topic.split("/"); | |
| if (t[2] == "LWT") { | |
| var sw = gun.get(t[1]); | |
| sw.get("status").put(message.toString("utf8")) | |
| gun.get("switches").set(sw); | |
| } else if (t[2] == "POWER") { | |
| var sw = gun.get(t[1]); | |
| sw.get("power").put(message.toString("utf8")) | |
| gun.get("switches").set(sw); | |
| } else if (t[2] == "SENSOR") { | |
| var sw = gun.get(t[1]); | |
| const sensor = JSON.parse(message).AM2301; | |
| sw.get("temp").put(sensor.Temperature) | |
| sw.get("hum").put(sensor.Humidity) | |
| sw.get("dew").put(sensor.DewPoint) | |
| console.log(JSON.parse(message).AM2301); | |
| gun.get("switches").set(sw); | |
| } else if (t[2] == "RESULT") { | |
| var sw = gun.get(t[1]); | |
| sw.get("power").put(JSON.parse(message).POWER) | |
| gun.get("switches").set(sw); | |
| } else { | |
| console.log(topic, message.toString('utf8')); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment