void WEBINTERFACE_CLASS::WebServer() { // Routing Table server.on("/wifisetup.html", handleWifi); server.on("/scan.json",handleScan); server.on("/", handleWifi); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); }
void setup() { Serial.begin(115200); delay(10); setup_wifi(); client.setServer(mqtt_server, 1883); Wire.begin(SDA, SCL); //sda,scl Serial.println("Sensor Test"); if (!bmp.begin()) { Serial.print("Ooops, no BMP180 detected ... Check your wiring or I2C ADDR!"); while (1); } else { Serial.println("BMP180 ready."); delay(1000); } /* OTA code */ ArduinoOTA.onStart([]() { Serial.println("Start"); }); ArduinoOTA.onEnd([]() { Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); // Set up mDNS responder: // - first argument is the domain name, in this example // the fully-qualified domain name is "esp8266.local" // - second argument is the IP address to advertise // we send our IP address on the WiFi network if (!MDNS.begin(hostname, WiFi.localIP())) { Serial.println("Error setting up MDNS responder!"); while(1) { delay(1000); } } Serial.print("mDNS responder started: "); Serial.print(hostname); Serial.println(".local"); httpUpdater.setup(&httpServer); httpServer.begin(); MDNS.addService("http", "tcp", 80); }
void handleNotFound(){ if(hasSD && loadFromSdCard(server.uri())) return; String message = "SDCARD Not Detected\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET)?"GET":"POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i=0; i<server.args(); i++){ message += " NAME:"+server.argName(i) + "\n VALUE:" + server.arg(i) + "\n"; } server.send(404, "text/plain", message); DBG_OUTPUT_PORT.print(message); }
void handleNotFound(){ if(loadFromSpiffs(httpd.uri())) return; String message = "File Not Found\n\n"; message += "URI: "; message += httpd.uri(); message += "\nMethod: "; message += (httpd.method() == HTTP_GET)?"GET":"POST"; message += "\nArguments: "; message += httpd.args(); message += "\n"; for (uint8_t i=0; i<httpd.args(); i++){ message += " NAME:"+httpd.argName(i) + "\n VALUE:" + httpd.arg(i) + "\n"; } httpd.send(404, "text/plain", message); // Serial.println(message); }
//http://192.168.4.1/config?ssid=street_no_vale2&pwd=jjjjjjjj&devid=CYURD001&ip=10.0.1.104&port=3332 void handleConfig(){ strcpy(ssid, server.arg("ssid").c_str()); strcpy(pwd, server.arg("pwd").c_str()); strcpy(devid, server.arg("devid").c_str()); strcpy(ip, server.arg("ip").c_str()); strcpy(port, server.arg("port").c_str()); server.send(200, "application/json", "{\"Success\":\"saved to eeprom... reset to boot into new wifi\"}"); saveConfig(); }
void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); }
void handleWifi() { // Check for args with connection settings if(server.args() > 0){ String temp = ""; temp = server.arg("ap"); if(temp.length() > 0){ quick_setup->CLIENT_SSID = temp; }else{ quick_setup->CLIENT_SSID = ""; } temp = server.arg("pw"); if(temp.length() > 0){ quick_setup->CLIENT_Password = temp; }else{ quick_setup->CLIENT_Password = ""; } // Save Settings quick_setup->SaveClientSettings(); quick_setup->Mode = CLIENT_MODE; wifi_helper->wifiSetup(); } String body = wifi_html; body.replace("$Network$",String(quick_setup->Mode == CLIENT_MODE ? quick_setup->CLIENT_SSID : quick_setup->AP_SSID)); body.replace("$Status$",String(quick_setup->Mode == CLIENT_MODE ? quick_setup->CLIENT_State : quick_setup->AP_State)); body.replace("$IP$",String(wifi_helper->IPtoString(quick_setup->Mode == CLIENT_MODE ? quick_setup->CLIENT_IP : quick_setup->AP_IP))); body.replace("$Mode$",String(quick_setup->Mode == CLIENT_MODE ? "Wifi Client" : "Access Point")); server.send(200, "text/html", body); }
void setup() { pinMode(LDR, INPUT); pinMode(BUTTON, INPUT); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); pinMode(BLUE, OUTPUT); delay(1000); Serial.begin(115200); Serial.println("Wifi Connecting"); WiFi.begin(wifiSSID, wifiPassword); wifi_station_set_auto_connect(true); wifi_station_set_hostname(wiFiHostname); wifiConnectCounter = 1; while (WiFi.status() != WL_CONNECTED) { delay(wifiRepeatInterval); wifiConnectCounter++; if (wifiConnectCounter > wifiMaxTries) { delay(wifiRepeatInterval * 1000 * 1000); wifiConnectCounter = 0; } } Serial.println("Wifi Connected"); server.on("/", handleRoot); server.begin(); }
bool loadFromSdCard(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.htm"; if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; else if(path.endsWith(".js")) dataType = "application/javascript"; else if(path.endsWith(".png")) dataType = "image/png"; else if(path.endsWith(".gif")) dataType = "image/gif"; else if(path.endsWith(".jpg")) dataType = "image/jpeg"; else if(path.endsWith(".ico")) dataType = "image/x-icon"; else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SD.open(path.c_str()); if(dataFile.isDirectory()){ path += "/index.htm"; dataType = "text/html"; dataFile = SD.open(path.c_str()); } if (!dataFile) return false; if (server.hasArg("download")) dataType = "application/octet-stream"; if (server.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); } dataFile.close(); return true; }
void setup() { Serial.begin(115200); Serial.println(); Serial.println("Starting WiFi..."); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); if (WiFi.waitForConnectResult() == WL_CONNECTED) { Serial.printf("OK\n"); Serial.printf("Starting UPnP..."); UPnPDevice device; device.setFriendlyName("Gateway LUPS"); device.setDeviceVersion("1.0"); device.setDeviceType("GatewayNativo"); device.setManufacturer("LUPS"); device.setManufacturerURL("http://lups.inf.ufpel.edu.br/"); device.setModelDescription("versao 1"); device.setModelName("Gateway Nativo"); device.setModelNumber("1.0"); device.setModelURL("http://lups.inf.ufpel.edu.br/"); device.setSerialNumber("12002983"); device.setPresentationURL("http://lups.inf.ufpel.edu.br/"); // device.addDevice(UPnPDevice inputDevice); // device.addService(UPnPService inputService); // device.addIcon(UPnPIcon inputIcon); HTTP.on("/index.html", HTTP_GET, []() { HTTP.send( 200, "text/plain", "ESP8266 - Gateway EXEHDA-IoT \n\n -> " "IP/temp?sensor=1 a 7 para " "ler temperatura DS18B20; \n -> IP/temp2438?sensor=1 a 7 para " "ler temperatura DS2438; \n -> IP/umidade?sensor=1 a 7 para ler " "umidade com HIH4000 e DS2438 \n -> IP/luz?sensor=1 a 7 para ler " "presenca de luz com LDR e DS2438."); }); HTTP.on("/description.xml", HTTP_GET, []() { UPnP.schema(HTTP.client()); }); HTTP.begin(); UPnP.setDevice(device); UPnP.setSchemaURL("description.xml"); UPnP.setHTTPPort(80); UPnP.begin(); Serial.printf("OK"); Serial.printf("Starting HTTP Server..."); Serial.printf("OK\n"); } else { Serial.printf("Failed\n"); while (1) delay(100); } }
// DELETEメソッドに対応 void handleDelete(){ if(server.args() == 0) return returnFail("BAD ARGS"); String path = server.arg(0); if(path == "/" || !SD.exists((char *)path.c_str())) { returnFail("BAD PATH"); return; } deleteRecursive(path); returnOK(); }
void MyFunctionRequestHandler::infoHandler(ESP8266WebServer& server) { String json = F("{"); json += '"'; json += F("heap"); json += '"'; json += ':'; json += '"'; json += String(ESP.getFreeHeap()); json += '"'; json += F(", "); json += '"'; json += F("ssid"); json += '"'; json += ':'; json += '"'; json += String(WiFi.SSID()); json += '"'; json += F(", "); json += '"'; json += F("ipaddress"); json += '"'; json += ':'; json += '"'; json += WiFi.localIP().toString(); json += '"'; json += F(", "); json += '"'; json += F("ipgateway"); json += '"'; json += ':'; json += '"'; json += WiFi.gatewayIP().toString(); json += '"'; json += F(", "); json += '"'; json += F("ipdns"); json += '"'; json += ':'; json += '"'; json += WiFi.dnsIP().toString(); json += '"'; json += F(", "); json += '"'; json += F("ipsubnetmask"); json += '"'; json += ':'; json += '"'; json += WiFi.subnetMask().toString(); json += '"'; json += F(", "); json += '"'; json += F("macaddress"); json += '"'; json += ':'; json += '"'; json += WiFi.macAddress(); json += '"'; json += F(", "); json += '"'; json += F("hostname"); json += '"'; json += ':'; json += '"'; json += WiFi.hostname(); json += '"'; json += F(", "); json += '"'; json += F("apipaddress"); json += '"'; json += ':'; json += '"'; json += WiFi.softAPIP().toString(); json += '"'; json += F(", "); json += '"'; json += F("apconnectedstations"); json += '"'; json += ':'; json += '"'; json += String(WiFi.softAPgetStationNum()); json += '"'; json += F(", "); json += '"'; json += F("wifiautoconnect"); json += '"'; json += ':'; json += '"'; json += String(WiFi.getAutoConnect()); json += '"'; json += F(", "); json += '"'; json += F("firmwareversion"); json += '"'; json += ':'; json += '"'; json += String(FIRMWARE_VERSION); json += '"'; json += '}'; server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store")); server.send(200, F("text/json"), json); }
void setupAP(){ WiFi.softAP(espssid); server.on("/", handleRoot); server.on("/config", handleConfig); server.on("/erase", handleErase); server.begin(); Serial.println(); Serial.print("connected as AP "); Serial.println(espssid); Serial.print("IP address: "); Serial.println(WiFi.softAPIP()); }
void handleFileUpload(){ if(server.uri() != "/edit") return; HTTPUpload& upload = server.upload(); if(upload.status == UPLOAD_FILE_START){ if(SD.exists((char *)upload.filename.c_str())) SD.remove((char *)upload.filename.c_str()); uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE); DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename); } else if(upload.status == UPLOAD_FILE_WRITE){ if(uploadFile) uploadFile.write(upload.buf, upload.currentSize); DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize); } else if(upload.status == UPLOAD_FILE_END){ if(uploadFile) uploadFile.close(); DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize); } }
bool NotFoundHandler::handle(ESP8266WebServer& server, HTTPMethod method, String uri) { if(flippie->config->verbose) Serial.printf("Handle '%s'(%s) in NotFoundHandler.\n", uri.c_str(), method == HTTP_GET ? "GET" : (method == HTTP_POST ? "POST" : "UNKOWN")); server.send(404, "text/html", String("Not found.")); return true; }
bool MyFunctionRequestHandler::handleStatic(ESP8266WebServer& server, String& actualUrl, const __FlashStringHelper* url, const __FlashStringHelper* staticFile, const __FlashStringHelper* contentType, bool mayCache){ if (actualUrl.equals(String(url))){ File file = SPIFFS.open(String(staticFile), String(F("r")).c_str()); if (file){ if (!mayCache){ server.sendHeader(F("Cache-Control"), F("private, max-age=0, no-cache, no-store")); } server.streamFile(file, contentType); //server.send(200, String(F("text/html")).c_str()); //server.client().write(file, 100); file.close(); return true; } } return false; }
// PUTメソッドに対応 void handleCreate(){ if(server.args() == 0) return returnFail("BAD ARGS"); String path = server.arg(0); if(path == "/" || SD.exists((char *)path.c_str())) { returnFail("BAD PATH"); return; } if(path.indexOf('.') > 0){ File file = SD.open((char *)path.c_str(), FILE_WRITE); if(file){ file.write((const char *)0); file.close(); } } else { SD.mkdir((char *)path.c_str()); } returnOK(); }
void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT); if (digitalRead(BUTTON_PIN) == 0) { Serial.println("Factory Reset"); } WiFiManager wifi; wifi.autoConnect(DEVICE_NAME); if (!mdns.begin(DEVICE_NAME, WiFi.localIP())) { Serial.println("Error setting up MDNS responder!"); } else { Serial.println("mDNS responder started"); } // Start TCP (HTTP) server server.begin(); Serial.println("TCP server started"); Serial.println("Listening on port 8266"); Serial.print("Sketch size: "); Serial.println(ESP.getSketchSize()); Serial.print("Free size: "); Serial.println(ESP.getFreeSketchSpace()); server.on("/", handle_root); server.on("/on", handle_on); server.on("/off", handle_off); httpUpdater.setup(&server); state = OFF; Serial.println("State: OFF"); pinMode(LED_PIN, OUTPUT); }
void MyFunctionRequestHandler::httpReboot(ESP8266WebServer& server, String message) { String response = F("<!DOCTYPE html>" "<html>" "<head>" "<title>Dynatrace UFO configuration changed. Rebooting now... </title>" "<META http-equiv='refresh' content='10;URL=/'>" "</head>" "<body>" "<center>"); response += message; response += F("Device is being rebooted. Redirecting to homepage in 10 seconds...</center>" "</body>" "</html>"); server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store")); server.send(200, F("text/html"), response); if (mDebug) Serial.println(F("ESP.restart()")); ESP.restart(); }
void SmartWifi::launchWeb(int webtype) { printer->println(""); printer->println("WiFi connected"); printer->print("Local IP: "); printer->println(WiFi.localIP()); printer->print("SoftAP IP: "); printer->println(WiFi.softAPIP()); createWebServer(webtype); // Start the server server.begin(); printer->println("Server started"); }
void setup() { delay(1000); Serial.begin(115200); lightMeter.begin(); delay(1000); Serial.println(); Serial.print("Configuring access point..."); /* You can remove the password parameter if you want the AP to be open. */ WiFi.softAP(ssid, password); IPAddress myIP = WiFi.softAPIP(); Serial.print("AP IP address: "); Serial.println(myIP); server.on("/",handleWebsite); server.on("/xml",handleXML); server.begin(); Serial.println("HTTP server started"); }
void handleRoot() { if (server.hasArg("redon")) { digitalWrite(15, HIGH); } else if (server.hasArg("redoff")) { digitalWrite(15, LOW); } else if (server.hasArg("greenon")) { digitalWrite(12, HIGH); } else if (server.hasArg("greenoff")) { digitalWrite(12, LOW); } else if (server.hasArg("blueon")) { digitalWrite(13, HIGH); } else if (server.hasArg("blueoff")) { digitalWrite(13, LOW); } else if (server.hasArg("off")) { digitalWrite(12, LOW); digitalWrite(13, LOW); digitalWrite(15, LOW); } int sensorValue = analogRead(LDR); char lightSensorValue[30]; dtostrf(sensorValue, 4, 3, lightSensorValue); int buttonValue = digitalRead(BUTTON); char buttonSensorValue[30]; dtostrf(buttonValue, 4, 3, buttonSensorValue); char request[1024]; strcpy(request, "<html><head>"); strcat(request, "<title>ESP8266 WittyCloud ESP12 Board</title>"); strcat(request, "<meta name=\"viewport\" content=\"width=device-width, " "initial-scale=1.0\"/>"); strcat(request, "</head><body><ul>"); strcat(request, "<li>Light sensor: "); strcat(request, lightSensorValue); strcat(request, "</li>"); strcat(request, "<li>Button: "); strcat(request, buttonSensorValue); strcat(request, "</li><hr />"); strcat(request, "<li>All: <a href=\"?off=1\">Off</a></li>"); strcat(request, "<li>Red: <a href=\"?redon=1\">On</a> <a " "href=\"?redoff=1\">Off</a></li>"); strcat(request, "<li>Green: <a href=\"?greenon=1\">On</a> <a " "href=\"?greenoff=1\">Off</a></li>"); strcat(request, "<li>Blue: <a href=\"?blueon=1\">On</a> <a " "href=\"?blueoff=1\">Off</a></li>"); strcat(request, "</body></html>"); server.send(200, "text/html", request); }
void handleStatus() { StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); String output; root["temperature"] = temperature; root["pressure"] = pressure; root["weight"] = weight; root.printTo(output); webServer.send(200, "application/json", output); }
void MyFunctionRequestHandler::dtIntegrationHandler(ESP8266WebServer& server) { String json = F("{"); json += '"'; json += F("enabled"); json += '"'; json += ':'; json += mpConfig->enabled ? F("true") : F("false"); json += F(", "); json += '"'; json += F("environmentid"); json += '"'; json += ':'; json += '"'; json += mpConfig->dynatraceEnvironmentID; json += '"'; json += F(", "); json += '"'; json += F("apikey"); json += '"'; json += ':'; json += '"'; json += mpConfig->dynatraceApiKey; json += '"'; json += F(", "); json += '"'; json += F("interval"); json += '"'; json += ':'; json += '"'; json += mpConfig->pollingIntervalS; json += '"'; json += '}'; server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store")); server.send(200, F("text/json"), json); }
void SmartWifi::handleCycle(){ unsigned long currentMillis = millis(); if (currentMillis - previousMillisReboot >= intervalReboot) { // save the last time you blinked the LED previousMillisReboot = currentMillis; ESP.restart(); } if (setupMode){ intervalReboot = 360000; server.handleClient(); }else{ //webSocketLoop(); } }
void Threm::loop() { // #ifdef DEBUG // DEBUG << "Threm::loop" << endl; // #endif _thremContext->beforeLoop(); IThremPlugin*plugin; PluginMeta* meta; for (int i = 0; i < _plugins->size(); i++) { plugin = _plugins->get(i); meta = _pluginMeta->get(i); if (meta->isEnabled) { plugin->readData(_thremContext); } } yield(); LinkedList < ThremNotification* >* notifications = _thremContext->getNotifications(); for (int i = 0; i < _plugins->size(); i++) { plugin = _plugins->get(i); meta = _pluginMeta->get(i); if (meta->isEnabled) { for (int n = 0; n < notifications->size(); n++) { plugin->writeData(notifications->get(n)); } } } yield(); _thremContext->afterLoop(); ESP8266WebServer* server = _thremContext->getServer(); server->handleClient(); }
void webServerSetup() { webServer.on("/status.json", handleStatus); webServer.serveStatic("/config.json", SPIFFS, "/config.json"); webServer.serveStatic("/", SPIFFS, "/public/index.html"); webServer.serveStatic("/assets/brewMonitor.js", SPIFFS, "/public/assets/brewMonitor.js"); webServer.onNotFound(handleNotFound); webServer.begin(); }
bool loadFromSpiffs(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.html"; if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".html")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; else if(path.endsWith(".js")) dataType = "application/javascript"; else if(path.endsWith(".png")) dataType = "image/png"; else if(path.endsWith(".gif")) dataType = "image/gif"; else if(path.endsWith(".jpg")) dataType = "image/jpeg"; else if(path.endsWith(".ico")) dataType = "image/x-icon"; else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip"; File dataFile = SPIFFS.open(path.c_str(), "r"); if (httpd.hasArg("download")) dataType = "application/octet-stream"; if (httpd.streamFile(dataFile, dataType) != dataFile.size()) { } dataFile.close(); return true; }
void loop() { client.loop(); //start the OTA handler ArduinoOTA.handle(); httpServer.handleClient(); long now = millis(); if(now - lastMsg > 1000) { lastMsg = now; if (!client.connected()) { reconnect(); } /* Get a new sensor event */ sensors_event_t bmpEvent; bmp.getEvent(&bmpEvent); if (bmpEvent.pressure) { bmp.getTemperature(&temp); float newPress = bmpEvent.pressure; float newTempF = convertToF(temp); if (checkBound(newTempF, tempF, diff)) { tempF = newTempF; Serial.print("New temperature:"); Serial.println(String(tempF).c_str()); client.publish(TOPIC_TEMP, String(tempF).c_str(), true); } if (checkBound(newPress, pressure, 3.00)) { pressure = newPress; Serial.print("New pressure:"); Serial.println(String(pressure).c_str()); client.publish(TOPIC_PRESS, String(pressure).c_str(), true); } } else { Serial.println("Sensor error"); } } }
void setup(void){ pinMode(led, OUTPUT); digitalWrite(led, LED_OFF); // Note the serial rate - if you don't match it when connecting you'll get garbage. Serial.begin(115200); WiFi.begin(ssid, password); Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // This tells the network that you can access the ip address of the esp8266 via 'esp8266.local' // The first arg is the hostname - '.local' will be appended to it, the second arg is the ip address if (mdns.begin("esp8266", WiFi.localIP())) { Serial.println("MDNS responder started"); } server.on("/", handleRoot); server.on("/inline", [](){ server.send(200, "text/plain", "this works as well"); }); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); }