Skip to content

Commit

Permalink
FeatureRequest: MQTT-Auto-Discovery for Home Assitant
Browse files Browse the repository at this point in the history
Fixes #22 - first intergation incl. config for full message or empty message
  • Loading branch information
ohAnd committed Jun 5, 2024
1 parent b279666 commit 8905302
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 29 deletions.
8 changes: 1 addition & 7 deletions include/Config.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ struct UserConfig
char mqttBrokerUser[64] = "dtuuser";
char mqttBrokerPassword[64] = "dtupass";
char mqttBrokerMainTopic[32] = "dtu1";
boolean mqttHAautoDiscovery = false;
boolean mqttActive = false;

uint8_t displayConnected = 0; // OLED default
Expand All @@ -41,13 +42,6 @@ struct UserConfig

extern UserConfig userConfig;

// struct for web update
typedef struct keyAndValue_
{
char key[30];
String value;
} keyAndValue_t;

// Define the UserConfigManager class
class UserConfigManager {
public:
Expand Down
4 changes: 2 additions & 2 deletions include/version.h
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
#define VERSION "1.6.0_localDev"
#define BUILDTIME "05.06.2024 - 19:12:17"
#define BUILDTIMESTAMP "1717607537"
#define BUILDTIME "06.06.2024 - 00:11:48"
#define BUILDTIMESTAMP "1717625508"
2 changes: 1 addition & 1 deletion include/version.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"version": "1.6.0_localDev",
"versiondate": "05.06.2024 - 19:12:17",
"versiondate": "06.06.2024 - 00:11:48",
"linksnapshot": "https://github.com/ohAnd/dtuGateway/releases/download/snapshot/dtuGateway_snapshot_1.6.0_localDev.bin",
"link": "https://github.com/ohAnd/dtuGateway//releases/latest/download/dtuGateway_release_1.6.0_localDev.bin"
}
3 changes: 1 addition & 2 deletions platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
platform = espressif8266
board = esp07s
framework = arduino
monitor_port = COM4
monitor_port = COM3
monitor_speed = 115200
lib_deps =
arduino-libraries/NTPClient @ ^3.2.1
Expand All @@ -37,7 +37,6 @@ monitor_filters =
default
time
build_flags =
; Define the TFT driver, pins etc. here:
-DGC9A01_DRIVER=1
-DTFT_WIDTH=240
-DTFT_HEIGHT=240
Expand Down
4 changes: 4 additions & 0 deletions src/Config.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ void UserConfigManager::printConfigdata()
Serial.println(userConfig.mqttBrokerMainTopic);
Serial.print(F("mqtt binding active: \t"));
Serial.println(userConfig.mqttActive);
Serial.print(F("mqtt HA autoDiscovery: \t"));
Serial.println(userConfig.mqttHAautoDiscovery);

Serial.print(F("dtu update time: \t"));
Serial.println(userConfig.dtuUpdateTime);
Expand Down Expand Up @@ -167,6 +169,7 @@ JsonDocument UserConfigManager::mappingStructToJson()
doc["mqtt"]["user"] = userConfig.mqttBrokerUser;
doc["mqtt"]["pass"] = userConfig.mqttBrokerPassword;
doc["mqtt"]["mainTopic"] = userConfig.mqttBrokerMainTopic;
doc["mqtt"]["HAautoDiscovery"] = userConfig.mqttHAautoDiscovery;

doc["display"]["type"] = userConfig.displayConnected;

Expand Down Expand Up @@ -199,6 +202,7 @@ void UserConfigManager::mappingJsonToStruct(JsonDocument doc)
String(doc["mqtt"]["user"]).toCharArray(userConfig.mqttBrokerUser, sizeof(userConfig.mqttBrokerUser));
String(doc["mqtt"]["pass"]).toCharArray(userConfig.mqttBrokerPassword, sizeof(userConfig.mqttBrokerPassword));
String(doc["mqtt"]["mainTopic"]).toCharArray(userConfig.mqttBrokerMainTopic, sizeof(userConfig.mqttBrokerMainTopic));
userConfig.mqttHAautoDiscovery = doc["mqtt"]["HAautoDiscovery"];

userConfig.displayConnected = doc["display"]["type"];

Expand Down
80 changes: 63 additions & 17 deletions src/dtuGateway.ino
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ int8_t blinkCode = BLINK_WIFI_OFF;
Display displayOLED;
DisplayTFT displayTFT;

String host;
WiFiUDP ntpUDP;
WiFiClient dtuClient;
NTPClient timeClient(ntpUDP); // By default 'pool.ntp.org' is used with 60 seconds update interval
Expand All @@ -82,6 +81,8 @@ PubSubClient mqttClient(puSubClient);
ESP8266WebServer server(80);

uint32_t chipID = ESP.getChipId();
String espUniqueName = String(apNameStart) + "_" + chipID;
IPAddress dtuGatewayIP;
unsigned long starttime = 0;

