ota added

This commit is contained in:
Dmitry Borisenko
2020-09-17 21:33:54 +03:00
parent d6f5506812
commit e23481eef2
13 changed files with 186 additions and 153 deletions

View File

@@ -43,7 +43,7 @@
}, },
{ {
"type": "h4", "type": "h4",
"title": "LittleFS version: 2.4.0" "title": "LittleFS version: 240"
}, },
{ {
"type": "hr" "type": "hr"

View File

View File

@@ -3,12 +3,12 @@
* Main consts * Main consts
*/ */
#define FIRMWARE_NAME "esp8266-iotm" #define FIRMWARE_NAME "esp8266-iotm"
#define FIRMWARE_VERSION "240" #define FIRMWARE_VERSION 240
#define NUM_BUTTONS 6 #define NUM_BUTTONS 6
#define LED_PIN 2 #define LED_PIN 2
#define FLASH_4MB true #define FLASH_4MB true
#define MQTT_RECONNECT_INTERVAL 20000 #define MQTT_RECONNECT_INTERVAL 20000
#define TELEMETRY_UPDATE_INTERVAL_MIN 60 #define TELEMETRY_UPDATE_INTERVAL_MIN 60
@@ -23,7 +23,6 @@
#define TAG_I2C "i2c" #define TAG_I2C "i2c"
#define TAG_ONE_WIRE_PIN "oneWirePin" #define TAG_ONE_WIRE_PIN "oneWirePin"
/* /*
* Optional * Optional
*/ */
@@ -42,7 +41,6 @@
#define ANALOG_ENABLED #define ANALOG_ENABLED
#define DALLAS_ENABLED #define DALLAS_ENABLED
#define DHT_ENABLED #define DHT_ENABLED
@@ -97,14 +95,14 @@ enum TimerTask_t { WIFI_SCAN,
TEST }; TEST };
enum notAsincActions { enum notAsincActions {
do_ZERO, do_ZERO,
do_UPGRADE, do_UPGRADE,
do_GETLASTVERSION, do_GETLASTVERSION,
do_UDPDATAPARSE, do_UDPDATAPARSE,
do_MQTTUDP, do_MQTTUDP,
do_BUSSCAN, do_BUSSCAN,
do_MQTTPARAMSCHANGED, do_MQTTPARAMSCHANGED,
do_LAST, do_LAST,
}; };
enum ErrorType_t { enum ErrorType_t {
@@ -137,5 +135,3 @@ enum BusScanner_t {
BS_I2C, BS_I2C,
BS_ONE_WIRE BS_ONE_WIRE
}; };

View File

@@ -80,7 +80,7 @@ extern int8_t dallasEnterCounter;
extern String logging_value_names_list; extern String logging_value_names_list;
extern int enter_to_logging_counter; extern int enter_to_logging_counter;
extern int scenario_line_status[40]; extern int scenario_line_status[40];
extern String lastVersion; extern int lastVersion;
//Запрос на скарнирование шины //Запрос на скарнирование шины

View File

@@ -1,8 +0,0 @@
#pragma once
#include <Arduino.h>
const String getAvailableUrl(const char* mcu);
void getLastVersion();
void upgradeInit();
void upgrade_firmware();

10
include/UpgradeFirm.h Normal file
View File

@@ -0,0 +1,10 @@
#pragma once
#include <Arduino.h>
extern void upgradeInit();
extern void getLastVersion();
extern void upgrade_firmware(int type);
extern bool upgradeFS();
extern bool upgradeBuild();
extern void restartEsp();

View File

@@ -47,7 +47,7 @@ int enter_to_logging_counter;
// Scenario // Scenario
int scenario_line_status[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; int scenario_line_status[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
String lastVersion = ""; int lastVersion;
BusScanner_t busToScan; BusScanner_t busToScan;
boolean busScanFlag = false; boolean busScanFlag = false;

View File

@@ -9,7 +9,7 @@ void loadConfig() {
configSetupJson.replace("\r\n", ""); configSetupJson.replace("\r\n", "");
jsonWriteStr(configSetupJson, "chipID", chipId); jsonWriteStr(configSetupJson, "chipID", chipId);
jsonWriteStr(configSetupJson, "firmware_version", FIRMWARE_VERSION); jsonWriteInt(configSetupJson, "firmware_version", FIRMWARE_VERSION);
prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId; prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId;

View File

@@ -1,89 +0,0 @@
#include "Upgrade.h"
#include "Class/NotAsinc.h"
#include "ESP8266.h"
#include "Global.h"
static const char* check_update_url PROGMEM = "http://91.204.228.124:1100/update/%s/version.txt";
void upgradeInit() {
myNotAsincActions->add(
do_UPGRADE, [&](void*) {
upgrade_firmware();
},
nullptr);
myNotAsincActions->add(
do_GETLASTVERSION, [&](void*) {
getLastVersion();
},
nullptr);
if (isNetworkActive()) {
getLastVersion();
if (lastVersion.length()) {
SerialPrint("I","Update","available: " + lastVersion);
}
};
}
const String getAvailableUrl(const char* mcu) {
char buf[128];
sprintf_P(buf, check_update_url, mcu);
return buf;
}
void getLastVersion() {
String url;
#ifdef ESP8266
url = getAvailableUrl("esp8266");
#else
url = getAvailableUrl("esp32");
#endif
lastVersion = getURL(url);
jsonWriteStr(configSetupJson, "last_version", lastVersion);
}
void upgrade_firmware() {
String scanerioBackup, configBackup, setupBackup;
scanerioBackup = readFile(String(DEVICE_SCENARIO_FILE), 4096);
configBackup = readFile(String(DEVICE_CONFIG_FILE), 4096);
setupBackup = configSetupJson;
SerialPrint("I","module","update data");
WiFiClient wifiClient;
#ifdef ESP8266
ESPhttpUpdate.rebootOnUpdate(false);
t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(wifiClient, F("http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"));
#else
httpUpdate.rebootOnUpdate(false);
t_httpUpdate_return ret = httpUpdate.updateSpiffs(client_for_upgrade, F("http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"));
#endif
if (ret == HTTP_UPDATE_OK) {
writeFile(String(DEVICE_SCENARIO_FILE), scanerioBackup);
writeFile(String(DEVICE_CONFIG_FILE), configBackup);
writeFile("config.json", setupBackup);
saveConfig();
SerialPrint("I","module","done!");
} else {
SerialPrint("[E]","module","on data");
return;
}
//Serial.println("update firmware");
#ifdef ESP8266
ret = ESPhttpUpdate.update(wifiClient, F("http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin"));
#else
ret = httpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin");
#endif
if (ret == HTTP_UPDATE_OK) {
SerialPrint("I","module","done! restart...");
ESP.restart();
} else {
SerialPrint("[E]","module","on firmware");
}
}

129
src/UpgradeFirm.cpp Normal file
View File

@@ -0,0 +1,129 @@
#include "UpgradeFirm.h"
#include "Class/NotAsinc.h"
#include "ESP8266.h"
#include "Global.h"
void upgradeInit() {
myNotAsincActions->add(
do_UPGRADE, [&](void*) {
upgrade_firmware(3);
},
nullptr);
myNotAsincActions->add(
do_GETLASTVERSION, [&](void*) {
getLastVersion();
},
nullptr);
if (isNetworkActive()) {
getLastVersion();
if (lastVersion > 0) {
SerialPrint("I", "Update", "available version: " + lastVersion);
}
};
}
void getLastVersion() {
if ((WiFi.status() == WL_CONNECTED)) {
String tmp = getURL(F("http://95.128.182.133/projects/iotmanager/esp8266/esp8266ver.txt"));
if (tmp == "error") {
lastVersion = -1;
} else {
lastVersion = tmp.toInt();
}
} else {
lastVersion = -2;
}
jsonWriteInt(configSetupJson, "last_version", lastVersion);
}
void upgrade_firmware(int type) {
if (type == 1) { //only build
if (upgradeBuild()) restartEsp();
} else if (type == 2) { //only spiffs
if (upgradeFS()) restartEsp();
} else if (type == 3) { //spiffs and build
if (upgradeFS()) {
if (upgradeBuild()) {
restartEsp();
}
}
}
}
bool upgradeFS() {
WiFiClient wifiClient;
bool ret = false;
Serial.println("Start upgrade LittleFS, please wait...");
ESPhttpUpdate.rebootOnUpdate(false);
t_httpUpdate_return retFS = ESPhttpUpdate.updateSpiffs(wifiClient, F("http://95.128.182.133/projects/iotmanager/esp8266/littlefs.bin"));
if (retFS == HTTP_UPDATE_OK) { //если FS обновилась успешно
SerialPrint("I", "Update", "LittleFS upgrade done!");
ret = true;
}
return ret;
}
bool upgradeBuild() {
WiFiClient wifiClient;
bool ret = false;
Serial.println("Start upgrade BUILD, please wait...");
ESPhttpUpdate.rebootOnUpdate(false);
t_httpUpdate_return retBuild = ESPhttpUpdate.update(wifiClient, F("http://95.128.182.133/projects/iotmanager/esp8266/firmware.bin"));
if (retBuild == HTTP_UPDATE_OK) { //если BUILD обновился успешно
SerialPrint("I", "Update", "BUILD upgrade done!");
ret = true;
}
return ret;
}
void restartEsp() {
Serial.println("Restart ESP....");
delay(1000);
ESP.restart();
}
//void upgrade_firmware() {
// String scanerioBackup, configBackup, setupBackup;
//
// scanerioBackup = readFile(String(DEVICE_SCENARIO_FILE), 4096);
// configBackup = readFile(String(DEVICE_CONFIG_FILE), 4096);
// setupBackup = configSetupJson;
//
// SerialPrint("I","module","update data");
// WiFiClient wifiClient;
//#ifdef ESP8266
// ESPhttpUpdate.rebootOnUpdate(false);
// t_httpUpdate_return ret = ESPhttpUpdate.updateSpiffs(wifiClient, F("http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"));
//#else
// httpUpdate.rebootOnUpdate(false);
// t_httpUpdate_return ret = httpUpdate.updateSpiffs(client_for_upgrade, F("http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.spiffs.bin"));
//#endif
// if (ret == HTTP_UPDATE_OK) {
// writeFile(String(DEVICE_SCENARIO_FILE), scanerioBackup);
// writeFile(String(DEVICE_CONFIG_FILE), configBackup);
// writeFile("config.json", setupBackup);
//
// saveConfig();
//
// SerialPrint("I","module","done!");
// } else {
// SerialPrint("[E]","module","on data");
// return;
// }
//
// //Serial.println("update firmware");
//#ifdef ESP8266
// ret = ESPhttpUpdate.update(wifiClient, F("http://91.204.228.124:1100/update/esp8266/esp32-esp8266_iot-manager_modules_firmware.ino.bin"));
//#else
// ret = httpUpdate.update(client_for_upgrade, "http://91.204.228.124:1100/update/esp32/esp32-esp8266_iot-manager_modules_firmware.ino.bin");
//#endif
// if (ret == HTTP_UPDATE_OK) {
// SerialPrint("I","module","done! restart...");
// ESP.restart();
// } else {
// SerialPrint("[E]","module","on firmware");
// }
//}

View File

@@ -3,7 +3,7 @@
#include "Global.h" #include "Global.h"
void SerialPrint(String errorLevel, String module, String msg) { void SerialPrint(String errorLevel, String module, String msg) {
if (module == "Stat") { //if (module == "Stat" || module == "Update") {
Serial.println(prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg); Serial.println(prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg);
} //}
} }

View File

@@ -63,7 +63,7 @@ String addNewDevice() {
//============================================== //==============================================
jsonWriteStr(json, "uniqueId", mac); jsonWriteStr(json, "uniqueId", mac);
jsonWriteStr(json, "name", FIRMWARE_NAME); jsonWriteStr(json, "name", FIRMWARE_NAME);
jsonWriteStr(json, "model", FIRMWARE_VERSION); jsonWriteInt(json, "model", FIRMWARE_VERSION);
//============================================== //==============================================
http.begin(client, F("http://95.128.182.133:8082/api/devices/")); http.begin(client, F("http://95.128.182.133:8082/api/devices/"));
http.setAuthorization("admin", "admin"); http.setAuthorization("admin", "admin");

View File

@@ -1,10 +1,9 @@
#include "Web.h" #include "Web.h"
#include "ItemsList.h"
#include "Class/NotAsinc.h"
#include "Global.h" #include "Global.h"
#include "Init.h" #include "Init.h"
#include "Class/NotAsinc.h" #include "ItemsList.h"
bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) { bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) {
if (request->hasArg("preset")) { if (request->hasArg("preset")) {
@@ -28,7 +27,6 @@ void web_init() {
}); });
server.on("/set", HTTP_GET, [](AsyncWebServerRequest* request) { server.on("/set", HTTP_GET, [](AsyncWebServerRequest* request) {
//==============================presets=========================================================================================================== //==============================presets===========================================================================================================
//uint8_t preset; //uint8_t preset;
//if (parseRequestForPreset(request, preset)) { //if (parseRequestForPreset(request, preset)) {
@@ -262,30 +260,26 @@ void web_init() {
*/ */
server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) { server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) {
myNotAsincActions->make(do_GETLASTVERSION); myNotAsincActions->make(do_GETLASTVERSION);
SerialPrint("I","Web","firmware version: " + lastVersion); SerialPrint("I", "Update", "firmware version: " + String(lastVersion));
if (!FLASH_4MB) {
lastVersion = "less";
} else if (isNetworkActive()) {
lastVersion = "nowifi";
}
String msg = ""; String msg = "";
if (lastVersion == FIRMWARE_VERSION) { if (lastVersion == FIRMWARE_VERSION) {
msg = F("Актуальная версия прошивки уже установлена."); msg = F("Актуальная версия прошивки уже установлена.");
} else if (lastVersion != FIRMWARE_VERSION) { } else if (lastVersion > FIRMWARE_VERSION) {
msg = F("Новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/'; }, 120000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>"); msg = F("Новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/'; }, 120000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
} else if (lastVersion == "error") { } else if (lastVersion == -1) {
msg = F("Cервер не найден. Попробуйте повторить позже..."); msg = F("Cервер не найден. Попробуйте повторить позже...");
} else if (lastVersion == "") { } else if (lastVersion == -2) {
msg = F("Нажмите на кнопку \"обновить прошивку\" повторно...");
} else if (lastVersion == "less") {
msg = F("Обновление \"по воздуху\" не поддерживается!");
} else if (lastVersion == "nowifi") {
msg = F("Устройство не подключено к роутеру!"); msg = F("Устройство не подключено к роутеру!");
} else if (lastVersion == "notsupported") {
msg = F("Обновление возможно только через usb!");
} }
// else if (lastVersion == "") {
//msg = F("Нажмите на кнопку \"обновить прошивку\" повторно...");
//} else if (lastVersion == "less") {
//msg = F("Обновление \"по воздуху\" не поддерживается!");
//} else if (lastVersion == "notsupported") {
// msg = F("Обновление возможно только через usb!");
//}
String tmp = "{}"; String tmp = "{}";
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + msg); jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + msg);
jsonWriteStr(tmp, "class", "pop-up"); jsonWriteStr(tmp, "class", "pop-up");
@@ -296,13 +290,14 @@ void web_init() {
* Upgrade * Upgrade
*/ */
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) { server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) {
myNotAsincActions->make(do_UPGRADE);; myNotAsincActions->make(do_UPGRADE);
;
request->send(200, "text/html"); request->send(200, "text/html");
}); });
} }
void setConfigParam(const char* param, const String& value) { void setConfigParam(const char* param, const String& value) {
SerialPrint("I","Web","set " + String(param) + ": " + value); SerialPrint("I", "Web", "set " + String(param) + ": " + value);
jsonWriteStr(configSetupJson, param, value); jsonWriteStr(configSetupJson, param, value);
saveConfig(); saveConfig();
} }