Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Support for mDNS #27

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 48 additions & 5 deletions ampel-main/ampel-main.ino
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include <RunningMedian.h> // https://github.com/RobTillaart/RunningMedian
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson (Version 5.10.0 only)
#include <ESP8266HTTPClient.h>
#include <ESP8266mDNS.h>

// NeoPixels
#define PIN D8 // NeoPixels pin
Expand All @@ -34,12 +35,12 @@ SCD30 airSensor;

String outputState = "off";
char sensorurl[200] = "www.mydomain.tld/sensor.php";
char mdnsname[200] = "my-co2ampel";
unsigned long startMillis = 560000; //900000
const unsigned long period = 600000;

// Flag for saving data
bool shouldSaveConfig = false;
int sensorint;

// Button menu
int menuselect = 0;
Expand All @@ -53,6 +54,16 @@ void saveConfigCallback () {
}


// mDNS server
#define SERVICE_PORT 8085
#define UPDATE_CYCLE (1 * 1000) // every second

char* pcHostDomain = 0; // Negociated host domain
bool bHostDomainConfirmed = false; // Flags the confirmation of the host domain
MDNSResponder::hMDNSService hMDNSService = 0; // The handle of the service in the MDNS responder
ESP8266WebServer server(SERVICE_PORT);
bool bGotNet = false;

int x;
int lux; // 60-200 (Luminous value of the NeoPixels)
int co2wert;
Expand All @@ -66,6 +77,8 @@ RunningMedian co2 = RunningMedian(5);
RunningMedian temperatur = RunningMedian(5);
RunningMedian luftfeuchte = RunningMedian(5);

bool gotWifiConfig = false;

