示例#1
1
//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();
}
示例#2
1
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);
}
示例#3
1
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);
}
示例#4
1
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);
}
示例#5
1
// GETメソッドに対応
void printDirectory() {
  if(!server.hasArg("dir")) return returnFail("BAD ARGS");
  String path = server.arg("dir");
  if(path != "/" && !SD.exists((char *)path.c_str())) return returnFail("BAD PATH");
  File dir = SD.open((char *)path.c_str());
  path = String();
  if(!dir.isDirectory()){
    dir.close();
    return returnFail("NOT DIR");
  }
  dir.rewindDirectory();
  server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  server.send(200, "text/json", "");
  WiFiClient client = server.client();

  server.sendContent("[");
  for (int cnt = 0; true; ++cnt) {
    File entry = dir.openNextFile();
    if (!entry)
    break;

    String output;
    if (cnt > 0)
      output = ',';

    output += "{\"type\":\"";
    output += (entry.isDirectory()) ? "dir" : "file";
    output += "\",\"name\":\"";
    output += entry.name();
    output += "\"";
    output += "}";
    server.sendContent(output);
    entry.close();
 }
 server.sendContent("]");
 dir.close();
}
示例#6
1
void returnOK() {
  server.sendHeader("Connection", "close");
  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.send(200, "text/plain", "");
}
示例#7
0
void SmartWifi::createWebServer(int webtype){
  printer->println("starting web service");

  if ( webtype == 1 ) {
    printer->println("WebType: 1");
    server.on("/", [this]() {

        content="";
        IPAddress ip = WiFi.softAPIP();
        String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
        //content = "<!DOCTYPE HTML>\r\n<html>Hello from ESP8266 at ";
        //content += ipStr;
        //content += "<p>";
        //content += st;
        content += "<!DOCTYPE html> <html > <head> <meta charset='UTF-8'> <title>Setup</title> <meta name='viewport' content='width=device-width, initial-scale=1.0'>";
        content += "</head> <style> * { box-sizing: border-box; } html { height: 100%; } body { background-color: #2c3338; color: #606468; font: 400 0.875rem/1.5 'Open Sans', sans-serif; margin: 0";
        content += "min-height: 100%; } a { color: #eee; outline: 0; text-decoration: none; } a:focus, a:hover { text-decoration: underline; } h1{ text-align: center; font-size: 21px; color: #B5B5B5; } input { border: 0; color: inherit; font: inherit; margin: 0; outline: 0; padding: 0; -webkit-transition: background-color .3s; transition: background-color .3s; } .site__container { -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; padding: 3rem 0; } .form input[type='password'], .form input[type='text'], .form input[type='submit'], select { width: 100%; } .form--login { color: #606468; } .form--login label, .form--login input[type='text'], .form--login input[type='password'], .form--login select, .form--login input[type='submit'] { border-radius: 0.25rem; padding: 1rem; } .form--login label { background-color: #363b41; border-bottom-right-radius: 0; border-top-right-radius: 0; padding-left: 1.25rem; padding-right: 1.25rem; } .form--login input[type='text'], .form--login input[type='password'], select { background-color: #3b4148; border-bottom-left-radius: 0; border-top-left-radius: 0; } select,.form--login input[type='text']:focus, .form--login input[type='text']:hover, .form--login input[type='password']:focus, .form--login input[type='password']:hover { background-color: #434A52; } .form--login input[type='submit'] { background-color: #ea4c88; color: #eee; font-weight: bold; text-transform: uppercase; } .form--login input[type='submit']:focus, .form--login input[type='submit']:hover { background-color: #d44179; } .form__field { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; margin-bottom: 1rem; } .form__input { -webkit-box-flex: 1; -webkit-flex: 1; -ms-flex: 1; flex: 1; } .align { -webkit-box-align: center; -webkit-align-items: center; -ms-flex-align: center; align-items: center; display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-box-orient: horizontal; -webkit-box-direction: normal; -webkit-flex-direction: row; -ms-flex-direction: row; flex-direction: row; } select{ color:white; border:none; outline: none; color: #ABABAB; } option{ background-color:#434A52; color:#ABABAB; } .hidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } .text--center { text-align: center; } .grid__container { margin: 0 auto; max-width: 20rem; width: 90%; } </style> <body> <body class='align'> <div class='site__container'> <div class='grid__container'> <form method='get' action='setting' class='form form--login'> <h1>Wifi Setup</h1> <div class='form__field' id='ssidlist'> <select name='ssid'>"+st+" </select> </div> <div class='form__field'> <input name='pass' id='login__password' type='password' class='form__input' placeholder='Password' required> </div> <div class='form__field'> <input name='device' id='login__password' type='text' class='form__input' placeholder='DeviceId' required> </div> <div class='form__field'> <input type='submit' value='Connect'> </div> </form> <p class='text--center'>SSID not found? <a onclick='showSSID()'>Enter Manually</a> <span class='fontawesome-arrow-right'></span></p> </div> </div> </body> </body> </html> <script> function showSSID(){ document.getElementById('ssidlist').style.display = 'none'; document.getElementById('ssid').style.display = 'block'; } </script>";
        //content += "</p><form method='get' action='setting'><label>SSID: </label><input name='ssid' length=32><input name='pass' length=64><input type='submit'></form>";
         //content += "</html>";
        server.send(200, "text/html", content);  
    });
    server.on("/setting", [this]() {
        String qsid = server.arg("ssid");
        String qpass = server.arg("pass");
        String qid = server.arg("device");
        content ="";
        if (qsid.length() > 0 && qpass.length() > 0) {
          writeCredentials(qsid, qpass, qid);
   
        } else {
          content = "{\"Error\":\"404 not found\"}";
          statusCode = 404;
          printer->println("Sending 404");
        }

        server.send(200, "application/json", content);
        WiFi.disconnect();
        delay(2000);
        EEPROM.end();
        hardReboot();
    });
  } else if (webtype == 0) {
    server.on("/", [this]() {
      IPAddress ip = WiFi.localIP();
      String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
      server.send(200, "application/json", "{\"IP\":\"" + ipStr + "\"}");
    });
    server.on("/cleareeprom", [this]() {
      content = "<!DOCTYPE HTML>\r\n<html>";
      content += "<p>Clearing the EEPROM</p></html>";
      server.send(200, "text/html", content);
      clearEEPROM();
      hardReboot();
    });
  }
  
}
示例#8
0
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);
}
示例#9
0
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;
}
示例#10
0
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);
  }
}
示例#11
0
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);
}
示例#12
0
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);
}
示例#13
0
文件: src.cpp 项目: RitterRBC/Arduino
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);
}
示例#14
0
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();
}
示例#15
0
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);
}
示例#16
0
void handleXML(){
  buildXML();
  delay(10);
  server.send(200,"text/xml",XML);
}
示例#17
0
void handleScan(){
  String body = wifi_helper->GetAPList();
  server.send(200, "application/json", body);
}
示例#18
0
void returnFail(String msg) {
  server.sendHeader("Connection", "close");
  server.sendHeader("Access-Control-Allow-Origin", "*");
  server.send(500, "text/plain", msg + "\r\n");
}
示例#19
0
void get_acc_settings() {
  server.send(200, "text/json", "");
  server.sendContent("[1,1,1]");
}
示例#20
0
void handleNotFound() {
  server.send(404, "text/plain", "404 File not found\n");
}
示例#21
0
void index_body(){
    server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':81/', ['arduino']);connection.onopen = function () {  connection.send('Connect ' + new Date()); }; connection.onerror = function (error) {    console.log('WebSocket Error ', error);};connection.onmessage = function (e) {  console.log('Server: ', e.data);};function sendRGB() {  var r = parseInt(document.getElementById('r').value).toString(16);  var g = parseInt(document.getElementById('g').value).toString(16);  var b = parseInt(document.getElementById('b').value).toString(16);  if(r.length < 2) { r = '0' + r; }   if(g.length < 2) { g = '0' + g; }   if(b.length < 2) { b = '0' + b; }   var rgb = '#'+r+g+b;    console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/></body></html>");
}
示例#22
0
// This a handler we can attach to our server
// Since the server is synchronous, the api is to write responses on the server object
// Here we blink the LED on whilst processing a request
void handleRoot() {
  digitalWrite(led, LED_ON);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, LED_OFF);
}
示例#23
0
void Wifi::begin(Stream &s) {
    _s = &s;
    //USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);

    //USE_SERIAL.setDebugOutput(true);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    int n = WiFi.scanNetworks();
    Serial.println("[SETUP] SCANNING...");
    Serial.println("");
    if (n == 0)
      USE_SERIAL.println("no networks found");
    else
    {
      USE_SERIAL.print(n);
      USE_SERIAL.println(" networks found");
      for (int i = 0; i < n; ++i)
      {
        // Print SSID and RSSI for each network found
        USE_SERIAL.print(i + 1);
        USE_SERIAL.print(": ");
        USE_SERIAL.print(WiFi.SSID(i));
        USE_SERIAL.print(" (");
        USE_SERIAL.print(WiFi.RSSI(i));
        USE_SERIAL.print(")");
        USE_SERIAL.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
        delay(10);
      }
    }
    Serial.println("");

    WiFiMulti.addAP(NETWORKNAME, NETWORKPASS);

    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    USE_SERIAL.print("IP address: ");
    USE_SERIAL.println(WiFi.localIP());
    USE_SERIAL.flush();

    // start webSocket server
    webSocket.begin();
    webSocket.onEvent(webSocketEvent);

    if(MDNS.begin("esp8266")) {
        USE_SERIAL.println("MDNS responder started");
    }

    // handle index
    server.on("/", []() {
        // send index.html
        server.send(200, "text/html", "<html><head><script>var connection = new WebSocket('ws://'+location.hostname+':8899/', ['arduino']);connection.onopen = function () {  connection.send('Connect ' + new Date()); }; connection.onerror = function (error) {    console.log('WebSocket Error ', error);};connection.onmessage = function (e) {  console.log('Server: ', e.data);};function sendRGB() {  var r = parseInt(document.getElementById('r').value).toString(16);  var g = parseInt(document.getElementById('g').value).toString(16);  var b = parseInt(document.getElementById('b').value).toString(16);  if(r.length < 2) { r = '0' + r; }   if(g.length < 2) { g = '0' + g; }   if(b.length < 2) { b = '0' + b; }   var rgb = '#'+r+g+b;    console.log('RGB: ' + rgb); connection.send(rgb); }</script></head><body>LED Control:<br/><br/>R: <input id=\"r\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>G: <input id=\"g\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/>B: <input id=\"b\" type=\"range\" min=\"0\" max=\"255\" step=\"1\" onchange=\"sendRGB();\" /><br/></body></html>");
    });

    server.begin();

    // Add service to MDNS
    MDNS.addService("http", "tcp", 80);
    MDNS.addService("ws", "tcp", 8899);

}
示例#24
0
void handleWebsite(){
  buildWebsite();
  delay(10);
  server.send(200,"text/html",webSite);
}
示例#25
0
void handleRoot(){
  server.send(200, "text/html", ssids);
}
示例#26
0
void handleNotFound() {
  webServer.send(404, "text/plain", "404 - Page Not Found");
}
示例#27
0
void MyFunctionRequestHandler::apiHandler(ESP8266WebServer& server) {
  mpIpDisplay->StopShowingIp();
  //applicationProblems = -1;  //force repaint display in client mode

  // adjust logo brightness (on/off right now)
  if (server.hasArg(F("logo"))) {
    if (server.arg(F("logo")).equals(F("on"))) {
      mpLedstripLogo->setBrightness(255);
    } else if (server.arg(F("logo")).equals(F("default"))) {
       ledsSetLogoDefault();
    } else {
       mpLedstripLogo->setBrightness(0);
    }
  }

  // to quickly set the RGB colors of the logo remotely
  if (server.hasArg(F("logoled"))) {
    byte led = byte(server.arg(F("logoled")).toInt());
    byte r = byte(server.arg(F("r")).toInt());
    byte g = byte(server.arg(F("g")).toInt());
    byte b = byte(server.arg(F("b")).toInt());
    mpLedstripLogo->setPixelColor(led, r, g, b);
  }

  if (server.hasArg(F("top_init"))){
    mpDisplayUpperRing->Init();
  }
  if (server.hasArg(F("top"))){
    String argument = server.arg(F("top"));
    unsigned int i = 0;
    unsigned int ret = 0;
    
    while (i < argument.length())
      i = mpDisplayUpperRing->ParseLedArg(argument, i);
  }
  if (server.hasArg(F("top_bg"))){
    String argument = server.arg(F("top_bg"));
    if (argument.length() == 6)
      mpDisplayUpperRing->SetBackground(argument.substring(2, 4) + argument.substring(0, 2) + argument.substring(4, 6)); 
  }
  if (server.hasArg(F("top_whirl"))){
    String argument = server.arg(F("top_whirl"));
    mpDisplayUpperRing->ParseWhirlArg(argument);
  } 
  if (server.hasArg(F("top_morph"))){
    String argument = server.arg(F("top_morph"));
    mpDisplayUpperRing->ParseMorphArg(argument);
  } 
    
  if (server.hasArg(F("bottom_init"))){
    mpDisplayLowerRing->Init();
  }
  if (server.hasArg(F("bottom"))){
    String argument = server.arg(F("bottom"));
    unsigned int i = 0;
    unsigned int ret = 0;
    
    while (i < argument.length())
      i = mpDisplayLowerRing->ParseLedArg(argument, i);
  }
  if (server.hasArg(F("bottom_bg"))){
    String argument = server.arg(F("bottom_bg"));
    if (argument.length() == 6)
      mpDisplayLowerRing->SetBackground(argument.substring(2, 4) + argument.substring(0, 2) + argument.substring(4, 6)); 
  }
  if (server.hasArg(F("bottom_whirl"))){
    String argument = server.arg(F("bottom_whirl"));
    mpDisplayLowerRing->ParseWhirlArg(argument);
  } 
  if (server.hasArg(F("bottom_morph"))){
    String argument = server.arg(F("bottom_morph"));
    mpDisplayLowerRing->ParseMorphArg(argument);
  } 

  if (server.hasArg(F("dynatrace-environmentid")) && server.hasArg(F("dynatrace-apikey")) && server.hasArg(F("dynatrace-interval"))) {
    if (mDebug) Serial.println(F("Storing Dynatrace SaaS/Managed environment integration settings"));
    mpConfig->enabled = server.hasArg(F("dynatrace-on"));
    mpConfig->dynatraceEnvironmentID = server.arg(F("dynatrace-environmentid"));
    mpConfig->dynatraceApiKey = server.arg(F("dynatrace-apikey"));
    mpConfig->pollingIntervalS = server.arg(F("dynatrace-interval")).toInt();
    mpConfig->SignalChange();
    mpConfig->Write();
    server.sendHeader(F("location"), F("/"));
    server.send(302);
    return;
  }

  if (server.hasArg(F("hostname"))) {
    String newWifiHostname = server.arg(F("hostname"));
    eepromSet(newWifiHostname);
  }

  // note its required to provide both arguments SSID and PWD
  if (server.hasArg(F("ssid")) && server.hasArg(F("pwd"))) {
    String newWifiSSID = server.arg(F("ssid"));
    String newWifiPwd = server.arg(F("pwd"));

    // if SSID is given, also update wifi credentials
    if (newWifiSSID.length()) {
      WiFi.mode(WIFI_STA);
      WiFi.begin(newWifiSSID.c_str(), newWifiPwd.c_str() );
    }

    if (mDebug) {
      Serial.println(String(F("New Wifi settings: ")) + newWifiSSID + F(" / ") + newWifiPwd);
      Serial.println(String(F("Restarting....")));
      Serial.flush();
    }

    httpReboot(server, String(F("New WIFI settings accepted. Mac address: ")) + WiFi.macAddress() + String(F("<p/>")));

  }

 
  server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store"));
  server.send(200);
}
示例#28
0
void Threm::start() {
	_thremContext->isStarted = true;

#ifdef LOG
	LOG << "Threm::start" << endl;
	LOG << "Free heap " << ESP.getFreeHeap() << endl;
#endif

	spiffsOk = SPIFFS.begin();

	if (!spiffsOk) {
#ifdef LOG
		LOG << "SPIFFS failed" << endl;
#endif
	}

	ESP8266WebServer* server = _thremContext->getServer();

	IThremPlugin* plugin;
	PluginMeta* meta;

	for (int i = 0; i < _plugins->size(); i++) {
		plugin = _plugins->get(i);
		bool canEnable = true;
		int pluginId = plugin->getUniqueId();
		{
			String state = getJsonStateFor(pluginId);
			yield();

			StaticJsonBuffer<JSON_BUFFER_SIZE> jsonBuffer;
			JsonObject& root = jsonBuffer.parseObject(state);
			if (!root.success()) {
#ifdef LOG
				LOG << "Failed to parse config for " << String(plugin->getUniqueId()) << endl;
#endif
			}
			else {
				bool isDisabled = root["off"];
				if (isDisabled) {
					canEnable = false;
				}
			}

			if (canEnable) {
				canEnable = plugin->init(_thremContext, root);
			}
		}



		meta = _pluginMeta->get(i);
		meta->isEnabled = canEnable;
#ifdef DEBUG
		DEBUG << String(plugin->getName()) << " enabled=" << canEnable << endl;
#endif
		_pluginMeta->set(i, meta);

		yield();
	}
#ifdef DEBUG
	DEBUG << "Plugins declared: " << _plugins->size() << endl;
#endif

#ifdef LOG
	LOG << getJsonState() << endl;
#endif

#ifdef DEBUG
	DEBUG << "default callbacks setup." << endl;
#endif

	server->onNotFound([=](){
		IThremPlugin*plugin;
		PluginMeta* meta;

		String uri = server->uri();
		for (int i = 0; i < _plugins->size(); i++) {
			plugin = _plugins->get(i);
			meta = _pluginMeta->get(i);
			if (meta->isEnabled) {
				if (plugin->handleNotFound(_thremContext, uri)) {
#ifdef LOG
					LOG << "NotFound handled by: " << plugin->getName() << endl;
#endif
					return;
				}
			}
		}

		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->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
		server->sendHeader("Pragma", "no-cache");
		server->sendHeader("Expires", "-1");
		server->send(404, "text/plain", message);
	});
#ifdef DEBUG
	DEBUG << "Starting webserver." << endl;
#endif
	server->begin();
#ifdef DEBUG
	DEBUG << "Web server started." << endl;
#endif
	}
示例#29
0
void handle_root()
{
  webString="Switch state: "+String((int)state);   // Arduino has a hard time with float to string
  server.send(200, "text/plain", webString);            // send to someones browser when asked
  server.send(200, "text/plain", "open /on or /off to control outlet");
}
示例#30
-1
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");
}