You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
61 lines
1.2 KiB
C++
61 lines
1.2 KiB
C++
5 years ago
|
#include <HTTPClient.h>
|
||
|
#include <SPIFFS.h>
|
||
|
#include "download.h"
|
||
4 years ago
|
#include "device.h"
|
||
5 years ago
|
|
||
|
HTTPClient http;
|
||
|
|
||
|
bool downloadFile(String url, const char *path)
|
||
|
{
|
||
|
// @note duration time: 200kb = 35sec write to flash
|
||
|
Serial.println("Download file: " + url);
|
||
|
|
||
5 years ago
|
// tmp file
|
||
5 years ago
|
bool hasError = false;
|
||
|
String tmpFile = path;
|
||
|
tmpFile += ".tmp";
|
||
|
|
||
5 years ago
|
// track duration
|
||
|
long startMills = millis();
|
||
|
|
||
|
File file = SPIFFS.open(tmpFile, FILE_WRITE);
|
||
|
if (!file)
|
||
|
{
|
||
|
Serial.println("Failed to open file for writing");
|
||
|
return false;
|
||
|
}
|
||
|
|
||
4 years ago
|
http.useHTTP10(true); // http1.1 chunked is not working correctly
|
||
5 years ago
|
http.setTimeout(7000);
|
||
4 years ago
|
http.setUserAgent("paperdash esp");
|
||
|
|
||
|
// use the last 8 bytes of the unique serial id
|
||
|
http.addHeader("X-PaperDash-Id", DeviceId);
|
||
|
|
||
5 years ago
|
http.begin(url);
|
||
|
int httpCode = http.GET();
|
||
|
if (httpCode != HTTP_CODE_OK)
|
||
|
{
|
||
4 years ago
|
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||
5 years ago
|
hasError = true;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
5 years ago
|
http.writeToStream(&file);
|
||
5 years ago
|
|
||
|
if (file)
|
||
|
{
|
||
|
file.close();
|
||
|
SPIFFS.remove(path);
|
||
|
SPIFFS.rename(tmpFile, path);
|
||
|
}
|
||
|
|
||
|
Serial.print("download completed in: ");
|
||
|
Serial.println(millis() - startMills);
|
||
|
}
|
||
|
|
||
|
// clean up
|
||
|
http.end();
|
||
|
|
||
|
return !hasError;
|
||
|
}
|