void setup() {
Serial.begin(115200);
Serial.println("");
Expand Down Expand Up @@ -113,8 +126,16 @@ void setup() {
json.printTo(Serial);
if (json.success()) {
Serial.println("\nparsed json");
strcpy(sensorurl, json["sensorurl"]);
sensorint = jsonBuffer.size();
const char* sensorurlJS = json["sensorurl"];
if (sensorurlJS != nullptr) {
gotWifiConfig = true;
strcpy(sensorurl, sensorurlJS);
}
const char* mdnsnameJS = json["mdnsname"];
if (mdnsnameJS != nullptr) {
gotWifiConfig = true;
strcpy(mdnsname, mdnsnameJS);
}
} else {
Serial.println("Failed to load JSON configuration");
}
Expand All @@ -123,9 +144,24 @@ void setup() {
} else {
Serial.println("Failed to mount file system");
}
if (sensorint > 5) {
if (gotWifiConfig) {
//wenn die variable sensorurl grösser 5 ist
Serial.println("Activating WIFI");
WiFiManager wifiManager;
for (int maxWait=0;maxWait<10;maxWait++) {
if (WiFi.status() == WL_CONNECTED) {
bGotNet = true;
break;
}
delay(500);
Serial.print(".");
}
if (bGotNet) {
Serial.println("");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
setupMDNS();
}
}
}

Expand Down Expand Up @@ -182,6 +218,9 @@ void loop() {
checkmenu();
}
makeled();
if (bGotNet) {
loopMDNS();
}
}

void makewifi() {
Expand All @@ -192,23 +231,27 @@ void makewifi() {
pixels.show();
}
WiFiManagerParameter custom_output("URL", "URL (kein HTTPS)", sensorurl, 200);
WiFiManagerParameter custom_mdnsname("MDNSNAME", "mDNS Name", mdnsname, 200);
WiFiManager wifiManager;
// Set configuration save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_output);
wifiManager.addParameter(&custom_mdnsname);
//wifiManager.resetSettings();
wifiManager.setTimeout(120);
wifiManager.autoConnect("co2ampel");
Serial.println("Connected");

strcpy(sensorurl, custom_output.getValue());
strcpy(mdnsname, custom_mdnsname.getValue());

// Save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println("Saving configuration");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["sensorurl"] = sensorurl;

json["mdnsname"] = mdnsname;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("Failed to open config file for writing");
Expand Down
124 changes: 124 additions & 0 deletions ampel-main/mdns.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
setStationHostname
*/
bool setStationHostname(const char* p_pcHostname) {

if (p_pcHostname) {
WiFi.hostname(p_pcHostname);
Serial.printf("setDeviceHostname: Station hostname is set to '%s'\n", p_pcHostname);
}
return true;
}


/*
MDNSDynamicServiceTxtCallback

Add a dynamic MDNS TXT item 'ct' to the clock service.
The callback function is called every time, the TXT items for the clock service
are needed.
This can be triggered by calling MDNS.announce().

*/
/*
void MDNSDynamicServiceTxtCallback(const MDNSResponder::hMDNSService p_hService) {
Serial.println("MDNSDynamicServiceTxtCallback");
if (hMDNSService == p_hService) {
Serial.print(String("Updating TXT item to: ") + co2.getMedian() + "\n");
MDNS.addDynamicServiceTxt(p_hService, "co2ppm",(String("")+co2.getMedian()).c_str());
}
}
*/

/*
MDNSProbeResultCallback

Probe result callback for the host domain.
If the domain is free, the host domain is set and the clock service is
added.
If the domain is already used, a new name is created and the probing is
restarted via p_pMDNSResponder->setHostname().

*/
void hostProbeResult(String p_pcDomainName, bool p_bProbeResult) {

Serial.println("MDNSProbeResultCallback");
Serial.printf("MDNSProbeResultCallback: Host domain '%s.local' is %s\n", p_pcDomainName.c_str(), (p_bProbeResult ? "free" : "already USED!"));
if (true == p_bProbeResult) {
// Set station hostname
setStationHostname(pcHostDomain);
if (!bHostDomainConfirmed) {
// Hostname free -> setup clock service
bHostDomainConfirmed = true;
if (!hMDNSService) {
// Add a 'clock.tcp' service to port 'SERVICE_PORT', using the host domain as instance domain
hMDNSService = MDNS.addService(0, "co2ampel", "tcp", SERVICE_PORT);
/*
if (hMDNSService) {
// Add a simple static MDNS service TXT item
MDNS.addServiceTxt(hMDNSService, "tcpport", SERVICE_PORT);
// Set the callback function for dynamic service TXTs
MDNS.setDynamicServiceTxtCallback(MDNSDynamicServiceTxtCallback);
}
*/
}
}
} else {
// Change hostname, use '-' as divider between base name and index
if (MDNSResponder::indexDomain(pcHostDomain, "-", 0)) {
MDNS.setHostname(pcHostDomain);
} else {
Serial.println("MDNSProbeResultCallback: FAILED to update hostname!");
}
}
}


/*
handleHTTPClient
*/

void handleHTTPRequest() {
Serial.println("");
Serial.println("HTTP Request");
String s;
s = String("{\"co2\": ") + co2.getMedian() +String(",")
+ String("\"temperature\": ") + temperatur.getMedian() +String(",")
+ String("\"humidity\": ") + luftfeuchte.getMedian() + String(",")
+ String("\"brightness\": ") + licht.getMedian() + String("}\n");
Serial.println("Sending 200");
server.send(200, "application/json", s);
}

void setupMDNS() {
// Setup MDNS responder
MDNS.setHostProbeResultCallback(hostProbeResult);
if ((!MDNSResponder::indexDomain(pcHostDomain, 0, mdnsname)) ||
(!MDNS.begin(pcHostDomain))) {
Serial.println("Error setting up MDNS responder!");
return;
}
Serial.println("MDNS responder started");
// Setup HTTP server
server.on("/", handleHTTPRequest);
server.begin();
Serial.println("HTTP server started");
}

void loopMDNS() {
// Check if a request has come in
server.handleClient();
// Allow MDNS processing
MDNS.update();
/*
static esp8266::polledTimeout::periodicMs timeout(UPDATE_CYCLE);
if (timeout.expired()) {

if (hMDNSService) {
// Just trigger a new MDNS announcement, this will lead to a call to
// 'MDNSDynamicServiceTxtCallback', which will update the time TXT item
MDNS.announce();
}
}
*/
}