Exemplo n.º 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();
}
Exemplo n.º 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);
}
Exemplo n.º 3
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);
}
Exemplo n.º 4
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);
}
Exemplo n.º 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();
}
Exemplo n.º 6
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);
}
Exemplo n.º 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();
    });
  }
  
}
Exemplo n.º 8
0
// 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();
}
Exemplo n.º 9
0
// 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();
}
Exemplo n.º 10
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
	}
Exemplo n.º 11
0
void handleErase(){
  if(server.arg("erase")=="true"){
    eraseConfig();
  }
}
Exemplo n.º 12
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);
}
Exemplo n.º 13
0
bool MyFunctionRequestHandler::handle(ESP8266WebServer& server, HTTPMethod requestMethod, String requestUri){
  
  server.client().setNoDelay(true);
  requestUri.toLowerCase();
  
  Serial.println(String(F("handle(")) + String(requestMethod) + String(F(", ")) + requestUri + String(F(")")));
   
  if (requestMethod == HTTP_GET){

    if (requestUri.equals(F("/")) || requestUri.equals(F("/index.html"))){
      server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store"));
      server.sendHeader(F("Content-Encoding"), F("gzip"));
      server.send_P(200, String(F("text/html")).c_str(), index_html_gz, sizeof(index_html_gz));
      return true;
    }
    if (requestUri.equals(F("/font.woff"))){
      server.send_P(200, String(F("text/html")).c_str(), font_woff, sizeof(font_woff));
      return true;
    }
    /*if (handleStatic(server, requestUri, F("/"), F("/index_comb.html.gz"), F("text/html"), false)) return true;
    if (handleStatic(server, requestUri, F("/"), F("/index.html"), F("text/html"), false)) return true;
    if (handleStatic(server, requestUri, F("/index.html"), F("/index_comb.html.gz"), F("text/html"), false)) return true;
    if (handleStatic(server, requestUri, F("/index.html"), F("/index.html"), F("text/html"), false)) return true;
    if (handleStatic(server, requestUri, F("/phonon.min.css"), F("/phonon.min.css"), F("text/css"), true)) return true;
    if (handleStatic(server, requestUri, F("/phonon.min.js"), F("/phonon.min.js"), F("application/javascript"), true)) return true;
    if (handleStatic(server, requestUri, F("/forms.min.css"), F("/forms.min.css"), F("text/css"), true)) return true;
    if (handleStatic(server, requestUri, F("/forms.min.js"), F("/forms.min.js"), F("application/javascript"), true)) return true;
    if (handleStatic(server, requestUri, F("/icons.min.css"), F("/icons.min.css"), F("text/css"), true)) return true;
    if (handleStatic(server, requestUri, F("/lists.min.css"), F("/lists.min.css"), F("text/css"), true)) return true;
    if (handleStatic(server, requestUri, F("/phonon-base.min.css"), F("/phonon-base.min.css"), F("text/css"), true)) return true;
    if (handleStatic(server, requestUri, F("/phonon-core.min.js"), F("/phonon-core.min.js"), F("application/javascript"), true)) return true;
    if (handleStatic(server, requestUri, F("/font.woff"), F("/font.woff"), F("application/font.woff"), true)) return true;
    if (handleStatic(server, requestUri, F("/font.eot"), F("/font.eot"), F("application/font.eot"), true)) return true;
    if (handleStatic(server, requestUri, F("/font.svg"), F("/font.svg"), F("application/font.svg"), true)) return true;
    if (handleStatic(server, requestUri, F("/font.ttf"), F("/font.ttf"), F("application/font.ttf"), true)) return true;
    */
  
    if (requestUri.startsWith(F("/api"))){
      apiHandler(server);
      return true;
    }
    if (requestUri.startsWith(F("/info"))){
      infoHandler(server);
      return true;
    }
    if (requestUri.startsWith(F("/dtintinfo"))){
      dtIntegrationHandler(server);
      return true;
    }
  }
  else if (requestMethod == HTTP_POST){
    if (requestUri.startsWith(F("/update"))){

      StreamString error;
      if (Update.hasError()) {
        Update.printError(error);
      }
      if (mbRebootRequired)
        httpReboot(server, (Update.hasError()) ? error : String(F("Upload succeeded! ")) + String(miUploadSize) + String(F(" bytes transferred<p>")));
      else{
         server.sendHeader(F("location"), F("/"));
         server.send(302);
         return true;
      }
    }
    
    if (requestUri.equals(F("/dynatrace"))){
      dynatracePostHandler(server);
      return true;
    }
  }
  
  //Now we really need to respond with 404
  String message = F("File Not Found\n\n");
  message += F("URI: ");
  message += server.uri();
  message += F("\nMethod: ");
  message += (server.method() == HTTP_GET ) ? F("GET") : F("POST");
  message += F("\nArguments: ");
  message += server.args();
  message += F("\n");

  for ( uint8_t i = 0; i < server.args(); i++ ) {
    message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  }
  server.sendHeader(F("cache-control"), F("private, max-age=0, no-cache, no-store"));
  server.send (404, F("text/plain"), message);
  
  return true;
}