// intervall for getting and sending temp
Expand Down Expand Up @@ -290,7 +291,7 @@ void handleInfojson()
{
String JSON = "{";
JSON = JSON + "\"chipid\": " + String(chipID) + ",";
JSON = JSON + "\"host\": \"" + String(host) + "\",";
JSON = JSON + "\"host\": \"" + espUniqueName + "\",";
JSON = JSON + "\"initMode\": " + userConfig.wifiAPstart + ",";

JSON = JSON + "\"firmware\": {";
Expand Down Expand Up @@ -385,11 +386,11 @@ void handleUpdateWifiSettings()

void handleUpdateDtuSettings()
{
String dtuHostIpDomainUser = server.arg("dtuHostIpDomainSend"); // retrieve message from webserver
String dtuDataCycle = server.arg("dtuDataCycleSend"); // retrieve message from webserver
String dtuCloudPause = server.arg("dtuCloudPauseSend"); // retrieve message from webserver
String dtuSSIDUser = server.arg("dtuSsidSend"); // retrieve message from webserver
String dtuPassUser = server.arg("dtuPasswordSend"); // retrieve message from webserver
String dtuHostIpDomainUser = server.arg("dtuHostIpDomainSend"); // retrieve message from webserver
String dtuDataCycle = server.arg("dtuDataCycleSend"); // retrieve message from webserver
String dtuCloudPause = server.arg("dtuCloudPauseSend"); // retrieve message from webserver
String dtuSSIDUser = server.arg("dtuSsidSend"); // retrieve message from webserver
String dtuPassUser = server.arg("dtuPasswordSend"); // retrieve message from webserver
Serial.println("\nhandleUpdateDtuSettings - got dtu ip: " + dtuHostIpDomainUser + "- got dtuDataCycle: " + dtuDataCycle + "- got dtu dtuCloudPause: " + dtuCloudPause);
Serial.println("handleUpdateDtuSettings - got dtu ssid: " + dtuSSIDUser + " - got WifiPass: " + dtuPassUser);

Expand Down Expand Up @@ -510,7 +511,8 @@ void handleConfigPage()
String key1 = key.substring(0, key.indexOf("."));
String key2 = key.substring(key.indexOf(".") + 1);

if (value == "false" || value == "true") {
if (value == "false" || value == "true")
{
bool boolValue = (value == "true");
doc[key1][key2] = boolValue;
}
Expand Down Expand Up @@ -1043,6 +1045,49 @@ boolean updateValuesToMqtt()
return true;
}

boolean sendHAautoDiscovery()
{
JsonDocument doc;
String haTopicPath = "homeassistant/sensor/" + String(espUniqueName) + "/config";

doc["name"] = "HM_Gateway_total-energy";
doc["unique_id"] = espUniqueName;
doc["state_topic"] = haTopicPath;
doc["unit_of_measurement"] = "kWh";
doc["icon"] = "mdi:sine-wave";
doc["device"]["name"] = "HoymilesGateway";
doc["device"]["identifiers"] = "mymqttdevice01";
doc["device"]["manufacturer"] = "ohAnd";
doc["device"]["model"] = "ESP8266/ESP32";
doc["device"]["hw_version"] = "1.0";
doc["device"]["sw_version"] = String(VERSION);
doc["device"]["configuration_url"] = "http://" + dtuGatewayIP.toString();

// serializeJsonPretty(doc, Serial);
// serializeJson(doc, Serial);

char mqttPayload[1024];
size_t len = serializeJson(doc, mqttPayload);

connectCheckMqttClient();
if (mqttClient.connected())
{
if (userConfig.mqttHAautoDiscovery)
{
mqttClient.beginPublish(haTopicPath.c_str(), len, true);
mqttClient.print(mqttPayload);
mqttClient.endPublish();
Serial.println("\nHA autoDiscovery - send JSON to broker at " + haTopicPath);
}
else
{
postMessageToMQTTbroker(haTopicPath, "");
Serial.println("\nHA autoDiscovery - send empty payload to broker at " + haTopicPath);
}
}

return true;
}
// ****

void setup()
Expand Down Expand Up @@ -1088,9 +1133,8 @@ void setup()

// Connect to Wi-Fi as AP
WiFi.mode(WIFI_AP);
String apSSID = String(apNameStart) + "_" + chipID;
WiFi.softAP(apSSID);
Serial.println("\n +++ serving access point with SSID: '" + apSSID + "' +++\n");
WiFi.softAP(espUniqueName);
Serial.println("\n +++ serving access point with SSID: '" + espUniqueName + "' +++\n");

// IP Address of the ESP8266 on the AP network
IPAddress apIP = WiFi.softAPIP();
Expand All @@ -1104,13 +1148,13 @@ void setup()
// display - change every reboot in first start mode
if (userConfig.displayConnected == 0)
{
displayOLED.drawFactoryMode(String(VERSION), apSSID, apIP.toString());
displayOLED.drawFactoryMode(String(VERSION), espUniqueName, apIP.toString());
userConfig.displayConnected = 1;
configManager.saveConfig(userConfig);
}
else if (userConfig.displayConnected == 1)
{
displayTFT.drawFactoryMode(String(VERSION), apSSID, apIP.toString());
displayTFT.drawFactoryMode(String(VERSION), espUniqueName, apIP.toString());
userConfig.displayConnected = 0;
configManager.saveConfig(userConfig);
}
Expand Down Expand Up @@ -1149,16 +1193,16 @@ void startServices()
if (WiFi.waitForConnectResult() == WL_CONNECTED)
{
Serial.print(F("\nConnected! IP address: "));
Serial.println(WiFi.localIP());
dtuGatewayIP = WiFi.localIP();
Serial.println(dtuGatewayIP.toString());
Serial.print(F("IP address of gateway: "));
Serial.println(WiFi.gatewayIP());
host = "hoymilesGW_" + String(chipID);

httpUpdater.setup(&server);

MDNS.begin(host);
MDNS.begin(espUniqueName);
MDNS.addService("http", "tcp", 80);
Serial.println("Ready! Open http://" + String(host) + ".local in your browser");
Serial.println("Ready! Open http://" + espUniqueName + ".local in your browser");

// ntp time - offset in summertime 7200 else 3600
timeClient.begin();
Expand Down Expand Up @@ -1558,6 +1602,8 @@ void loop()
if (userConfig.openhabActive)
getPowerSetDataFromOpenHab();
}
// if (userConfig.mqttActive && userConfig.mqttHAautoDiscovery)
sendHAautoDiscovery();
}

// mid task
Expand Down

0 comments on commit 8905302

Please sign in to comment.