Skip to content

Commit f4a32c5

Browse files
committed
Auto update from web enabled
1 parent f326aa1 commit f4a32c5

9 files changed

+197
-137
lines changed

platformio.ini

+6-5
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,11 @@
99
; https://docs.platformio.org/page/projectconf.html
1010

1111
[env:esp32doit-devkit-v1]
12-
; platform = espressif32
13-
platform = https://github.com/platformio/platform-espressif32.git
12+
platform = espressif32
13+
; platform = https://github.com/platformio/platform-espressif32.git
1414
; once the 1.0.5 will be released we can comment this line and probably just use `platform = espressif32` for the line above
15-
platform_packages =
16-
platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git
15+
; platform_packages =
16+
; platformio/framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git
1717
board = esp32doit-devkit-v1
1818
monitor_speed = 115200
1919
upload_speed = 921600
@@ -23,7 +23,8 @@ upload_protocol = espota
2323
upload_port = openmosfet.local
2424
framework = arduino
2525
build_flags =
26-
-D DEBUG
26+
-DCORE_DEBUG_LEVEL=0
27+
; -D DEBUG
2728
lib_deps =
2829
https://github.com/thomasfredericks/Bounce2.git
2930
https://github.com/bblanchon/ArduinoJson.git

src/autoUpdater.cpp

+121-60
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#include "config.h"
22
#include "autoUpdater.h"
33
#include "utilities.h"
4+
#include "wifiServer.h"
45

