Für mein Olero Projekt brauche ich einen WebServer auf dem ESP8266, der sich selbst ins WLAN einhängt und innerhalb des LAN über eine lokale Domain (mDNS) erreichbar ist.
Sollte doch eigentlich nicht so schwer sein. Es gibt haufenweise Tutorials dazu im Internet. Aber egal welches Tutorial ich befolgte: mein ESP war nie über mDNS erreichbar – immer nur über seine IP.
Nach ewig langem Suchen bin ich dann über eine Diskussion gestolpert, die mir den notwendigen Hinweis gezeigt hat: bei allen Tutorials fehlten zwei mDNS Aufrufe! Kaum habe ich sie hinzugefügt, klappt alles wie am Schnürchen.
// ---------------------------------------------------------
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiClient.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
// WLAN settings it should try to connect to
const char *ssid = "MyNetworkSSID";
const char *password = "myNetworkPassword";
// Hostname for mDNS - note that .local will be added automatically
const char *hostname = "myeps";
// web server port - 80 is http
const int port = 80;
// Create a async http server
AsyncWebServer server(port);
// ---------------------------------------------------------
// Arduino setup function
// ---------------------------------------------------------
void setup(void) {
// connect to existing WLAN
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// wait for connection to be stablished - note: you should do some error handling here
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
// start HTTP server - note: might need some other setup beforehand
server.begin();
// setup mDNS - note: you should do error handling here
MDNS.begin(hostname);
// IMPORTANT: add http service to MDNS - this step was always missing
MDNS.addService("http", "tcp", 80);
}
// ---------------------------------------------------------
// Arduino main loop function
// ---------------------------------------------------------
void loop(void)
{
// IMPORTANT: this step was always missing, too
MDNS.update();
}
// end-of-file
// ---------------------------------------------------------
Und damit ist der ESP unter folgenden URLs zu finden:
- Windows 10: http://myesp.local
- Android: http://myesp.
Auf den Android Trick bin ich zufällig gestoßen. Einfach statt „.local“ nur den Punkt „.“ an die mDNS Domain anhängen und dann wird der ESP gefunden.
Der gesamte Source Code für einen ESP8266 Web Server ist auf Github unter https://github.com/emavok/esp8266-webserver zu finden.