Web.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #include "Web.h"
  2. WebServer server(80);
  3. Web::Web()
  4. {
  5. }
  6. void Web::main()
  7. {
  8. //Serial.println("Running the shits");
  9. // Notify if client has connected to the update server
  10. int current_sta = WiFi.softAPgetStationNum();
  11. if (current_sta < this->num_sta)
  12. {
  13. this->num_sta = current_sta;
  14. Serial.print("Update server: Client disconnected -> ");
  15. Serial.println(this->num_sta);
  16. }
  17. else if (current_sta > this->num_sta)
  18. {
  19. this->num_sta = current_sta;
  20. Serial.print("Update server: Client connected -> ");
  21. Serial.println(this->num_sta);
  22. }
  23. server.handleClient();
  24. delay(1);
  25. }
  26. void Web::setupOTAupdate()
  27. {
  28. Serial.println("Configuring update server...");
  29. // Start WiFi AP
  30. WiFi.softAP(ssid, password);
  31. Serial.println("");
  32. Serial.print("IP address: ");
  33. Serial.println(WiFi.softAPIP());
  34. /*use mdns for host name resolution*/
  35. /*
  36. if (!MDNS.begin(host)) { //http://esp32.local
  37. Serial.println("Error setting up MDNS responder!");
  38. while (1) {
  39. delay(1000);
  40. }
  41. }
  42. Serial.println("mDNS responder started");
  43. */
  44. /*return index page which is stored in serverIndex */
  45. server.on("/", HTTP_GET, [this]() {
  46. server.sendHeader("Connection", "close");
  47. server.send(200, "text/html", loginIndex);
  48. });
  49. server.on("/serverIndex", HTTP_GET, [this]() {
  50. server.sendHeader("Connection", "close");
  51. server.send(200, "text/html", serverIndex);
  52. });
  53. /*handling uploading firmware file */
  54. server.on("/update", HTTP_POST, [this]() {
  55. server.sendHeader("Connection", "close");
  56. server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
  57. ESP.restart();
  58. }, [this]() {
  59. HTTPUpload& upload = server.upload();
  60. if (upload.status == UPLOAD_FILE_START) {
  61. Serial.printf("Update: %s\n", upload.filename.c_str());
  62. if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
  63. Update.printError(Serial);
  64. }
  65. } else if (upload.status == UPLOAD_FILE_WRITE) {
  66. /* flashing firmware to ESP*/
  67. if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
  68. Update.printError(Serial);
  69. }
  70. } else if (upload.status == UPLOAD_FILE_END) {
  71. if (Update.end(true)) { //true to set the size to the current progress
  72. Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
  73. } else {
  74. Update.printError(Serial);
  75. }
  76. }
  77. });
  78. server.begin();
  79. Serial.println("Completed update server setup");
  80. }