/* https://github.com/0x1d/esp8266-laser 0x1d, FrYakaTKoP */ #include #include #include #include #include #include #include /* some hard coded config, change if needed */ // Set how long the esp should try to connect to a network before starting it's own AP unsigned int wifiTimeout = 15000; //ms // Hardcoded Soft AP network parameters char *ssidAP = "laserAp"; IPAddress apIP(192, 168, 4, 1); IPAddress netMsk(255, 255, 255, 0); // this is sent to server if invalid request const char *metaRefreshStr = "

redirecting...

"; /* hostname for mDNS. Should work at least on windows. Try http://esplaser.local */ const char *myHostname = "esplaser"; // espsoftwareserial // SoftwareSerial(int receivePin, int transmitPin, bool inverse_logic = false, unsigned int buffSize = 64); SoftwareSerial laserSerial(14, 12, false, 256); /* End of hard coded config */ String ssid = ""; String password = ""; int apMode = 1; // default value, will be overwriten with config from file int _apMode = 0; // runtime apMode // [0] laser, [1] m1, [2] m2, [3] m3 byte lmValues[4] = {0, 0, 0, 0}; unsigned long previousMillis = 0; // Web server ESP8266WebServer server(80); bool hFileRead(String path) { //Serial.println("handleFileRead: " + path); if (path.endsWith("/")) path += "index.html"; String contentType = getContentType(path); String pathWithGz = path + ".gz"; if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { if (SPIFFS.exists(pathWithGz)) path += ".gz"; File file = SPIFFS.open(path, "r"); size_t sent = server.streamFile(file, contentType); file.close(); return true; } return false; } String getContentType(String filename) { if (server.hasArg("download")) return "application/octet-stream"; else if (filename.endsWith(".htm")) return "text/html"; else if (filename.endsWith(".html")) return "text/html"; else if (filename.endsWith(".ini")) return "text/plain"; else if (filename.endsWith(".css")) return "text/css"; else if (filename.endsWith(".js")) return "application/javascript"; else if (filename.endsWith(".png")) return "image/png"; else if (filename.endsWith(".gif")) return "image/gif"; else if (filename.endsWith(".jpg")) return "image/jpeg"; else if (filename.endsWith(".ico")) return "image/x-icon"; else if (filename.endsWith(".xml")) return "text/xml"; else if (filename.endsWith(".pdf")) return "application/x-pdf"; else if (filename.endsWith(".zip")) return "application/x-zip"; else if (filename.endsWith(".gz")) return "application/x-gzip"; return "text/plain"; } void hFileList() { String responseBuffer = String(); StaticJsonBuffer<500> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonArray& files = root.createNestedArray("files"); Dir dir = SPIFFS.openDir("/"); while (dir.next()) { File entry = dir.openFile("r"); files.add(String(entry.name())); entry.close(); } root.prettyPrintTo(responseBuffer); server.send(200, "text/json", responseBuffer); jsonBuffer.clear(); responseBuffer = String(); } void hReadSpiro() { String responseBuffer = String(); StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonObject& data = root.createNestedObject("spirograph"); data["laser"] = (String)lmValues[0]; data["motor1"] = (String)lmValues[1]; data["motor2"] = (String)lmValues[2]; data["motor3"] = (String)lmValues[3]; root.prettyPrintTo(responseBuffer); server.send(200, "text/json", responseBuffer); jsonBuffer.clear(); responseBuffer = String(); } void hWriteSpiro() { String responseBuffer = String(); StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonObject& data = root.createNestedObject("wificonfig"); if (server.hasArg("laser") ) { lmValues[0] = server.arg("laser").toInt(); data["laser"] = (String)lmValues[0]; String msg = "AT SLV "; msg += (String)lmValues[0]; laserSerial.println(msg); delay(20); } if (server.hasArg("motor1") ) { lmValues[1] = server.arg("motor1").toInt(); data["motor1"] = (String)lmValues[1]; String msg = "AT SMS 1 "; msg += (String)lmValues[1]; laserSerial.println(msg); delay(20); } if (server.hasArg("motor2") ) { lmValues[2] = server.arg("motor2").toInt(); data["motor2"] = (String)lmValues[2]; String msg = "AT SMS 2 "; msg += (String)lmValues[2]; laserSerial.println(msg); delay(20); } if (server.hasArg("motor3") ) { lmValues[3] = server.arg("motor3").toInt(); data["motor3"] = (String)lmValues[3]; String msg = "AT SMS 3 "; msg += (String)lmValues[3]; laserSerial.println(msg); delay(20); } root.prettyPrintTo(responseBuffer); server.send(200, "text/json", responseBuffer); jsonBuffer.clear(); responseBuffer = String(); } void hReadWifi() { // Serial.println("hReadWifi"); String responseBuffer = String(); StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonObject& data = root.createNestedObject("wificonfig"); data["apMode"] = apMode; data["SSID"] = ssid; data["Password"] = "***"; //password; //data["save"] = "false"; //data["apply"] = "false"; root.prettyPrintTo(responseBuffer); //root.prettyPrintTo(Serial); server.send(200, "text/json", responseBuffer); jsonBuffer.clear(); responseBuffer = String(); } void hWriteWifi() { // Serial.println("hWriteWifi"); String responseBuffer = String(); boolean save = false; boolean apply = false; StaticJsonBuffer<200> jsonBuffer; JsonObject& root = jsonBuffer.createObject(); JsonObject& data = root.createNestedObject("wificonfig"); if (server.hasArg("apMode") ) { apMode = server.arg("apMode").toInt(); data["apMode"] = apMode; } if (server.hasArg("SSID") ) { ssid = server.arg("SSID"); data["SSID"] = ssid; } if (server.hasArg("password") ) { password = server.arg("password"); data["Password"] = "***"; //password; } if (server.arg("save") == "true") { save = true; data["save"] = "true"; } if (server.arg("apply") == "true") { apply = true; data["apply"] = "true"; } root.prettyPrintTo(responseBuffer); //root.prettyPrintTo(Serial); server.send(200, "text/json", responseBuffer); if (save) { saveConfigFile(); } if (apply) { setupWifi(); } jsonBuffer.clear(); responseBuffer = String(); } bool saveConfigFile() { StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.createObject(); json["apMode"] = apMode; json["SSID"] = ssid; json["Password"] = password; File configFile = SPIFFS.open("/wifi.json", "w"); if (!configFile) { //Serial.println("Failed to open config file for writing"); return false; } json.printTo(configFile); return true; } void hSaveConf() { bool success = saveConfigFile(); if (success) { server.send(200, "text/plain", "saved config to file,
reset or /resetwifi to apply settings"); } else { server.send(500, "text/plain", "error saving file"); } } boolean readConfigFile() { Serial.println("Reading wifi.json"); File configFile = SPIFFS.open("/wifi.json", "r"); if (!configFile) { Serial.println("Failed to open config file"); return false; } size_t size = configFile.size(); if (size > 1024) { Serial.println("Config file size is too large"); return false; } // Allocate a buffer to store contents of the file. std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); StaticJsonBuffer<200> jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); if (!json.success()) { Serial.println("Failed to parse config file"); return false; } apMode = json["apMode"]; apMode = apMode; const char* tSsid = json["SSID"]; const char* tPwd = json["Password"]; ssid = tSsid; password = tPwd; Serial.print("SSID: "); Serial.println(ssid); Serial.print("PW: "); Serial.println("***"); //Serial.println(password); return true; } void setupWifi() { WiFi.disconnect(); delay(100); if (!connectWifi()) { Serial.println("connect failed, start SoftAP"); _apMode = 1; // fallback to AP mode connectWifi(); } } boolean connectWifi() { Serial.print("connectWifi apMode="); Serial.println(apMode); if (_apMode == 0) { Serial.print("Connecting to "); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid.c_str(), password.c_str()); previousMillis = millis(); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); if (millis() - previousMillis >= wifiTimeout) { Serial.println(""); Serial.println("connection timedout"); return false; } } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); return true; } else { Serial.printf("Starting SoftAP %s\n", ssidAP); WiFi.mode(WIFI_AP); WiFi.softAP(ssidAP); Serial.print("SoftAP started! IP address: "); Serial.println ( WiFi.softAPIP() ); return true; } } void setup(void) { laserSerial.begin(9600); laserSerial.flush(); Serial.begin(115200); Serial.print("\n"); SPIFFS.begin(); // { // Dir dir = SPIFFS.openDir("/"); // while (dir.next()) { // String fileName = dir.fileName(); // size_t fileSize = dir.fileSize(); // Serial.printf("FS File: %s\n", fileName.c_str()); // } // Serial.printf("\n"); // } if (!readConfigFile()) { Serial.println("reading wifi config failed, start SoftAP"); _apMode = 1; } delay(100); setupWifi(); // Setup MDNS responder if (!MDNS.begin(myHostname)) { Serial.println("Error setting up MDNS responder!"); } else { Serial.println("mDNS responder started"); // Add service to MDNS-SD MDNS.addService("http", "tcp", 80); } //SERVER INIT //list directory server.on("/files", HTTP_GET, hFileList); server.on("/files", HTTP_POST, []() { server.send(400, "text/plain", "400 Bad Request"); }); server.on("/saveconf", HTTP_GET, []() { server.send(400, "text/plain", "400 Bad Request"); }); server.on("/saveconf", HTTP_POST, hSaveConf); server.on("/resetwifi", HTTP_GET, []() { server.send(400, "text/plain", "400 Bad Request"); }); server.on("/resetwifi", HTTP_POST, setupWifi); server.on("/wificonfig", HTTP_GET, hReadWifi); server.on("/wificonfig", HTTP_POST, hWriteWifi); server.on("/spirograph", HTTP_GET, hReadSpiro); server.on("/spirograph", HTTP_POST, hWriteSpiro); server.on("/heap", HTTP_GET, []() { String json = "{"; json += "\"heap\":" + String(ESP.getFreeHeap()); json += "}"; server.send(200, "text/json", json); json = String(); }); server.on("/heap", HTTP_POST, []() { server.send(400, "text/plain", "400 Bad Request"); }); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); } void handleNotFound() { String uri = server.uri(); //Serial.print("unhandled uri:"); //Serial.println(uri); if (uri.substring(0, 12) == "/wifi.json") { server.send(403, "text/plain", "Forbidden"); return; } if (!hFileRead(server.uri())) { server.send(404, "text/html", metaRefreshStr); // server.send(302, "text/plain", "blub"); } } void loop(void) { server.handleClient(); }