Set up mDNS in a more fool-proof way

This commit is contained in:
Gergely Polonkai 2021-01-18 10:57:45 +01:00
parent 44dc23051f
commit de722e001c
No known key found for this signature in database
GPG Key ID: 2D2885533B869ED4

View File

@ -47,6 +47,9 @@
# include <Adafruit_BMP085.h>
#endif // HAVE_BMP180
char *negotiated_hostname = NULL;
bool hostname_verified = false;
MDNSResponder::hMDNSService mdns_service = NULL;
ESP8266WebServer server(80);
unsigned long last_update = 0;
@ -163,6 +166,42 @@ stop()
}
}
bool
set_station_hostname(const char *hostname)
{
if (hostname) {
WiFi.hostname(hostname);
}
return true;
}
void
host_probe_result(String hostname, bool result)
{
if (result == true) {
set_station_hostname(negotiated_hostname);
if (!hostname_verified) {
hostname_verified = true;
if (!mdns_service) {
mdns_service = MDNS.addService(0, "http", "tcp", 80);
if (mdns_service) {
MDNS.addServiceTxt(mdns_service, "port#", 80);
}
}
}
} else {
if (MDNSResponder::indexDomain(negotiated_hostname, "-", 0)) {
MDNS.setHostname(negotiated_hostname);
} else {
Serial.println("Failed to set mDNS hostname");
}
}
}
void
setup()
{
@ -183,8 +222,11 @@ setup()
address.printTo(Serial);
Serial.println("");
if (!MDNS.begin(MDNS_NAME)) {
Serial.println("Error setting up mDNS responder!");
MDNS.setHostProbeResultCallback(host_probe_result);
if ((!MDNSResponder::indexDomain(negotiated_hostname, 0, MDNS_NAME)) ||
(!MDNS.begin(negotiated_hostname))) {
Serial.println("Error setting up mDNS!");
stop();
}
@ -194,8 +236,6 @@ setup()
server.begin();
MDNS.addService("http", "tcp", 80);
// Initialize sensors
#ifdef DHT_TYPE
dht.begin();