firtel

WiFi Joystick

Jan 27th, 2022 (edited)
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 39.93 KB | None | 0 0
  1. //ESP-WROOM-02 WiFi Joystick WebSocket版
  2. //ESPAsyncWebServer,ESPAsyncTCP Library needed
  3. //
  4. //ESP8266 Boards v2.7.4推奨(v3ではWiFiセーブバグあるため…
  5. //CPU 80Mhz,Crystal 26Mhz
  6. //Flash 4MB(FS3MB
  7. //Flash 40Mhz
  8. //Reset no dtr
  9.  
  10. //ESP32 v2.0.0
  11. //Library
  12. //AsyncTCP
  13. //https://github.com/me-no-dev/AsyncTCP/archive/master.zip
  14. //ESPAsyncWebServer
  15. //https://github.com/me-no-dev/ESPAsyncWebServer/archive/master.zip
  16.  
  17. //RGB LED
  18. //FastLED Library
  19.  
  20. #ifdef ESP32
  21. #include <WiFi.h>
  22. #include <AsyncTCP.h>
  23. #include <ESPmDNS.h>
  24. #elif defined(ESP8266)
  25. #include <ESP8266WiFi.h>
  26. #include <ESPAsyncTCP.h>
  27. #include <ESP8266mDNS.h>
  28. #endif
  29. #include <ESPAsyncWebServer.h>
  30.  
  31.  
  32. #define LED_BUILTIN 13
  33.  
  34. //#define debug//コメントを外すとデバッグメッセージをシリアルに流す
  35. //#define RGBLED
  36.  
  37. #ifdef RGBLED
  38. #include <FastLED.h>
  39. #define NUM_LEDS 1
  40. #define DATA_PIN 27
  41. CRGB leds[NUM_LEDS];
  42. #endif
  43.  
  44. AsyncWebServer server(80);
  45. AsyncWebSocket ws("/ws");
  46.  
  47. int8_t x = 0;
  48. int8_t y = 0;
  49.  
  50. //gzip compressed arry
  51. //https://www.mischianti.org/online-converter-file-to-cpp-gzip-byte-array-3/
  52. //File: joystick.html.gz, Size: 1189
  53. #define joystick_html_gz_len 1189
  54. const uint8_t joystick_html_gz[] PROGMEM = {  
  55. 0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x9D, 0x56, 0x4D, 0x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0xAA, 0x60, 0x4A,
  89. 0x67, 0x64, 0x48, 0x5E, 0x4D, 0xCB, 0x7E, 0x14, 0x3D, 0xBD, 0x99, 0x32, 0x9E, 0x88, 0x69, 0x98,
  90. 0x89, 0xD8, 0x48, 0x24, 0x4C, 0x45, 0xA9, 0xF4, 0x08, 0xB8, 0x8D, 0xA6, 0xE5, 0xAB, 0x83, 0xD6,
  91. 0x0F, 0x37, 0xAC, 0x14, 0xF1, 0x15, 0x28, 0x63, 0x69, 0x7C, 0x70, 0xA3, 0x8F, 0x6B, 0x94, 0xF1,
  92. 0x09, 0x2B, 0x71, 0x42, 0x80, 0xF4, 0xBD, 0x4C, 0xD0, 0xC4, 0xEB, 0x12, 0xC1, 0x4F, 0x70, 0xD1,
  93. 0x31, 0xD8, 0xCB, 0x8A, 0xC7, 0x3A, 0x30, 0xC1, 0xB9, 0xA0, 0xBE, 0x81, 0xF1, 0x99, 0x09, 0xE3,
  94. 0x77, 0xB4, 0xD6, 0x08, 0xFE, 0x9A, 0x36, 0xB1, 0x80, 0x89, 0xEF, 0x9D, 0xCB, 0x19, 0x4A, 0x87,
  95. 0x28, 0x41, 0x44, 0x01, 0x1C, 0x4F, 0xC3, 0xC2, 0x41, 0xE3, 0x38, 0x98, 0x48, 0x61, 0x18, 0x7A,
  96. 0x36, 0x36, 0x59, 0xD6, 0x85, 0x1D, 0x71, 0x98, 0x2E, 0xF1, 0x7E, 0xD3, 0xE9, 0x16, 0x30, 0x14,
  97. 0xDC, 0xC4, 0xC6, 0xDF, 0x10, 0x0B, 0xFD, 0xB2, 0x30, 0xBA, 0xDD, 0x84, 0xC4, 0x99, 0x28, 0xA1,
  98. 0x81, 0xBC, 0xD0, 0xEB, 0x1D, 0x98, 0x1C, 0xCA, 0x92, 0x4E, 0xC0, 0x60, 0x4E, 0xED, 0xFA, 0x80,
  99. 0x44, 0x11, 0x19, 0x04, 0x01, 0x41, 0x6A, 0x88, 0x4A, 0x59, 0x49, 0xF4, 0x51, 0xD3, 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25, 0x1F, 0x90, 0x60, 0xBF, 0xC1, 0xB7, 0xD5,
  122. 0x2C, 0x8F, 0x13, 0xD6, 0xE5, 0x0D, 0xC6, 0x87, 0x5F, 0x35, 0x9F, 0x34, 0xFD, 0x41, 0x34, 0x3E,
  123. 0x24, 0x9E, 0x45, 0x3B, 0x7B, 0xC4, 0x23, 0x17, 0x7D, 0x6F, 0x4F, 0x57, 0xB4, 0x62, 0x1A, 0x59,
  124. 0xD3, 0xA8, 0x09, 0xCA, 0x2E, 0x89, 0x6F, 0x89, 0x7A, 0x6F, 0xD8, 0xD0, 0xFA, 0xE6, 0x8D, 0xE5,
  125. 0xA9, 0x31, 0x8C, 0x48, 0x4B, 0xC9, 0x8E, 0xA3, 0xE5, 0x5E, 0xF7, 0x5D, 0x93, 0x61, 0xCF, 0xED,
  126. 0xCE, 0xEC, 0x72, 0xD4, 0xF6, 0x67, 0x0F, 0x9A, 0xD3, 0xEE, 0x95, 0x46, 0x1D, 0x2C, 0x4D, 0x23,
  127. 0x6B, 0x6A, 0xEA, 0xB8, 0xED, 0x92, 0xFD, 0xE8, 0xA3, 0x1E, 0xB6, 0xBB, 0xDF, 0x8C, 0xA9, 0x95,
  128. 0xFB, 0x0E, 0x6F, 0xD2, 0xE6, 0x1B, 0x00, 0xBF, 0x0A, 0xF4, 0xA7, 0xEF, 0x3F, 0xB9, 0xA7, 0x0A,
  129. 0x67, 0x01, 0x0B, 0x00, 0x00
  130. };
  131. //File: virtualjoystick.js.gz, Size: 2945
  132. #define virtualjoystick_js_gz_len 2945"text/plain", "Not found");
  133. }
  134.  
  135. void SoftAPmode(){
  136.   WiFi.mode(WIFI_AP);
  137.   WiFi.softAP("ESP-WROOM-02");
  138.   WiFi.begin();
  139. }
  140.  
  141. void setup() {
  142.   pinMode(LED_BUILTIN, OUTPUT);
  143.   pinMode(0, INPUT_PULLUP);//書き込みボタンをボタンとして使えるように。
  144.   digitalWrite(LED_BUILTIN, LOW);
  145.   Serial.begin(9600);
  146.   Serial.println("");
  147.  
  148.   #ifdef RGBLED
  149.   FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  150.   leds[0] = CRGB::Green;
  151.   FastLED.show();
  152.   #endif
  153.  
  154.   boolean SoftAP = false;
  155.  
  156.   if(WiFi.SSID() != NULL){
  157.     WiFi.mode(WIFI_STA);
  158.     WiFi.begin();
  159.   }else{
  160.     SoftAP = true;
  161.   }
  162.  
  163.   unsigned int cnt = 0;
  164.   while (WiFi.status() != WL_CONNECTED) {
  165.     cnt++;
  166.     delay(100);
  167.     led_toggle();//LED点滅
  168.     //Wifiアクセスポイントに接続できない場合Soft APモードに変更する
  169.     if(cnt >= 100 || digitalRead(0) == LOW || SoftAP == true){//接続トライ100カウント以上もしくは書き込みボタンを押すとSoft APモードに変更
  170.       SoftAP = true;
  171.       digitalWrite(LED_BUILTIN, LOW);
  172.       SoftAPmode();
  173.       //dnsServer.start(53, "*", WiFi.softAPIP());
  174.       #ifdef ESP8266
  175.       WiFi.setSleepMode(WIFI_NONE_SLEEP);
  176.       #endif
  177.       break;//Soft APにしてもbreakしないと抜けられない
  178.     }
  179.  
  180.     #ifdef debug
  181.     Serial.print(".");
  182.     #endif
  183.   }
  184.   /*if (WiFi.waitForConnectResult() != WL_CONNECTED) {
  185.     Serial.printf("WiFi Failed!\n");
  186.     return;
  187.   }
  188.   */
  189.   #ifdef debug
  190.   Serial.println("");
  191.   Serial.println("WiFi connected");  
  192.   Serial.println("IP address: ");
  193.   if(SoftAP == false){
  194.     Serial.println(WiFi.localIP());
  195.   }else{
  196.     Serial.println(WiFi.softAPIP());
  197.   }
  198.   #endif
  199.  
  200.   //mDNS初期化
  201.   if (!MDNS.begin("esp")) {
  202.     #ifdef debug
  203.     Serial.println("Error setting up MDNS responder!");
  204.     #endif
  205.   }
  206.   MDNS.addService("http", "tcp", 80);
  207.  
  208.   initWebSocket();
  209.  
  210.   server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
  211.     AsyncWebServerResponse *response = request->beginResponse_P(200, "text/html", joystick_html_gz, joystick_html_gz_len);
  212.     response->addHeader(F("Content-Encoding"), F("gzip"));
  213.     request->send(response);
  214.   });
  215.   server.on("/virtualjoystick.js", HTTP_GET, [](AsyncWebServerRequest *request){
  216.     AsyncWebServerResponse *response = request->beginResponse_P(200, "text/javascript", virtualjoystick_js_gz, virtualjoystick_js_gz_len);
  217.     response->addHeader(F("Content-Encoding"), F("gzip"));
  218.     request->send(response);
  219.   });
  220.   wifiMgr();
  221.   //server.on("/update", HTTP_GET, [](AsyncWebServerRequest *request){handleUpdate(request);});
  222.   server.on("/doUpdate", HTTP_POST,
  223.     [](AsyncWebServerRequest *request) {},
  224.     [](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data,
  225.                   size_t len, bool final) {handleDoUpdate(request, filename, index, data, len, final);}
  226.   );
  227.   server.onNotFound(notFound);
  228.   server.begin();
  229.  
  230. }
  231.  
  232. void loop() {
  233.   #ifdef ESP8266
  234.   MDNS.update();
  235.   #endif
  236.   ws.cleanupClients();
  237.   if(Serial.available() > 0){
  238.     char serData = Serial.read();
  239.     if(serData == 'c'){
  240.       led_toggle();
  241.       Serial.print("c");
  242.       Serial.write(x);
  243.       Serial.write(y);
  244.     }else if(serData == '&'){
  245.       led_toggle();
  246.       ws.textAll(Serial.readStringUntil(';'));
  247.     }else{
  248.       Serial.flush();
  249.       while(!Serial.available()){
  250.         Serial.read();
  251.       }
  252.     }
  253.   }
  254. }
  255.  
  256. void led_toggle(){
  257.   static boolean ledtoggle = false;
  258.   ledtoggle = !ledtoggle;
  259.   digitalWrite(LED_BUILTIN,ledtoggle);
  260.   #ifdef RGBLED
  261.   if(ledtoggle == false){
  262.     leds[0] = CRGB::Green;
  263.     FastLED.show();
  264.   }else{
  265.     leds[0] = CRGB::Black;
  266.     FastLED.show();
  267.   }
  268.   #endif
  269. }
  270.  
  271. //WebSocket
  272. /*void notifyClients() {
  273.   ws.textAll(String(ledState));
  274. }*/
  275.  
  276. void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
  277.   AwsFrameInfo *info = (AwsFrameInfo*)arg;
  278.   if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
  279.     data[len] = 0;
  280.     /*if (strcmp((char*)data, "toggle") == 0) {
  281.       ledState = !ledState;
  282.       notifyClients();
  283.     }
  284.     */
  285.     //Serial.println((char*)data);
  286.     uint8_t ypos = 0;
  287.     char strx[4];
  288.     char stry[4];
  289.     if(data[0] == 'x'){
  290.       for (int i=2; i <= len; i++){
  291.         if(data[i] == 'y'){
  292.           ypos = i + 2;
  293.           break;
  294.         }else{
  295.           strx[i-2] = data[i];
  296.         }
  297.       }
  298.       for (int i=ypos; i <= len; i++){
  299.         stry[i-ypos] = data[i];
  300.       }
  301.       //Serial.println(ypos);
  302.       x = atoi(strx);
  303.       y = atoi(stry);
  304.       #ifdef debug
  305.       Serial.print("x:");
  306.       Serial.print(x);
  307.       Serial.print(",y:");
  308.       Serial.println(y);
  309.       #endif
  310.     }
  311.   }
  312. }
  313.  
  314. void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
  315.              void *arg, uint8_t *data, size_t len) {
  316.     switch (type) {
  317.       case WS_EVT_CONNECT:
  318.         #ifdef debug
  319.         Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
  320.         #endif
  321.         break;
  322.       case WS_EVT_DISCONNECT:
  323.         #ifdef debug
  324.         Serial.printf("WebSocket client #%u disconnected\n", client->id());
  325.         #endif
  326.         x = 0;
  327.         y = 0;
  328.         break;
  329.       case WS_EVT_DATA:
  330.         handleWebSocketMessage(arg, data, len);
  331.         break;
  332.       case WS_EVT_PONG:
  333.       case WS_EVT_ERROR:
  334.         break;
  335.   }
  336. }
  337.  
  338. void initWebSocket() {
  339.   ws.onEvent(onEvent);
  340.   server.addHandler(&ws);
  341. }
  342.  
  343. //以下Wifi設定画面用
  344.  
  345. #define SSIDLIMIT 30
  346. String ssid_rssi_str[SSIDLIMIT];
  347. String ssid_str[SSIDLIMIT];
  348.  
  349. String ssid;
  350. String passwd;
  351.  
  352. String maskpasswd(String passwd){
  353. String maskpasswd = "";
  354.  
  355.   for (int i=0; i<passwd.length(); i++) maskpasswd = maskpasswd + "*";
  356.   if (passwd.length() == 0) maskpasswd = "(null)";
  357.  
  358.   return maskpasswd;
  359. }
  360.  
  361. String Headder_str() {
  362.   String html = "";
  363.   html += "<!DOCTYPE html><html><head>";
  364.   html += "<meta name='viewport' content='width=device-width, initial-scale=1.3'>";
  365.   html += "<meta http-equiv='Pragma' content='no-cache'>";
  366.   html += "<meta http-equiv='Cache-Control' content='no-cache'></head>";
  367.   html += "<meta http-equiv='Expires' content='0'>";
  368.   html += "<style>";
  369.   html += "a:link, a:visited { background-color: #009900; color: white; padding: 5px 15px;";
  370.   html += "text-align: center; text-decoration: none;  display: inline-block;}";
  371.   html += "a:hover, a:active { background-color: green;}";
  372.   html += "bo32{ background-color: #EEEEEE;}";
  373.   html += "input[type=button], input[type=submit], input[type=reset] {";
  374.   html += "background-color: #000099;  border: none;  color: white;  padding: 5px 20px;";
  375.   html += "text-decoration: none;  margin: 4px 2px;";
  376.   html += "</style>";
  377.   html += "<body>";
  378.   html += "<h2>Setup</h2>";
  379.   return html;
  380. }
  381.  
  382. void wifiMgr() {
  383.  
  384.   server.on("/setup", HTTP_GET, [] (AsyncWebServerRequest *request) {
  385.     String html = Headder_str();
  386.     html += "<a href='/wifiinput'>WIFI setup</a>";
  387.     html += "<hr><h3>Current Settings</h3>";
  388.     html += "SSID: " + WiFi.SSID() + "<br>";
  389.     html += "passwd: " + maskpasswd(passwd) + "<br>";
  390.     html += "<hr><h3>Firmware Update</h3>";
  391.     html += "<form method='POST' action='/doUpdate' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
  392.     html += "<hr><p><center><a href='/reboot'>Reboot</a></center>";
  393.     html += "</body></html>";
  394.     request->send(200, "text/html", html);
  395.   });
  396.   server.on("/wifiinput", HTTP_GET, [] (AsyncWebServerRequest *request) {
  397.     String html = Headder_str();
  398.     html += "<a href='/'>TOP</a> ";
  399.     html += "<hr><p>";
  400.     html += "<h3>WiFi Selector</h3>";
  401.     html += "<form action='/wifiset' method='get'>";
  402.     html += "<select name='ssid' id ='ssid'>";
  403.     html += "</select><br>\r\n";
  404.     html += "Password<br><input type='password' name='passwd' value='" + passwd + "'>";
  405.     html += "<br><input type='submit' value='set'>";
  406.     html += "</form><br>";
  407.     html += "<script type='text/javascript'>\n";
  408.     html += "const selectName = document.getElementById('ssid');\n";
  409.     html += "let xhr = new XMLHttpRequest();\n";
  410.     html += "xhr.open('GET', 'scan');\n";
  411.     html += "xhr.onload = () => {\n";
  412.     html += "let responseJson = JSON.parse(xhr.response);\n";
  413.     html += "for(var i=0;i<responseJson.length;i++){\n";
  414.     html += "let op = document.createElement('option');\n";
  415.     html += "op.value = responseJson[i].ssid;\n";
  416.     html += "op.textContent = responseJson[i].ssid;\n";
  417.     html += "selectName.appendChild(op);}}\n";
  418.     html += "xhr.send();\n</script>\n";
  419.     html += "<br><hr><p><center><a href='/'>Cancel</a></center>";
  420.     html += "</body></html>";
  421.     request->send(200, "text/html", html);
  422.   });
  423.   server.on("/wifiset", HTTP_GET, [] (AsyncWebServerRequest *request) {
  424.     AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "");
  425.     //ssid = server.arg("ssid");
  426.     //passwd = server.arg("passwd");
  427.     ssid = request->arg("ssid");
  428.     passwd = request->arg("passwd");
  429.     ssid.trim();
  430.     passwd.trim();
  431.     #ifdef debug
  432.     Serial.println(ssid);
  433.     #endif
  434.  
  435.     response->addHeader("Location", String("http://esp.local"));
  436.     request->send(response);
  437.  
  438.     MDNS.end();
  439.     WiFi.mode(WIFI_STA);
  440.     WiFi.begin(ssid.c_str(), passwd.c_str());
  441.     unsigned int cnt = 0;
  442.     while (WiFi.status() != WL_CONNECTED) {
  443.       cnt++;
  444.       delay(100);
  445.       led_toggle();//LED点滅
  446.       if(cnt >= 100){//接続トライ100カウントで戻る
  447.         digitalWrite(LED_BUILTIN, LOW);
  448.         //WiFi.mode(WIFI_AP);
  449.         //WiFi.softAP("ESP-WROOM-02");
  450.         //WiFi.begin();
  451.         SoftAPmode();
  452.         break;
  453.       }
  454.       #ifdef debug
  455.       Serial.print(".");
  456.       #endif
  457.     }
  458.     if (!MDNS.begin("esp")) {
  459.       #ifdef debug
  460.       Serial.println("Error setting up MDNS responder!");
  461.       #endif
  462.     }
  463.     MDNS.addService("http", "tcp", 80);
  464.     if(WiFi.status() == WL_CONNECTED){
  465.       digitalWrite(LED_BUILTIN, HIGH);
  466.     }
  467.  
  468.   });
  469.   server.on("/reboot", HTTP_GET, [] (AsyncWebServerRequest *request) {
  470.     String html = Headder_str();
  471.     html += "<hr><p>";
  472.     html += "<h3>reboot confirmation</h3><p>";
  473.     html += "Are you sure to reboot?<p>";
  474.     html += "<center><a href='/doreboot'>YES</a> <a href='/'>no</a></center>";
  475.     html += "<p><hr>";
  476.     html += "</body></html>";
  477.     request->send(200, "text/html", html);
  478.   });
  479.   server.on("/doreboot", HTTP_GET, [] (AsyncWebServerRequest *request) {
  480.     String html = Headder_str();
  481.     html += "<hr><p>";
  482.     html += "<h3>rebooting</h3><p>";
  483.     html += "The setting WiFi connection will be disconnected...<p>";
  484.     html += "<hr>";
  485.     html += "</body></html>";
  486.     request->send(200, "text/html", html);
  487.  
  488.     // reboot
  489.     #ifdef debug
  490.     Serial.println("reboot now.");
  491.     #endif
  492.     //digitalWrite(LED_BUILTIN, LOW);
  493.    
  494.     delay(2000); // hold 2 sec
  495.     ESP.restart(); // restart
  496.   });
  497.   server.on("/scan", HTTP_GET, [](AsyncWebServerRequest *request){
  498.   String json = "[";
  499.   int n = WiFi.scanComplete();
  500.   if(n == -2){
  501.     WiFi.scanNetworks(true);
  502.   } else if(n){
  503.     for (int i = 0; i < n; ++i){
  504.       if(i) json += ",";
  505.       json += "{";
  506.       json += "\"rssi\":"+String(WiFi.RSSI(i));
  507.       json += ",\"ssid\":\""+WiFi.SSID(i)+"\"";
  508.       json += ",\"bssid\":\""+WiFi.BSSIDstr(i)+"\"";
  509.       json += ",\"channel\":"+String(WiFi.channel(i));
  510.       json += ",\"secure\":"+String(WiFi.encryptionType(i));
  511.       json += ",\"hidden\":"+String(WiFi.isHidden(i)?"true":"false");
  512.       json += "}";
  513.     }
  514.     WiFi.scanDelete();
  515.     if(WiFi.scanComplete() == -2){
  516.       WiFi.scanNetworks(true);
  517.     }
  518.   }
  519.   json += "]";
  520.   //CORS対策
  521.   AsyncWebServerResponse *response = request->beginResponse(200, "application/json", json);
  522.   response->addHeader(F("Access-Control-Allow-Origin"), F("*"));
  523.   response->addHeader(F("Access-Control-Max-Age"), F("600"));
  524.   response->addHeader(F("Access-Control-Allow-Methods"), F("PUT,POST,GET,OPTIONS"));
  525.   response->addHeader(F("Access-Control-Allow-Headers"), F("*"));
  526.   request->send(response);
  527.   //request->send(200, "application/json", json);
  528.   json = String();
  529.   });
  530.  
  531. }
  532.  
  533. //以下WebUpdate用
  534.  
  535. /*
  536. void handleUpdate(AsyncWebServerRequest *request) {
  537.   char* html = "<form method='POST' action='/doUpdate' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
  538.   request->send(200, "text/html", html);
  539. }
  540. */
  541.  
  542. size_t content_len;
  543.  
  544. void handleDoUpdate(AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data, size_t len, bool final) {
  545.   if (!index){
  546.     Serial.println("Update");
  547.     content_len = request->contentLength();
  548.     // if filename includes spiffs, update the spiffs partition
  549.     //int cmd = (filename.indexOf("spiffs") > -1) ? U_PART : U_FLASH;
  550. #ifdef ESP8266
  551.     Update.runAsync(true);
  552.     if (!Update.begin(content_len, U_FLASH)) {
  553. #else
  554.     if (!Update.begin(UPDATE_SIZE_UNKNOWN, U_FLASH)) {
  555. #endif
  556.       Update.printError(Serial);
  557.     }
  558.   }
  559.  
  560.   if (Update.write(data, len) != len) {
  561.     Update.printError(Serial);
  562. #ifdef ESP8266
  563.   } else {
  564.     Serial.printf("Progress: %d%%\n", (Update.progress()*100)/Update.size());
  565. #endif
  566.   }
  567.  
  568.   if (final) {
  569.     AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Please wait while the device reboots");
  570.     response->addHeader("Refresh", "20");  
  571.     response->addHeader("Location", "/");
  572.     request->send(response);
  573.     if (!Update.end(true)){
  574.       Update.printError(Serial);
  575.     } else {
  576.       Serial.println("Update complete");
  577.       Serial.flush();
  578.       ESP.restart();
  579.     }
  580.   }
  581. }
  582.  
  583. void printProgress(size_t prg, size_t sz) {
  584.   Serial.printf("Progress: %d%%\n", (prg*100)/content_len);
  585. }
  586.  
  587.  
  588.  
Advertisement
Add Comment
Please, Sign In to add comment