! :) hot reload of Garden IP setting when new IP advertised by garden controller over MQTT.

This commit is contained in:
Dobromir Popov
2023-05-15 13:27:09 +03:00
parent 1a33a40564
commit 9d8c3d74c4
3 changed files with 35 additions and 34 deletions

View File

@@ -41,9 +41,10 @@ config.gardenIP = process.env.GARDEN_IP || config.gardenIP
// defining HTTP endpoints
app.get('/', (req, res) => {
res.send([
{title: 'Hello, world (again)!'}
]);
res.redirect('/garden');
// res.send([
// {title: 'Hello, world (again)!'}
// ]);
});

View File

@@ -3,6 +3,7 @@ var db = require("./db");
const env = process.env.NODE_ENV || "development";
console.log("ENV: %s", env);
var fs = require("fs");
const path = require('path');
const configPath = path.join(__dirname, '/../config/config.json');
const config = require(configPath)[env];
@@ -43,10 +44,13 @@ console.log("MQTT: mqtt_settings.port : %s", mqtt_settings.port);
// mqttServer.on('clientConnected', function(){
// console.log("MQTT client connected !");
// });
var EspDeviceName = process.env.MQTT_ESP_NAME;
var EspDeviceName = process.env.MQTT_ESP_NAME || config.mqttEspName;
var mqtt = require("mqtt");
var mqtt_client = mqtt.connect("mqtt://" + mqtt_settings.host);
var mqtt_client = mqtt.connect("mqtt://" + mqtt_settings.host,
{
clientId: process.env.MQTT_WEBAPP_NAME || config.mqttWebappName || "iot.garden.dev.local"
});
mqtt_client.on("connect", function () {
console.log("MQTT connected to " + mqtt_settings.host + ". subscribing to topics");
mqtt_client.subscribe("tele/tasmota/STATE");
@@ -60,6 +64,7 @@ mqtt_client.on("connect", function () {
// mqtt_client.subscribe('ir');
// ESP_Easy_0 = garden
console.log("subscribing to topics '" + EspDeviceName + "/'");
mqtt_client.subscribe(EspDeviceName + "/+");
mqtt_client.subscribe(EspDeviceName + "/+/+");
mqtt_client.publish("tasmota", "controller connected");
@@ -178,22 +183,17 @@ mqtt_client.on("message", function (topic, message) {
console.log("MQTT> processing /ping message. Payload:" + context);
var data = context.replace(/^\{|\}$/g, '').split('|');
var ip = data[4].replace(/"/g, '');
console.log("got reporded garden controller IP: " + ip);
console.log("MQTT> /ping got us " + data.length + "data items");
if (ip != config.gardenIP) {
//console.log("MQTT> /ping got us " + data.length + " data items");
config.gardenIP = ip;
// Make a copy of config and change that
let newConfig = Object.assign({}, config);
newConfig.gardenIP = ip;
// Write the new config back to the original file
let newConfig = require(configPath);
newConfig[env].gardenIP = ip;
fs.writeFileSync(configPath, JSON.stringify(newConfig, null, 2));
} catch (e) {
console.log("MQTT> error at /ping: " + e);
console.log("Got NEW reporded garden controller IP: " + ip + ". new value stored in persistent settings storage");
}
} catch (e) {
console.log("MQTT> error processing /ping message: " + e);
}
}
if (!handled) {