如何实现 ESP32 固件的 OTA 在线升级更新

请参考如下文章

https://blog.csdn.net/liwei16611/article/details/81051909

只是针对 3.2、Web Browser 方案固件更新 进行修改。

//const char* SSID = "HUAWEI-7MMSCQ";
//const char* PSWD = "abcdefgh";

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <esp_wifi.h>

const char* host = "esp32";
const char* ssid = "MERCURY_27D378";
const char* ssidAP = "ESP32AP";
const char* password = "abcdefghi";
String Version = "Version 1.0";
WebServer server(80);
IPAddress myIP;

long Time1, Time2;
uint16_t Count;
boolean IsStartUpdate = false, isDeviceConnected;
uint8_t LEDPin = 2, Cycles;
String TempStr;

/*
   Login page
*/

const char* loginIndex =
  "<form name='loginForm'>"
  "<table width='20%' bgcolor='A09F9F' align='center'>"
  "<tr>"
  "<td colspan=2>"
  "<center><font size=4><b>ESP32 Login Page</b></font></center>"
  "<br>"
  "</td>"
  "<br>"
  "<br>"
  "</tr>"
  "<td>Username:</td>"
  "<td><input type='text' size=25 name='userid'><br></td>"
  "</tr>"
  "<br>"
  "<br>"
  "<tr>"
  "<td>Password:</td>"
  "<td><input type='Password' size=25 name='pwd'><br></td>"
  "<br>"
  "<br>"
  "</tr>"
  "<tr>"
  "<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
  "</tr>"
  "</table>"
  "</form>"
  "<script>"
  "function check(form)"
  "{"
  "if(form.userid.value=='admin' && form.pwd.value=='admin')"
  "{"
  "window.open('/serverIndex')"
  "}"
  "else"
  "{"
  " alert('Error Password or Username')/*displays error message*/"
  "}"
  "}"
  "</script>";

/*
   Server Index Page
*/

// "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
//下面的 action='#'  修改为 action='update'


const char* serverIndex =
  "<form method='POST' action='update' enctype='multipart/form-data' id='upload_form'>"
  "<input type='file' name='update'>"
  "<input type='submit' value='Update'>"
  "</form>"
  "<div id='prg'>progress: 0%</div>"
  "<script>"
  "$('form').submit(function(e){"
  "e.preventDefault();"
  "var form = $('#upload_form')[0];"
  "var data = new FormData(form);"
  " $.ajax({"
  "url: '/update',"
  "type: 'POST',"
  "data: data,"
  "contentType: false,"
  "//processData:false,"
  "xhr: function() {"
  "var xhr = new window.XMLHttpRequest();"
  "xhr.upload.addEventListener('progress', function(evt) {"
  "if (evt.lengthComputable) {"
  "var per = evt.loaded / evt.total;"
  "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
  "}"
  "}, false);"
  "return xhr;"
  "},"
  "success:function(d, s) {"
  "console.log('success!')"
  "},"
  "error: function (a, b, c) {"
  "}"
  "});"
  "});"
  "</script>";



/*
   setup function
*/
void setup(void) {
  Serial.begin(115200);
  //ConnectToWIFI();

  StartAP();
  iniWebServer();

}

void ConnectToWIFI() {

  // Connect to WiFi network
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  myIP = WiFi.localIP();
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(myIP);

}


void StartAP() {

  pinMode(LEDPin, OUTPUT);
  esp_wifi_restore();
  WiFi.disconnect(true);
  WiFi.softAP(ssidAP, password);
  //Initiate connection
  myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  WiFi.onEvent(MyWiFiEvent);

}

//wifi event handler
void MyWiFiEvent(WiFiEvent_t event) {
  String OutStr;
  switch (event) {
    //    case SYSTEM_EVENT_STA_GOT_IP:
    //      //When connected set
    //      Serial.print("WiFi connected! IP address: ");
    //      Serial.println(WiFi.localIP());
    //      //initializes the UDP state
    //      //This initializes the transfer buffer
    //      udp.begin(WiFi.localIP(), udpPort);
    //      UDPconnected = true;
    //      break;
    //    case SYSTEM_EVENT_STA_DISCONNECTED:
    //      Serial.println("WiFi lost connection");
    //      UDPconnected = false;
    //      break;

    case SYSTEM_EVENT_AP_STACONNECTED:
      Serial.print ("WiFi STA connection ");
      Serial.println(WiFi.softAPgetStationNum());
      isDeviceConnected = true;

      break;

    case SYSTEM_EVENT_AP_STAIPASSIGNED:
      Serial.print ("WiFi STA IP assigned. ");

      break;

    case SYSTEM_EVENT_AP_STADISCONNECTED:
      Serial.print ("WiFi STA disconnection ");
      Serial.println(WiFi.softAPgetStationNum());
      isDeviceConnected = false;
      digitalWrite(LEDPin, HIGH);
      break;

  }

}



void iniWebServer() {

  /*use mdns for host name resolution*/
  if (!MDNS.begin(host)) { //http://esp32.local
    Serial.println("Error setting up MDNS responder!");
    while (1) {
      delay(1000);
    }
  }
  Serial.println("mDNS responder started");
  /*return index page which is stored in serverIndex */
  server.on("/", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", loginIndex);
  });


  TempStr = "Current program " + Version;
  TempStr += serverIndex;

  server.on("/serverIndex", HTTP_GET, []() {
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", TempStr.c_str());
    Serial.println("You can upload file...");
  });

  /*handling uploading firmware file */
  server.on("/update", HTTP_POST, []() {
    server.sendHeader("Connection", "close");
    Serial.print("Start upload...");
    String Result;
    Result = (Update.hasError()) ? "FAIL" : "OK";
    Serial.println(Result);
    server.send(200, "text/plain", Result);
    //server.send(200, "text/plain", "Upload OK");

    ESP.restart();
  }, []() {
    HTTPUpload & upload = server.upload();
    Serial.print(".");
    if (upload.status == UPLOAD_FILE_START) {
      Serial.printf("Update: %s\n", upload.filename.c_str());
      IsStartUpdate = true;
      if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
        Update.printError(Serial);
      }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
      /* flashing firmware to ESP*/
      Serial.print("-");
      Count++;
      if ((Count % 20) == 0) {
        Serial.println("");
      }
      LEDflash(2);
      if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
        Update.printError(Serial);
        Serial.print("Updated Fail.");
      }
    } else if (upload.status == UPLOAD_FILE_END) {
      if (Update.end(true)) { //true to set the size to the current progress
        Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
      } else {
        Update.printError(Serial);
      }
    }
  });
  server.begin();

}


void loop(void) {
  server.handleClient();

  delay(1);
  if (millis() - Time1 > 5000 && !IsStartUpdate) {
    Time1 = millis();
    Serial.print("Please connect: ");
    Serial.print(myIP);
    Serial.println(" by explore");
  }

  
}


void LEDflash(uint8_t LEDflashTick) {

  Cycles++;
  if (Cycles > LEDflashTick) {
    digitalWrite(LEDPin, HIGH);
  } else {
    digitalWrite(LEDPin, LOW);
  }

  if (Cycles == LEDflashTick * 2) {
    Cycles = 0;
  }

}

 

 

手机或笔记本电脑连上 WiFi “ESP32AP”,然后打开浏览器,访问 “192.168.4.1”,在网页里的Username 中输入 “admin”,Password 中输入 "admin",然后就可以选择文件,再点 “update”,LED就会闪烁,表示正在写入程序。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值