Arduino icon indicating copy to clipboard operation
Arduino copied to clipboard

SecureWebUpdater OTA Updating from SD card

Open SrikanthBala opened this issue 10 years ago • 3 comments

Basic Infos

Hardware

Hardware: NODEMCU V1.0 Core Version: 2.3.0

Description

I am a little confused on how I should implement a Web update from a SD card. I am using a combination of SDWebServer, WiFiManager and Secure WebUpdater. The following code works upto the point of loading my Web page (a HTML file in my SD card called index.) I am able to download files etc stored in a subdirectory using the links provided and store them in my PC from the WebServer

Despite scouring through the sites for how to implement the SecureWebUpdater example given to run from my SD card, I am out of my depth. I tried to understand 'Simple Updater' example given in http://esp8266.github.io/Arduino/versions/2.0.0/doc/ota_updates/ota_updates.html

However I don't know how to let the browser tell my ESP to run the ESPhttpUpdate.update("192.168.0.2", 80, "/arduino.bin"); as suggested in the example. For Example, how do I get a button on my HTML file to tell the ESP to download a bin file from my PC and use it to OTA update my ESP

Can someone help me

I'm not sure if this is the right forum to post for help regarding code

My code is as follows

Settings in IDE

Module: NODEMCU V1.0 Flash Size: 4MB/1MB CPU Frequency: 80Mhz Flash Mode: ?qio? Flash Frequency: 40Mhz Upload Using: OTA Reset Method: nodemcu

Sketch

/* Credits :

  • The Following example is a combination of efforts made by various people to breathe life into the ESP8266
    • ESP8266 arduino core team
    • ESP SDWebServer Copyright (c) 2015 Hristo Gochkov. GNU license
    • ESP WiFiManager //https://github.com/tzapu/WiFiManager
    • ESP SecureWebUpdater by krzychb & JeroenVogelpoel JeroenVogelpoel https://github.com/esp8266/Arduino/blob/master/doc/ota_updates/readme.md#http-server */

include <ESP8266WiFi.h>

include <WiFiClient.h>

include <ESP8266WebServer.h>

include <ESP8266mDNS.h>

include <ESP8266HTTPUpdateServer.h>

include <SPI.h>

include <SD.h>

include <WiFiManager.h>

include <WiFiUdp.h>

define DBG_OUTPUT_PORT Serial

define SD_CS 4

const char* ssid = ""; const char password = "*"; const char host = "VG"; const char* update_path = "VG"; const char* update_username = "admin"; const char* update_password = "admin";

ESP8266WebServer server(80); ESP8266HTTPUpdateServer httpUpdater;

static bool hasSD = false; File uploadFile;

void setup(void){ DBG_OUTPUT_PORT.begin(115200); DBG_OUTPUT_PORT.setDebugOutput(true); DBG_OUTPUT_PORT.print("\n");

if (SD.begin(SD_CS)){ DBG_OUTPUT_PORT.println("SD Card initialized."); hasSD = true; }

WiFiManager wifiManager; //fetches ssid and pass from eeprom and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration wifiManager.autoConnect(host); /* WiFi.begin(ssid, password); DBG_OUTPUT_PORT.print("Connecting to "); DBG_OUTPUT_PORT.println(ssid); // Wait for connection uint8_t i = 0; while (WiFi.status() != WL_CONNECTED && i++ < 20) {//wait 10 seconds delay(500); }

if(i == 21){ DBG_OUTPUT_PORT.print("Could not connect to"); DBG_OUTPUT_PORT.println(ssid); while(1) delay(500); } DBG_OUTPUT_PORT.print("Connected! IP address: "); */ DBG_OUTPUT_PORT.print("Vaccguard has connected to "); DBG_OUTPUT_PORT.println(WiFi.localIP());

if (MDNS.begin(host)) { MDNS.addService("http", "tcp", 80); DBG_OUTPUT_PORT.println("MDNS responder started"); DBG_OUTPUT_PORT.print("You can now connect to http://"); DBG_OUTPUT_PORT.print(host); DBG_OUTPUT_PORT.println(".local"); }

//Start Updater httpUpdater.setup(&server, update_path, update_username, update_password);

server.on("/list", HTTP_GET, printDirectory); server.on("/edit", HTTP_DELETE, handleDelete); server.on("/edit", HTTP_PUT, handleCreate); server.on("/edit", HTTP_POST, { returnOK(); }, handleFileUpload); server.onNotFound(handleNotFound);

server.begin(); DBG_OUTPUT_PORT.println("HTTP server started");

}

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

void returnOK() { server.send(200, "text/plain", ""); }