56
#include <ArduinoJson.h>
67
#include <HTTPClient.h>
@@ -21,24 +22,21 @@ void OMAutoUpdater::requestUpdate(){
2122

2223
void OMAutoUpdater::updateFromGit(){
2324

24-
HTTPClient http;
25+
HTTPClient httpGithubApiClient;
2526

26-
Serial.print("[HTTP] begin...\n");
27-
// configure traged server and url
28-
//http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS
29-
http.begin(OM_DEFAULT_GITHUB_API_LATEST_RELEASE_URL); //HTTP
27+
httpGithubApiClient.begin(OM_DEFAULT_GITHUB_API_LATEST_RELEASE_URL); //HTTP
28+
int httpCodeGithubApi = httpGithubApiClient.GET();
3029

31-
Serial.print("[HTTP] GET...\n");
32-
// start connection and send HTTP header
33-
int httpCode = http.GET();
34-
35-
// httpCode will be negative on error
36-
if(httpCode > 0) {
30+
// httpCodeGithubApi will be negative on error
31+
if(httpCodeGithubApi > 0) {
3732
// HTTP header has been send and Server response header has been handled
38-
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
33+
34+
#ifdef DEBUG
35+
Serial.printf("[HTTP] GET... code: %d\n", httpCodeGithubApi);
36+
#endif
3937

4038
// file found at server
41-
if(httpCode == HTTP_CODE_OK) {
39+
if(httpCodeGithubApi == HTTP_CODE_OK) {
4240

4341
// The filter: it contains "true" for each value we want to keep
4442
StaticJsonDocument<200> filter;//200 = estimation au pifomètre
@@ -47,64 +45,127 @@ void OMAutoUpdater::updateFromGit(){
4745
filter["assets"][0]["size"] = true;
4846

4947
DynamicJsonDocument doc(2000);//2000 = estimation au doigt mouillé
50-
deserializeJson(doc, http.getStream(), DeserializationOption::Filter(filter));
51-
http.end();
52-
53-
for(int i = 0; i < doc["assets"].size(); ++i){
54-
if( doc["assets"][i]["name"].as<String>().equals(OM_DEFAULT_BINARY_FILE_NAME)){
55-
56-
Serial.println( "Begin downloading of -> " + doc["assets"][i]["browser_download_url"].as<String>() );
57-
58-
HTTPClient http2;
59-
//http2.setFollowRedirects(HTTPC_DISABLE_FOLLOW_REDIRECTS); // code 302
60-
//http2.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // code 404
61-
http2.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // code 404
62-
http2.begin(doc["assets"][i]["browser_download_url"].as<const char*>());
63-
64-
httpCode = http2.GET();
65-
if(httpCode == HTTP_CODE_OK) {
66-
if (!Update.begin(http2.getSize(), U_FLASH)) {
67-
Update.printError(Serial);
48+
deserializeJson(doc, httpGithubApiClient.getStream(), DeserializationOption::Filter(filter));
49+
httpGithubApiClient.end();
50+
51+
//we go through each asset to find the right one and download it
52+
String assetUrl;
53+
for(int currentAssetIndex = 0; currentAssetIndex < doc["assets"].size(); ++currentAssetIndex){
54+
if( doc["assets"][currentAssetIndex]["name"].as<String>().equals(OM_DEFAULT_BINARY_FILE_NAME)){
55+
56+
#ifdef DEBUG
57+
Serial.println( "Begin downloading of -> " + doc["assets"][currentAssetIndex]["browser_download_url"].as<String>() );
58+
#endif
59+
60+
assetUrl = doc["assets"][currentAssetIndex]["browser_download_url"].as<String>();
61+
62+
//github api assets uses 302 redirections, we cannot just get the first page
63+
//currently setFollowRedirects does'nt work for me, until it eventually does, we'll handle redirects manually
64+
const int maxRedirects = 4;
65+
for(int redirectCounter = 1; redirectCounter <= maxRedirects; ++redirectCounter){
66+
HTTPClient httpReleaseAssetClient;
67+
//httpReleaseAssetClient.setFollowRedirects(HTTPC_DISABLE_FOLLOW_REDIRECTS); // code 302
68+
//httpReleaseAssetClient.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // code 404
69+
//httpReleaseAssetClient.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS); // code 404
70+
httpReleaseAssetClient.begin(assetUrl);
71+
72+
//we declare which headers we want to keep (for redirects)
73+
const char * headerKeys[] = {"Location"} ;
74+
size_t headerKeysSize = sizeof(headerKeys)/sizeof(char*);
75+
httpReleaseAssetClient.collectHeaders(headerKeys, headerKeysSize);
76+
77+
int httpCodeReleaseAsset = httpReleaseAssetClient.GET();
78+
79+
80+
if(httpCodeReleaseAsset == HTTP_CODE_MOVED_PERMANENTLY || httpCodeReleaseAsset == HTTP_CODE_FOUND){
81+
assetUrl = httpReleaseAssetClient.header("Location");// this is a redirection, store the new url and make another round-trip
82+
httpReleaseAssetClient.end();
6883
}
69-
int initialSize = http2.getSize();
70-
Serial.println( "lets go" );
71-
int finalSize = Update.writeStream(http2.getStream());
72-
http2.end();
73-
74-
Serial.print( "initialSize : " );
75-
Serial.println( initialSize );
76-
Serial.print( "finalSize : " );
77-
Serial.println( finalSize );
78-
if (finalSize == initialSize) {
79-
Serial.println("Written : " + String(finalSize) + " successfully");
80-
} else {
81-
Serial.println("Written only : " + String(finalSize) + "/" + String(initialSize) + ". Retry?" );
82-
83-
}
84-
if (Update.end()) {
85-
Serial.println("OTA done!");
86-
if (Update.isFinished()) {
87-
Serial.println("Update successfully completed. Rebooting.");
88-
ESP.restart();
84+
else if(httpCodeReleaseAsset == HTTP_CODE_OK) {
85+
if (!Update.begin(httpReleaseAssetClient.getSize(), U_FLASH)) {
86+
#ifdef DEBUG
87+
Update.printError(Serial);
88+
#endif
89+
break;
90+
}
91+
int initialSize = httpReleaseAssetClient.getSize();
92+
// int sizeLeftToUpdate = initialSize;
93+
OMwifiserver::events.send("","updateStarted",millis());
94+
#ifdef DEBUG
95+
Serial.println( "Starting update" );
96+
#endif
97+
int finalSize = 0;
98+
99+
finalSize = Update.writeStream(httpReleaseAssetClient.getStream());
100+
httpReleaseAssetClient.end();
101+
//I would like to show progress with this and https://github.com/me-no-dev/ESPAsyncWebServer#async-event-source-plugin
102+
/*
103+
WiFiClient* stream = httpReleaseAssetClient.getStreamPtr();
104+
105+
// inspired by https://github.com/esp8266/Arduino/issues/4010
106+
uint8_t buff[1024] = { 0 };
107+
size_t sizePack;
108+
while(httpReleaseAssetClient.connected() && sizeLeftToUpdate > 0 && stream->available() > 0){
109+
sizePack = stream->available();
110+
if (sizePack) {
111+
int c = stream->readBytes(buff, ((sizePack > sizeof(buff)) ? sizeof(buff) : sizePack));
112+
int bytesWritten = Update.write(buff, c);
113+
if (sizeLeftToUpdate > 0)
114+
sizeLeftToUpdate -= c;
115+
finalSize += bytesWritten;
116+
}
117+
118+
119+
//n'envoyer la notif de progression (ou la stocker) que tout les x secondes et/ou pourcents
120+
// if (progress != int(Update.progress() * 100 / httpClient.getSize())) {
121+
// progress = int(Update.progress() * 100 / httpClient.getSize());
122+
// }
123+
124+
Serial.print("sizeof(buff): ");
125+
Serial.println(sizeof(buff));
126+
Serial.print("sizePack: ");
127+
Serial.println(sizePack);
128+
Serial.print("Update.progress(): ");
129+
Serial.println(finalSize);
130+
}
131+
*/
132+
133+
if (Update.end() && finalSize == initialSize) {
134+
if (Update.isFinished()) {
135+
#ifdef DEBUG
136+
Serial.println("Update successfully completed. Rebooting.");
137+
#endif
138+
OMwifiserver::events.send("","updateSuccessful",millis());
139+
delay(500);//"ensure" that event is fully sent
140+
ESP.restart();
141+
} else {
142+
#ifdef DEBUG
143+
Serial.println("Update not finished? Something went wrong!");
144+
#endif
145+
}
89146
} else {
90-
Serial.println("Update not finished? Something went wrong!");
147+
OMwifiserver::events.send("","updateFailed",millis());
148+
#ifdef DEBUG
149+
Serial.println("Error Occurred. Error #: " + String(Update.getError()));
150+
#endif
151+
break;
91152
}
92-
} else {
93-
Serial.println("Error Occurred. Error #: " + String(Update.getError()));
153+
break;
154+
}else{
155+
OMwifiserver::events.send("","updateFailed",millis());
156+
break;
94157
}
95-
96-
}else{
97-
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
98158
}
99-
100-
break;
101159
}
102160
}
103161

104162

105163
}
106164
} else {
107-
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
165+
#ifdef DEBUG
166+
Serial.printf("[HTTP] GET... failed, error: %s\n", httpGithubApiClient.errorToString(httpCodeGithubApi).c_str());
167+
#endif
168+
OMwifiserver::events.send("","updateFailed",millis());
108169
}
109170
OMAutoUpdater::isUpdateRequested = false;
110171
}

src/config.h

-23
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,6 @@
1616

1717
#define OM_DEFAULT_GITHUB_API_LATEST_RELEASE_URL "https://api.github.com/repos/simonjamain/openmosfet/releases/latest"
1818
#define OM_DEFAULT_BINARY_FILE_NAME "openmosfet.esp32.bin"//TODO: if enabling esp8266 compatibility, lets update that and define two options
19-
// #define OM_DEFAULT_BINARY_FILE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DMB8GA1UdIwQYMBaA\n"\
34-
// "FLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\n"\
35-
// "nzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\n"\
36-
// "eM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\n"\
37-
// "hS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\n"\
38-
// "Yzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\n"\
39-
// "vEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n"\
40-
// "+OkuE6N36B9K\n"\
41-
// "-----END CERTIFICATE-----"
4219

4320
#define OM_DEFAULT_WIFI_SEARCH_TIMEOUT_SECONDS 5
4421
#define OM_DEFAULT_WIFI_SHUTDOWN_DELAY_MINUTES 15

src/configuration.cpp

+6-2
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@ boolean OMConfiguration::useActiveBreaking = OM_DEFAULT_USE_ACTIVE_BRAKING;
2323

2424
void OMConfiguration::loadFromJson(Stream &stream){
2525
DynamicJsonDocument doc(capacity);
26-
27-
Serial.println(deserializeJson(doc, stream).c_str());
2826

27+
deserializeJson(doc, stream);
28+
29+
#ifdef DEBUG
2930
Serial.println("JSON CHARGE");
3031
serializeJson(doc, Serial);
32+
#endif
3133

3234
strcpy(OMConfiguration::appSsid, doc["appSsid"]);
3335
strcpy(OMConfiguration::appPasswd, doc["appPasswd"]);
@@ -149,8 +151,10 @@ boolean OMConfiguration::save(void){
149151
currentFireMode["timeBetweenShots_ms"] = OMConfiguration::fireModes[i].getTimeBetweenShotsMs();
150152
}
151153

154+
#ifdef DEBUG
152155
Serial.println("JSON SAUVE");
153156
serializeJson(doc, Serial);
157+
#endif
154158

155159
File file = FILESYSTEM.open(OM_CONFIGFILE_NAME, "w");
156160
serializeJson(doc, file);

src/openmosfet.cpp

+3-3
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ void loop();
1515

1616
void setup() {
1717
Serial.begin(115200);
18-
Serial.println("Bonjour2");
1918

2019
OMInputsInterface::begin(replica);
2120

@@ -42,10 +41,11 @@ void setup() {
4241
Serial.println(OMConfiguration::load());
4342
Serial.println("config chargée :");
4443
OMConfiguration::printCfg();
44+
#else
45+
OMConfiguration::load();
4546
#endif
4647

47-
OMConfiguration::load();
48-
48+
4949
OMwifiserver::begin();
5050
OMOtaUploader::begin();
5151
}

src/ui.h

+2-2
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)