Skip to content

Instantly share code, notes, and snippets.

@sarjsheff
Created June 7, 2020 06:23
Show Gist options
  • Select an option

  • Save sarjsheff/79b5ab233371604239b2259275d389b8 to your computer and use it in GitHub Desktop.

Select an option

Save sarjsheff/79b5ab233371604239b2259275d389b8 to your computer and use it in GitHub Desktop.
Store tasmota mqtt events in GUN database.
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