Subversion Repositories ESP8266_P1_Meter

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 raymond 1
#ifdef ESP8266
2
  #include <ESP8266HTTPClient.h>
3
  #include <ESP8266httpUpdate.h>
4
#elif defined(ESP32)
5
  #include <WiFiClientSecure.h>
6
  #include <HTTPClient.h>
7
  #include <HTTPUpdate.h>
8
#endif
9
#include <EEPROM.h>            // For storing the firmware version
10
 
11
#include <FS.h>
12
#include <LittleFS.h>
13
#include <AsyncFsWebServer.h>   // https://github.com/cotestatnt/async-esp-fs-webserver/
14
 
15
#define FILESYSTEM LittleFS
16
AsyncFsWebServer server( FILESYSTEM, 80, "remoteOTA");
17
 
18
#ifndef LED_BUILTIN
19
#define LED_BUILTIN 2
20
#endif
21
 
22
// In order to set SSID and password open the /setup webserver page
23
// const char* ssid;
24
// const char* password;
25
 
26
uint8_t ledPin = LED_BUILTIN;
27
bool apMode = false;
28
 
29
#ifdef ESP8266
30
String fimwareInfo = "https://raw.githubusercontent.com/cotestatnt/async-esp-fs-webserver/master/examples/remoteOTA/version-esp8266.json";
31
#elif defined(ESP32)
32
String fimwareInfo = "https://raw.githubusercontent.com/cotestatnt/async-esp-fs-webserver/master/examples/remoteOTA/version-esp32.json";
33
#endif
34
 
35
char fw_version[10] = {"0.0.0"};
36
 
37
//////////////////////////////  Firmware update /////////////////////////////////////////
38
void doUpdate(const char* url, const char* version) {
39
 
40
  #ifdef ESP8266
41
  #define UPDATER ESPhttpUpdate
42
  #elif defined(ESP32)
43
  #define UPDATER httpUpdate
44
  #if ESP_ARDUINO_VERSION_MAJOR > 2
45
  esp_task_wdt_config_t twdt_config = {
46
      .timeout_ms = 15*1000,
47
      .idle_core_mask = (1 << portNUM_PROCESSORS) - 1,    // Bitmask of all cores
48
      .trigger_panic = false,
49
  };
50
  ESP_ERROR_CHECK(esp_task_wdt_reconfigure(&twdt_config));
51
  #else
52
  ESP_ERROR_CHECK(esp_task_wdt_init(15, 0));
53
  #endif
54
  #endif
55
 
56
  // onProgress handling is missing with ESP32 library
57
  UPDATER.onProgress([](int cur, int total){
58
    static uint32_t sendT;
59
    if(millis() - sendT > 1000){
60
      sendT = millis();
61
      Serial.printf("Updating %d of %d bytes...\n", cur, total);
62
    }
63
  });
64
 
65
  WiFiClientSecure client;
66
  client.setInsecure();
67
  UPDATER.rebootOnUpdate(false);
68
  UPDATER.setFollowRedirects(HTTPC_FORCE_FOLLOW_REDIRECTS);
69
  UPDATER.setLedPin(LED_BUILTIN, LOW);
70
  t_httpUpdate_return ret = UPDATER.update(client, url, fw_version);
71
  client.stop();
72
 
73
  switch (ret) {
74
    case HTTP_UPDATE_FAILED:
75
      Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", UPDATER.getLastError(), UPDATER.getLastErrorString().c_str());
76
      break;
77
 
78
    case HTTP_UPDATE_NO_UPDATES:
79
      Serial.println("HTTP_UPDATE_NO_UPDATES");
80
      break;
81
 
82
    case HTTP_UPDATE_OK:
83
      Serial.println("HTTP_UPDATE_OK");
84
      strcpy(fw_version, version);
85
      EEPROM.put(0, fw_version);
86
      EEPROM.commit();
87
      Serial.print("System will be restarted with the new version ");
88
      Serial.println(fw_version);
89
      delay(1000);
90
      ESP.restart();
91
      break;
92
  }
93
 
94
 
95
}
96
 
97
////////////////////////////////  Filesystem  /////////////////////////////////////////
98
 
99
 