void returnFail(String msg) { server.send(500, "text/plain", msg + "\r\n"); }

bool loadFromSdCard(String path){ String dataType = "text/plain"; if(path.endsWith("/")) path += "index.htm";

if(path.endsWith(".src")) path = path.substring(0, path.lastIndexOf(".")); else if(path.endsWith(".htm")) dataType = "text/html"; else if(path.endsWith(".css")) dataType = "text/css"; else if(path.endsWith(".js")) dataType = "application/javascript"; else if(path.endsWith(".png")) dataType = "image/png"; else if(path.endsWith(".gif")) dataType = "image/gif"; else if(path.endsWith(".jpg")) dataType = "image/jpeg"; else if(path.endsWith(".ico")) dataType = "image/x-icon"; else if(path.endsWith(".xml")) dataType = "text/xml"; else if(path.endsWith(".pdf")) dataType = "application/pdf"; else if(path.endsWith(".zip")) dataType = "application/zip";

File dataFile = SD.open(path.c_str()); if(dataFile.isDirectory()){ path += "/index.htm"; dataType = "text/html"; dataFile = SD.open(path.c_str()); }

if (!dataFile) return false;

if (server.hasArg("download")) dataType = "application/octet-stream";

if (server.streamFile(dataFile, dataType) != dataFile.size()) { DBG_OUTPUT_PORT.println("Sent less data than expected!"); }

dataFile.close(); return true; }

void handleFileUpload(){ if(server.uri() != "/edit") return; HTTPUpload& upload = server.upload(); if(upload.status == UPLOAD_FILE_START){ if(SD.exists((char *)upload.filename.c_str())) SD.remove((char *)upload.filename.c_str()); uploadFile = SD.open(upload.filename.c_str(), FILE_WRITE); DBG_OUTPUT_PORT.print("Upload: START, filename: "); DBG_OUTPUT_PORT.println(upload.filename); } else if(upload.status == UPLOAD_FILE_WRITE){ if(uploadFile) uploadFile.write(upload.buf, upload.currentSize); DBG_OUTPUT_PORT.print("Upload: WRITE, Bytes: "); DBG_OUTPUT_PORT.println(upload.currentSize); } else if(upload.status == UPLOAD_FILE_END){ if(uploadFile) uploadFile.close(); DBG_OUTPUT_PORT.print("Upload: END, Size: "); DBG_OUTPUT_PORT.println(upload.totalSize); } }

void deleteRecursive(String path){ File file = SD.open((char *)path.c_str()); if(!file.isDirectory()){ file.close(); SD.remove((char *)path.c_str()); return; }

file.rewindDirectory(); while(true) { File entry = file.openNextFile(); if (!entry) break; String entryPath = path + "/" +entry.name(); if(entry.isDirectory()){ entry.close(); deleteRecursive(entryPath); } else { entry.close(); SD.remove((char *)entryPath.c_str()); } yield(); } SD.rmdir((char *)path.c_str()); file.close(); }

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(); }

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(); }

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(); }

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); }

SrikanthBala avatar Aug 28 '16 12:08 SrikanthBala

What I need is to implement a 'Update Firmware' button on my Page which will check for new firmware from a specified site, download it and update my ESP just like my Router for example does

If this is difficult to implement, the next best would be to download a bin file from a site and then let my SD card webpage have a link which will let me update just like the ESP8266WebUpdater example

SrikanthBala avatar Aug 28 '16 12:08 SrikanthBala

Hi @SrikanthBala,

Nice to hear from you again!

However I don't know how to let the browser tell my ESP to run the ESPhttpUpdate.update("192.168.0.2", 80, "/arduino.bin"); as suggested in the example.

Your "Update Firmware" button should point ESP to specific URL, e.g. "/firmware_update". For ESP to respond, you could use the following code:

  server.on("/firmware_update", [](){
    ESPhttpUpdate.update("192.168.0.2", 80, "/arduino.bin"); 
  });

Please check HelloServer.ino for quick examples how to use server.on().

I'm not sure if this is the right forum to post for help regarding code

This forum to report the issues. The better place to ask for support regarding application code is http://www.esp8266.com

/* Credits :

I have prepared some of OTA documentation, but I am not the author of the OTA implementation / code.

I would suggest to move this discussion to http://www.esp8266.com. There are several people willing to answer to questions like that, including me :smile:

Krzysztof

krzychb avatar Aug 28 '16 14:08 krzychb

Thanks again. Will close the issue here as recommended. Bye.

SrikanthBala avatar Aug 28 '16 14:08 SrikanthBala