100
bool startFilesystem() {
101
  if (FILESYSTEM.begin()){
102
    server.printFileList(FILESYSTEM, "/", 1, Serial);
103
    return true;
104
  }
105
  else {
106
    Serial.println("ERROR on mounting filesystem. It will be reformatted!");
107
    FILESYSTEM.format();
108
    ESP.restart();
109
  }
110
  return false;
111
}
112
 
113
 
114
////////////////////////////  HTTP Request Handlers  ////////////////////////////////////
115
void handleLed(AsyncWebServerRequest *request) {
116
  // http://xxx.xxx.xxx.xxx/led?val=1
117
  if(request->hasArg("val")) {
118
    int value = request->arg("val").toInt();
119
    digitalWrite(ledPin, value);
120
  }
121
 
122
  String reply = "LED is now ";
123
  reply += digitalRead(ledPin) ? "OFF" : "ON";
124
  request->send(200, "text/plain", reply);
125
}
126
 
127
/* Handle the update request from client.
128
* The web page will check if is it necessary or not checking the actual version.
129
* Info about firmware as version and remote url, are stored in "version.json" file
130
*
131
* Using this example, the correct workflow for deploying a new firmware version is:
132
  - upload the new firmware.bin compiled on your web space (in this example Github is used)
133
  - update the "version.json" file with the new version number and the address of the binary file
134
  - on the update webpage, press the "UPDATE" button.
135
*/
136
void handleUpdate(AsyncWebServerRequest *request) {
137
  if(request->hasArg("version") && request->hasArg("url")) {
138
    const char* new_version = request->arg("version").c_str();
139
    const char* url = request->arg("url").c_str();
140
    String reply = "Firmware is going to be updated to version ";
141
    reply += new_version;
142
    reply += " from remote address ";
143
    reply += url;
144
    reply += "<br>Wait 10-20 seconds and then reload page.";
145
    request->send(200, "text/plain", reply );
146
    Serial.println(reply);
147
    doUpdate(url, new_version);
148
  }
149
}
150
 
151
///////////////////////////////////  SETUP  ///////////////////////////////////////
152
void setup(){
153
  pinMode(LED_BUILTIN, OUTPUT);
154
  Serial.begin(115200);
155
  EEPROM.begin(128);
156
 
157
  // FILESYSTEM INIT
158
  startFilesystem();
159
 
160
  // Try to connect to WiFi (will start AP if not connected after timeout)
161
  if (!server.startWiFi(10000)) {
162
    Serial.println("\nWiFi not connected! Starting AP mode...");
163
    server.startCaptivePortal("ESP_AP", "123456789", "/setup");
164
  }
165
 
166
  // Enable ACE FS file web editor and add FS info callback function
167
  server.enableFsCodeEditor();
168
 
169
  // Add custom handlers to webserver
170
  server.on("/led", HTTP_GET, handleLed);
171
  server.on("/firmware_update", HTTP_GET, handleUpdate);
172
 
173
  // Add handler as lambda function (just to show a different method)
174
  server.on("/version", HTTP_GET, [](AsyncWebServerRequest *request) {
175
    server.getOptionValue("New firmware JSON", fimwareInfo);
176
 
177
    EEPROM.get(0, fw_version);
178
    if (fw_version[0] == 0xFF) // Still not stored in EEPROM (first run)
179
      strcpy(fw_version, "0.0.0");
180
    String reply = "{\"version\":\"";
181
    reply += fw_version;
182
    reply += "\", \"newFirmwareInfoJSON\":\"";
183
    reply += fimwareInfo;
184
    reply += "\"}";
185
    // Send to client actual firmware version and address where to check if new firmware available
186
    request->send(200, "text/json", reply);
187
  });
188
 
189
  // Configure /setup page and start Web Server
190
  server.addOptionBox("Remote Update");
191
  server.addOption("New firmware JSON", fimwareInfo);
192
 
193
  // Start server with built-in websocket event handler
194
  server.init();
195
  Serial.print(F("ESP Web Server started on IP Address: "));
196
  Serial.println(server.getServerIP());
197
  Serial.println(F(
198
    "This is \"remoteOTA.ino\" example.\n"
199
    "Open /setup page to configure optional parameters.\n"
200
    "Open /edit page to view, edit or upload example or your custom webserver source files."
201
  ));
202
}
203
 
204
///////////////////////////////////  LOOP  ///////////////////////////////////////
205
void loop() {
206
 
207
  // This delay is required in order to avoid loopTask() WDT reset on ESP32
208
  delay(1);  
209
}