mirror of
https://github.com/IoTManagerProject/IoTManager.git
synced 2026-03-28 07:02:17 +03:00
recovery
This commit is contained in:
183
src/Utils/FileUtils.cpp
Normal file
183
src/Utils/FileUtils.cpp
Normal file
@@ -0,0 +1,183 @@
|
||||
#include "Utils/FileUtils.h"
|
||||
|
||||
#include "FileSystem.h"
|
||||
#include "Utils/StringUtils.h"
|
||||
#include "Utils\SerialPrint.h"
|
||||
|
||||
const String filepath(const String& filename) {
|
||||
return filename.startsWith("/") ? filename : "/" + filename;
|
||||
}
|
||||
|
||||
bool fileSystemInit() {
|
||||
if (!FileFS.begin()) {
|
||||
SerialPrint("E", F("FS"), F("FS Init ERROR, may be FS was not flashed"));
|
||||
return false;
|
||||
}
|
||||
SerialPrint("I", F("FS"), F("FS Init completed"));
|
||||
return true;
|
||||
}
|
||||
|
||||
void removeFile(const String& filename) {
|
||||
String path = filepath(filename);
|
||||
if (FileFS.exists(path)) {
|
||||
if (!FileFS.remove(path)) {
|
||||
SerialPrint("I", "Files", "remove " + path);
|
||||
}
|
||||
} else {
|
||||
SerialPrint("E", "Files", "not exist" + path);
|
||||
}
|
||||
}
|
||||
|
||||
File seekFile(const String& filename, size_t position) {
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "r");
|
||||
if (!file) {
|
||||
SerialPrint("[E]", "Files", "open " + path);
|
||||
}
|
||||
// поставим курсор в начало файла
|
||||
file.seek(position, SeekSet);
|
||||
return file;
|
||||
}
|
||||
|
||||
const String readFileString(const String& filename, const String& to_find) {
|
||||
String path = filepath(filename);
|
||||
String res = "failed";
|
||||
auto file = FileFS.open(path, "r");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
if (file.find(to_find.c_str())) {
|
||||
res = file.readStringUntil('\n');
|
||||
}
|
||||
file.close();
|
||||
return res;
|
||||
}
|
||||
|
||||
const String addFileLn(const String& filename, const String& str) {
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "a");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
file.println(str);
|
||||
file.close();
|
||||
return "sucсess";
|
||||
}
|
||||
|
||||
const String addFile(const String& filename, const String& str) {
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "a");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
file.print(str);
|
||||
file.close();
|
||||
return "sucсess";
|
||||
}
|
||||
|
||||
bool copyFile(const String& src, const String& dst, bool overwrite) {
|
||||
String srcPath = filepath(src);
|
||||
String dstPath = filepath(dst);
|
||||
SerialPrint("I", "Files", "copy " + srcPath + " to " + dstPath);
|
||||
if (!FileFS.exists(srcPath)) {
|
||||
SerialPrint("[E]", "Files", "not exist: " + srcPath);
|
||||
return false;
|
||||
}
|
||||
if (FileFS.exists(dstPath)) {
|
||||
if (!overwrite) {
|
||||
SerialPrint("[E]", "Files", "already exist: " + dstPath);
|
||||
return false;
|
||||
}
|
||||
FileFS.remove(dstPath);
|
||||
}
|
||||
auto srcFile = FileFS.open(srcPath, "r");
|
||||
auto dstFile = FileFS.open(dstPath, "w");
|
||||
|
||||
uint8_t buf[512];
|
||||
while (srcFile.available()) {
|
||||
size_t len = srcFile.read(buf, 512);
|
||||
dstFile.write(buf, len);
|
||||
}
|
||||
srcFile.close();
|
||||
dstFile.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
const String writeFile(const String& filename, const String& str) {
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "w");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
file.print(str);
|
||||
file.close();
|
||||
return "sucсess";
|
||||
}
|
||||
|
||||
const String readFile(const String& filename, size_t max_size) {
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "r");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
size_t size = file.size();
|
||||
if (size > max_size) {
|
||||
file.close();
|
||||
return "large";
|
||||
}
|
||||
String temp = file.readString();
|
||||
file.close();
|
||||
return temp;
|
||||
}
|
||||
|
||||
size_t countLines(const String filename) {
|
||||
size_t cnt = -1;
|
||||
String path = filepath(filename);
|
||||
auto file = FileFS.open(path, "r");
|
||||
if (!file) {
|
||||
return cnt;
|
||||
}
|
||||
file.seek(0, SeekSet);
|
||||
size_t size = file.size();
|
||||
size_t psn;
|
||||
do {
|
||||
cnt++;
|
||||
file.readStringUntil('\n');
|
||||
psn = file.position();
|
||||
} while (psn < size);
|
||||
file.close();
|
||||
return cnt;
|
||||
}
|
||||
|
||||
size_t getFileSize(const String filename) {
|
||||
size_t size = -1;
|
||||
String filepath(filename);
|
||||
auto file = FileFS.open(filepath, "r");
|
||||
if (!file) {
|
||||
return size;
|
||||
}
|
||||
size = file.size();
|
||||
file.close();
|
||||
return size;
|
||||
}
|
||||
|
||||
const String getFSSizeInfo() {
|
||||
String res;
|
||||
#ifdef ESP8266
|
||||
FSInfo info;
|
||||
if (FileFS.info(info)) {
|
||||
res = prettyBytes(info.usedBytes) + " of " + prettyBytes(info.totalBytes);
|
||||
} else {
|
||||
res = "error";
|
||||
}
|
||||
#else
|
||||
res = prettyBytes(FileFS.usedBytes()) + " of " + prettyBytes(FileFS.totalBytes());
|
||||
#endif
|
||||
return res;
|
||||
}
|
||||
|
||||
const String getConfigFile(uint8_t preset, ConfigType_t type) {
|
||||
char buf[64];
|
||||
sprintf(buf, "/conf/%s%03d.txt", (type == CT_CONFIG) ? "c" : "s", preset);
|
||||
return String(buf);
|
||||
}
|
||||
60
src/Utils/JsonUtils.cpp
Normal file
60
src/Utils/JsonUtils.cpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#include "Utils/JsonUtils.h"
|
||||
#include "Utils/FileUtils.h"
|
||||
#include "Global.h"
|
||||
|
||||
String jsonReadStr(String& json, String name) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
return root[name].as<String>();
|
||||
}
|
||||
|
||||
boolean jsonReadBool(String& json, String name) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
return root[name].as<boolean>();
|
||||
}
|
||||
|
||||
int jsonReadInt(String& json, String name) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
return root[name];
|
||||
}
|
||||
|
||||
String jsonWriteStr(String& json, String name, String value) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
root[name] = value;
|
||||
json = "";
|
||||
root.printTo(json);
|
||||
return json;
|
||||
}
|
||||
|
||||
String jsonWriteBool(String& json, String name, boolean value) {
|
||||
return jsonWriteStr(json, name, value ? "1" : "0");
|
||||
}
|
||||
|
||||
String jsonWriteInt(String& json, String name, int value) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
root[name] = value;
|
||||
json = "";
|
||||
root.printTo(json);
|
||||
return json;
|
||||
}
|
||||
|
||||
String jsonWriteFloat(String& json, String name, float value) {
|
||||
DynamicJsonBuffer jsonBuffer;
|
||||
JsonObject& root = jsonBuffer.parseObject(json);
|
||||
root[name] = value;
|
||||
json = "";
|
||||
root.printTo(json);
|
||||
return json;
|
||||
}
|
||||
|
||||
void saveConfig() {
|
||||
writeFile(String("config.json"), configSetupJson);
|
||||
}
|
||||
|
||||
void saveStore() {
|
||||
writeFile(String("store.json"), configStoreJson);
|
||||
}
|
||||
9
src/Utils/SerialPrint.cpp
Normal file
9
src/Utils/SerialPrint.cpp
Normal file
@@ -0,0 +1,9 @@
|
||||
#include "Utils\SerialPrint.h"
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
void SerialPrint(String errorLevel, String module, String msg) {
|
||||
//if (module == "MySensor") {
|
||||
Serial.println(prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg);
|
||||
//}
|
||||
}
|
||||
142
src/Utils/StringUtils.cpp
Normal file
142
src/Utils/StringUtils.cpp
Normal file
@@ -0,0 +1,142 @@
|
||||
#include "Utils/StringUtils.h"
|
||||
|
||||
#include "Consts.h"
|
||||
|
||||
String selectToMarkerLast(String str, String found) {
|
||||
int p = str.lastIndexOf(found);
|
||||
return str.substring(p + found.length());
|
||||
}
|
||||
|
||||
String selectToMarker(String str, String found) {
|
||||
int p = str.indexOf(found);
|
||||
return str.substring(0, p);
|
||||
}
|
||||
|
||||
String extractInner(String str) {
|
||||
int p1 = str.indexOf("[");
|
||||
int p2 = str.indexOf("]");
|
||||
return str.substring(p1 + 1, p2);
|
||||
}
|
||||
|
||||
String deleteAfterDelimiter(String str, String found) {
|
||||
int p = str.indexOf(found);
|
||||
return str.substring(0, p);
|
||||
}
|
||||
|
||||
String deleteBeforeDelimiter(String str, String found) {
|
||||
int p = str.indexOf(found) + found.length();
|
||||
return str.substring(p);
|
||||
}
|
||||
|
||||
String deleteBeforeDelimiterTo(String str, String found) {
|
||||
int p = str.indexOf(found);
|
||||
return str.substring(p);
|
||||
}
|
||||
|
||||
String deleteToMarkerLast(String str, String found) {
|
||||
int p = str.lastIndexOf(found);
|
||||
return str.substring(0, p);
|
||||
}
|
||||
|
||||
String selectToMarkerPlus(String str, String found, int plus) {
|
||||
int p = str.indexOf(found);
|
||||
return str.substring(0, p + plus);
|
||||
}
|
||||
|
||||
String selectFromMarkerToMarker(String str, String tofind, int number) {
|
||||
if (str.indexOf(tofind) == -1) {
|
||||
return "not found";
|
||||
}
|
||||
str += tofind; // добавим для корректного поиска
|
||||
uint8_t i = 0; // Индекс перебора
|
||||
do {
|
||||
if (i == number) {
|
||||
// если индекс совпал с позицией
|
||||
return selectToMarker(str, tofind);
|
||||
}
|
||||
// отбросим проверенный блок до разделителя
|
||||
str = deleteBeforeDelimiter(str, tofind);
|
||||
i++;
|
||||
} while (str.length() != 0);
|
||||
|
||||
return "not found";
|
||||
}
|
||||
|
||||
uint8_t hexStringToUint8(String hex) {
|
||||
uint8_t tmp = strtol(hex.c_str(), NULL, 0);
|
||||
if (tmp >= 0x00 && tmp <= 0xFF) {
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
uint16_t hexStringToUint16(String hex) {
|
||||
uint16_t tmp = strtol(hex.c_str(), NULL, 0);
|
||||
if (tmp >= 0x0000 && tmp <= 0xFFFF) {
|
||||
return tmp;
|
||||
}
|
||||
}
|
||||
|
||||
size_t itemsCount2(String str, const String& separator) {
|
||||
// если строки поиск нет сразу выход
|
||||
if (str.indexOf(separator) == -1) {
|
||||
return 0;
|
||||
}
|
||||
// добавим для корректного поиска
|
||||
str += separator;
|
||||
size_t cnt = 0;
|
||||
while (str.length()) {
|
||||
// отбросим проверенный блок до разделителя
|
||||
str = deleteBeforeDelimiter(str, separator);
|
||||
cnt++;
|
||||
}
|
||||
return cnt;
|
||||
}
|
||||
|
||||
size_t itemsCount(String& str, const char* delim) {
|
||||
size_t cnt = 0;
|
||||
char* cstr = new char[str.length() + 1];
|
||||
strcpy(cstr, str.c_str());
|
||||
char* token;
|
||||
while ((token = strtok_r(cstr, delim, &cstr))) {
|
||||
cnt++;
|
||||
//printf("%s\n", token);
|
||||
}
|
||||
delete[] cstr;
|
||||
return cnt;
|
||||
}
|
||||
|
||||
char* stringToChar(String& str) {
|
||||
char* mychar = new char[str.length() + 1];
|
||||
strcpy(mychar, str.c_str());
|
||||
return mychar;
|
||||
}
|
||||
|
||||
boolean isDigitStr(const String& str) {
|
||||
for (size_t i = 0; i < str.length(); i++) {
|
||||
if (!isDigit(str.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return str.length();
|
||||
}
|
||||
|
||||
boolean isDigitDotCommaStr(const String& str) {
|
||||
for (size_t i = 0; i < str.length(); i++) {
|
||||
char latter = str.charAt(i);
|
||||
if (!isDigit(latter) && latter != '.' && latter != '-') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
String prettyBytes(size_t size) {
|
||||
if (size < 1024)
|
||||
return String(size) + "b";
|
||||
else if (size < (1024 * 1024))
|
||||
return String(size / 1024.0) + "kB";
|
||||
else if (size < (1024 * 1024 * 1024))
|
||||
return String(size / 1024.0 / 1024.0) + "MB";
|
||||
else
|
||||
return String(size / 1024.0 / 1024.0 / 1024.0) + "GB";
|
||||
}
|
||||
250
src/Utils/SysUtils.cpp
Normal file
250
src/Utils/SysUtils.cpp
Normal file
@@ -0,0 +1,250 @@
|
||||
#include "Utils/SysUtils.h"
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
|
||||
const String getUniqueId(const char* name) {
|
||||
return String(name) + getMacAddress();
|
||||
}
|
||||
|
||||
uint32_t ESP_getChipId(void) {
|
||||
#ifdef ESP32
|
||||
uint32_t id = 0;
|
||||
for (uint32_t i = 0; i < 17; i = i + 8) {
|
||||
id |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
|
||||
}
|
||||
return id;
|
||||
#else
|
||||
return ESP.getChipId();
|
||||
#endif
|
||||
}
|
||||
|
||||
uint32_t ESP_getFlashChipId(void) {
|
||||
#ifdef ESP32
|
||||
// Нет аналогичной (без доп.кода) функций в 32
|
||||
// надо использовать другой id - варианты есть
|
||||
return ESP_getChipId();
|
||||
#else
|
||||
return ESP.getFlashChipId();
|
||||
#endif
|
||||
}
|
||||
|
||||
const String getChipId() {
|
||||
return String(ESP_getChipId()) + "-" + String(ESP_getFlashChipId());
|
||||
}
|
||||
|
||||
void setChipId() {
|
||||
chipId = getChipId();
|
||||
SerialPrint("I", "System", "id: " + chipId);
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
static uint32_t total_memory = 52864;
|
||||
#else
|
||||
static uint32_t total_memory = ESP.getHeapSize();
|
||||
#endif
|
||||
|
||||
const String printMemoryStatus() {
|
||||
uint32_t free = ESP.getFreeHeap();
|
||||
uint32_t used = total_memory - free;
|
||||
uint32_t memory_load = (used * 100) / total_memory;
|
||||
char buf[64];
|
||||
sprintf(buf, "used: %d%% free: %s", memory_load, getHeapStats().c_str());
|
||||
return String(buf);
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
const String getHeapStats() {
|
||||
uint32_t free;
|
||||
uint16_t max;
|
||||
uint8_t frag;
|
||||
ESP.getHeapStats(&free, &max, &frag);
|
||||
String buf;
|
||||
buf += prettyBytes(free);
|
||||
buf += " frag: ";
|
||||
buf += frag;
|
||||
buf += '%';
|
||||
return buf;
|
||||
}
|
||||
#else
|
||||
const String getHeapStats() {
|
||||
String buf;
|
||||
buf = prettyBytes(ESP.getFreeHeap());
|
||||
return buf;
|
||||
}
|
||||
#endif
|
||||
|
||||
const String getMacAddress() {
|
||||
uint8_t mac[6];
|
||||
char buf[13] = {0};
|
||||
#if defined(ESP8266)
|
||||
WiFi.macAddress(mac);
|
||||
sprintf(buf, MACSTR, MAC2STR(mac));
|
||||
#else
|
||||
esp_read_mac(mac, ESP_MAC_WIFI_STA);
|
||||
sprintf(buf, MACSTR, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
|
||||
#endif
|
||||
return String(buf);
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
void setLedStatus(LedStatus_t status) {
|
||||
if (jsonReadBool(configSetupJson, "blink") == 1) {
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
switch (status) {
|
||||
case LED_OFF:
|
||||
noTone(LED_PIN);
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
break;
|
||||
case LED_ON:
|
||||
noTone(LED_PIN);
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
break;
|
||||
case LED_SLOW:
|
||||
tone(LED_PIN, 1);
|
||||
break;
|
||||
case LED_FAST:
|
||||
tone(LED_PIN, 20);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
void setLedStatus(LedStatus_t status) {
|
||||
if (jsonReadBool(configSetupJson, "blink") == 1) {
|
||||
pinMode(LED_PIN, OUTPUT);
|
||||
switch (status) {
|
||||
case LED_OFF:
|
||||
digitalWrite(LED_PIN, HIGH);
|
||||
break;
|
||||
case LED_ON:
|
||||
digitalWrite(LED_PIN, LOW);
|
||||
break;
|
||||
case LED_SLOW:
|
||||
break;
|
||||
case LED_FAST:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
//===================================================================
|
||||
/*
|
||||
void web_print (String text) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
jsonWriteStr(json, "test1", jsonReadStr(json, "test2"));
|
||||
jsonWriteStr(json, "test2", jsonReadStr(json, "test3"));
|
||||
jsonWriteStr(json, "test3", jsonReadStr(json, "test4"));
|
||||
jsonWriteStr(json, "test4", jsonReadStr(json, "test5"));
|
||||
jsonWriteStr(json, "test5", jsonReadStr(json, "test6"));
|
||||
|
||||
jsonWriteStr(json, "test6", GetTime() + " " + text);
|
||||
|
||||
ws.textAll(json);
|
||||
}
|
||||
}
|
||||
*/
|
||||
//===================================================================
|
||||
/*
|
||||
"socket": [
|
||||
"ws://{{ip}}/ws"
|
||||
],
|
||||
*/
|
||||
//===================================================================
|
||||
/*
|
||||
{
|
||||
"type": "h4",
|
||||
"title": "('{{build2}}'=='{{firmware_version}}'?'NEW':'OLD')"
|
||||
},
|
||||
*/
|
||||
//===================================================================
|
||||
/*
|
||||
{
|
||||
"type": "button",
|
||||
"title": "Конфигурация устройства",
|
||||
"socket": "test2",
|
||||
"class": "btn btn-block btn-primary"
|
||||
},
|
||||
{
|
||||
"type": "hr"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test1}}"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test2}}"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test3}}"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test4}}"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test5}}"
|
||||
},
|
||||
{
|
||||
"type": "h6",
|
||||
"title": "{{test6}}"
|
||||
},
|
||||
{
|
||||
"type": "hr"
|
||||
},
|
||||
*/
|
||||
//===================================================================
|
||||
|
||||
/*
|
||||
String getResetReason(uint8_t core) {
|
||||
int reason = rtc_get_reset_reason(core);
|
||||
switch (reason) {
|
||||
case 1 : return "Power on"; break; //Vbat power on reset
|
||||
case 3 : return "Software reset digital core"; break; //Software reset digital core
|
||||
case 4 : return "Legacy watch dog reset digital core"; break; //Legacy watch dog reset digital core
|
||||
case 5 : return "Deep Sleep reset digital core"; break; //Deep Sleep reset digital core
|
||||
case 6 : return "Reset by SLC module, reset digital core"; break; //Reset by SLC module, reset digital core
|
||||
case 7 : return "Timer Group0 Watch dog reset digital core"; break; //Timer Group0 Watch dog reset digital core
|
||||
case 8 : return "Timer Group1 Watch dog reset digital core"; break; //Timer Group1 Watch dog reset digital core
|
||||
case 9 : return "RTC Watch dog Reset digital core"; break; //
|
||||
case 10 : return "Instrusion tested to reset CPU"; break;
|
||||
case 11 : return "Time Group reset CPU"; break;
|
||||
case 12 : return "Software reset CPU"; break;
|
||||
case 13 : return "RTC Watch dog Reset CPU"; break;
|
||||
case 14 : return "for APP CPU, reseted by PRO CPU"; break;
|
||||
case 15 : return "Reset when the vdd voltage is not stable"; break;
|
||||
case 16 : return "RTC Watch dog reset digital core and rtc module"; break;
|
||||
default : return "NO_MEAN";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
String EspClass::getResetReason(void) {
|
||||
char buff[32];
|
||||
if (resetInfo.reason == REASON_DEFAULT_RST) { // normal startup by power on
|
||||
strcpy_P(buff, PSTR("Power on"));
|
||||
} else if (resetInfo.reason == REASON_WDT_RST) { // hardware watch dog reset
|
||||
strcpy_P(buff, PSTR("Hardware Watchdog"));
|
||||
} else if (resetInfo.reason == REASON_EXCEPTION_RST) { // exception reset, GPIO status won’t change
|
||||
strcpy_P(buff, PSTR("Exception"));
|
||||
} else if (resetInfo.reason == REASON_SOFT_WDT_RST) { // software watch dog reset, GPIO status won’t change
|
||||
strcpy_P(buff, PSTR("Software Watchdog"));
|
||||
} else if (resetInfo.reason == REASON_SOFT_RESTART) { // software restart ,system_restart , GPIO status won’t change
|
||||
strcpy_P(buff, PSTR("Software/System restart"));
|
||||
} else if (resetInfo.reason == REASON_DEEP_SLEEP_AWAKE) { // wake up from deep-sleep
|
||||
strcpy_P(buff, PSTR("Deep-Sleep Wake"));
|
||||
} else if (resetInfo.reason == REASON_EXT_SYS_RST) { // external system reset
|
||||
strcpy_P(buff, PSTR("External System"));
|
||||
} else {
|
||||
strcpy_P(buff, PSTR("Unknown"));
|
||||
}
|
||||
return String(buff);
|
||||
}
|
||||
*/
|
||||
237
src/Utils/TimeUtils.cpp
Normal file
237
src/Utils/TimeUtils.cpp
Normal file
@@ -0,0 +1,237 @@
|
||||
#include "Utils/TimeUtils.h"
|
||||
#include "Global.h"
|
||||
#include "Utils/StringUtils.h"
|
||||
|
||||
static const uint8_t days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
|
||||
|
||||
//static const char* week_days[7] = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
|
||||
|
||||
// String getTimeUnix() {
|
||||
// time_t t;
|
||||
// struct tm* tm;
|
||||
|
||||
// t = time(NULL);
|
||||
// tm = localtime(&t);
|
||||
// Serial.printf("%04d/%02d/%02d(%s) %02d:%02d:%02d\n",
|
||||
// tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, week_days[tm->tm_wday],
|
||||
// tm->tm_hour, tm->tm_min, tm->tm_sec);
|
||||
// delay(1000);
|
||||
// time_t now = time(nullptr);
|
||||
// if (now < 30000) {
|
||||
// return "failed";
|
||||
// }
|
||||
// return String(now);
|
||||
// }
|
||||
|
||||
// String getTime() {
|
||||
// time_t now = time(nullptr);
|
||||
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
|
||||
// now = now + zone;
|
||||
// String Time = ""; // Строка для результатов времени
|
||||
// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
|
||||
// int i = Time.indexOf(":"); //Ишем позицию первого символа :
|
||||
// Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после
|
||||
// return Time; // Возврашаем полученное время
|
||||
// }
|
||||
|
||||
// String getTimeWOsec() {
|
||||
// time_t now = time(nullptr);
|
||||
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
|
||||
// now = now + zone;
|
||||
// String Time = ""; // Строка для результатов времени
|
||||
// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
|
||||
// int i = Time.indexOf(":"); //Ишем позицию первого символа :
|
||||
// Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после
|
||||
// return Time; // Возврашаем полученное время
|
||||
// }
|
||||
|
||||
// String getDate() {
|
||||
// time_t now = time(nullptr);
|
||||
// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt();
|
||||
// now = now + zone;
|
||||
// String Data = ""; // Строка для результатов времени
|
||||
// Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017
|
||||
// Data.replace("\n", "");
|
||||
// uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел
|
||||
// String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел
|
||||
// Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел
|
||||
// return Data; // Возврашаем полученную дату
|
||||
// }
|
||||
|
||||
// String getDateDigitalFormated() {
|
||||
// String date = getDate();
|
||||
|
||||
// date = deleteBeforeDelimiter(date, " ");
|
||||
|
||||
// date.replace("Jan", "01");
|
||||
// date.replace("Feb", "02");
|
||||
// date.replace("Mar", "03");
|
||||
// date.replace("Apr", "04");
|
||||
// date.replace("May", "05");
|
||||
// date.replace("Jun", "06");
|
||||
// date.replace("Jul", "07");
|
||||
// date.replace("Aug", "08");
|
||||
// date.replace("Sep", "09");
|
||||
// date.replace("Oct", "10");
|
||||
// date.replace("Nov", "11");
|
||||
// date.replace("Dec", "12");
|
||||
|
||||
// String month = date.substring(0, 2);
|
||||
// String day = date.substring(3, 5);
|
||||
// String year = date.substring(8, 10);
|
||||
|
||||
// String out = day;
|
||||
// out += ".";
|
||||
// out += month;
|
||||
// out += ".";
|
||||
// out += year;
|
||||
|
||||
// return out;
|
||||
// }
|
||||
|
||||
// int timeToMin(String Time) {
|
||||
// //"00:00:00" время в секунды
|
||||
// long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах
|
||||
// Time = deleteBeforeDelimiter(Time, ":"); // Теперь здесь минуты секунды
|
||||
// min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут
|
||||
// return min;
|
||||
// }
|
||||
|
||||
static const char* TIME_FORMAT PROGMEM = "%02d:%02d:%02d";
|
||||
static const char* TIME_FORMAT_WITH_DAYS PROGMEM = "%dd %02d:%02d";
|
||||
|
||||
const String prettySeconds(unsigned long time_s) {
|
||||
unsigned long tmp = time_s;
|
||||
unsigned long seconds;
|
||||
unsigned long minutes;
|
||||
unsigned long hours;
|
||||
unsigned long days;
|
||||
seconds = tmp % 60;
|
||||
tmp = tmp / 60;
|
||||
|
||||
minutes = tmp % 60;
|
||||
tmp = tmp / 60;
|
||||
|
||||
hours = tmp % 24;
|
||||
days = tmp / 24;
|
||||
|
||||
char buf[32];
|
||||
|
||||
if (days) {
|
||||
sprintf_P(buf, TIME_FORMAT_WITH_DAYS, days, hours, minutes, seconds);
|
||||
}
|
||||
else {
|
||||
sprintf_P(buf, TIME_FORMAT, hours, minutes, seconds);
|
||||
}
|
||||
return String(buf);
|
||||
}
|
||||
|
||||
const String prettyMillis(unsigned long time_ms) {
|
||||
return prettySeconds(time_ms / 1000);
|
||||
}
|
||||
|
||||
unsigned long millis_since(unsigned long sinse) {
|
||||
return millis_passed(sinse, millis());
|
||||
}
|
||||
|
||||
unsigned long millis_passed(unsigned long start, unsigned long finish) {
|
||||
unsigned long result = 0;
|
||||
if (start <= finish) {
|
||||
unsigned long passed = finish - start;
|
||||
if (passed <= __LONG_MAX__) {
|
||||
result = static_cast<long>(passed);
|
||||
}
|
||||
else {
|
||||
result = static_cast<long>((__LONG_MAX__ - finish) + start + 1u);
|
||||
}
|
||||
}
|
||||
else {
|
||||
unsigned long passed = start - finish;
|
||||
if (passed <= __LONG_MAX__) {
|
||||
result = static_cast<long>(passed);
|
||||
result = -1 * result;
|
||||
}
|
||||
else {
|
||||
result = static_cast<long>((__LONG_MAX__ - start) + finish + 1u);
|
||||
result = -1 * result;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
int getOffsetInSeconds(int timezone) {
|
||||
return getOffsetInMinutes(timezone) * ONE_MINUTE_s;
|
||||
}
|
||||
|
||||
int getOffsetInMinutes(int timezone) {
|
||||
return timezone * ONE_HOUR_m;
|
||||
}
|
||||
|
||||
void breakEpochToTime(unsigned long epoch, Time_t& tm) {
|
||||
// break the given time_input into time components
|
||||
// this is a more compact version of the C library localtime function
|
||||
|
||||
unsigned long time = epoch;
|
||||
tm.second = time % 60;
|
||||
time /= 60; // now it is minutes
|
||||
tm.minute = time % 60;
|
||||
time /= 60; // now it is hours
|
||||
tm.hour = time % 24;
|
||||
time /= 24; // now it is days
|
||||
tm.days = time;
|
||||
tm.day_of_week = ((time + 4) % 7) + 1; // Sunday is day 1
|
||||
|
||||
uint8_t year = 0;
|
||||
unsigned long days = 0;
|
||||
|
||||
while ((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
|
||||
year++;
|
||||
}
|
||||
tm.year = year - 30;
|
||||
|
||||
days -= LEAP_YEAR(year) ? 366 : 365;
|
||||
time -= days; // now it is days in this year, starting at 0
|
||||
tm.day_of_year = time;
|
||||
|
||||
uint8_t month;
|
||||
uint8_t month_length;
|
||||
for (month = 0; month < 12; month++) {
|
||||
if (1 == month) { // february
|
||||
if (LEAP_YEAR(year)) {
|
||||
month_length = 29;
|
||||
}
|
||||
else {
|
||||
month_length = 28;
|
||||
}
|
||||
}
|
||||
else {
|
||||
month_length = days_in_month[month];
|
||||
}
|
||||
|
||||
if (time >= month_length) {
|
||||
time -= month_length;
|
||||
}
|
||||
else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tm.month = month + 1; // jan is month 1
|
||||
tm.day_of_month = time + 1; // day of month
|
||||
tm.valid = (epoch > MIN_DATETIME);
|
||||
}
|
||||
|
||||
void timeInit() {
|
||||
ts.add(
|
||||
TIME, 1000, [&](void*) {
|
||||
String timenow = timeNow->getTimeWOsec();
|
||||
static String prevTime;
|
||||
if (prevTime != timenow) {
|
||||
prevTime = timenow;
|
||||
jsonWriteStr(configLiveJson, "timenow", timenow);
|
||||
eventGen2("timenow", timenow);
|
||||
SerialPrint("I", F("NTP"), timenow);
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
SerialPrint("I", F("NTP"), F("Handle time init"));
|
||||
}
|
||||
87
src/Utils/WebUtils.cpp
Normal file
87
src/Utils/WebUtils.cpp
Normal file
@@ -0,0 +1,87 @@
|
||||
#include "Utils/WebUtils.h"
|
||||
|
||||
#include "ESPAsyncWebServer.h"
|
||||
|
||||
String getURL(const String& urls) {
|
||||
String res = "";
|
||||
HTTPClient http;
|
||||
http.begin(espClient, urls);
|
||||
int httpCode = http.GET();
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
res = http.getString();
|
||||
} else {
|
||||
res = "error";
|
||||
}
|
||||
http.end();
|
||||
return res;
|
||||
}
|
||||
|
||||
const String getMethodName(AsyncWebServerRequest* request) {
|
||||
String res = F("UNKNOWN");
|
||||
if (request->method() == HTTP_GET)
|
||||
res = F("GET");
|
||||
else if (request->method() == HTTP_POST)
|
||||
res = F("POST");
|
||||
else if (request->method() == HTTP_DELETE)
|
||||
res = F("DELETE");
|
||||
else if (request->method() == HTTP_PUT)
|
||||
res = F("PUT");
|
||||
else if (request->method() == HTTP_PATCH)
|
||||
res = F("PATCH");
|
||||
else if (request->method() == HTTP_HEAD)
|
||||
res = F("HEAD");
|
||||
else if (request->method() == HTTP_OPTIONS)
|
||||
res = F("OPTIONS");
|
||||
return res;
|
||||
}
|
||||
|
||||
const String getRequestInfo(AsyncWebServerRequest* request) {
|
||||
String res = getMethodName(request);
|
||||
res += ' ';
|
||||
res += "http://";
|
||||
res += request->host();
|
||||
res += request->url();
|
||||
res += '\n';
|
||||
if (request->contentLength()) {
|
||||
res += "content-type: ";
|
||||
res += request->contentType();
|
||||
res += " content-lenght: ";
|
||||
res += prettyBytes(request->contentLength());
|
||||
res += '\n';
|
||||
}
|
||||
|
||||
if (request->headers()) {
|
||||
res += "headers:\n";
|
||||
for (size_t i = 0; i < request->headers(); i++) {
|
||||
AsyncWebHeader* h = request->getHeader(i);
|
||||
res += h->name();
|
||||
res += '=';
|
||||
res += h->value();
|
||||
res += '\n';
|
||||
}
|
||||
}
|
||||
|
||||
if (request->params()) {
|
||||
res += "params:\n";
|
||||
for (size_t i = 0; i < request->params(); i++) {
|
||||
AsyncWebParameter* p = request->getParam(i);
|
||||
if (p->isFile()) {
|
||||
res += "FILE";
|
||||
} else if (p->isPost()) {
|
||||
res += "POST";
|
||||
} else {
|
||||
res += "GET";
|
||||
}
|
||||
res += ' ';
|
||||
res += p->name();
|
||||
res += ':';
|
||||
res += p->value();
|
||||
if (p->isFile()) {
|
||||
res += " size:";
|
||||
res += p->size();
|
||||
}
|
||||
res += '\n';
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
172
src/Utils/WiFiUtils.cpp
Normal file
172
src/Utils/WiFiUtils.cpp
Normal file
@@ -0,0 +1,172 @@
|
||||
#include "Utils/WiFiUtils.h"
|
||||
#include "FileSystem.h"
|
||||
|
||||
void routerConnect() {
|
||||
WiFi.setAutoConnect(false);
|
||||
WiFi.persistent(false);
|
||||
|
||||
setLedStatus(LED_SLOW);
|
||||
WiFi.mode(WIFI_STA);
|
||||
byte tries = 20;
|
||||
|
||||
String _ssid = jsonReadStr(configSetupJson, "routerssid");
|
||||
String _password = jsonReadStr(configSetupJson, "routerpass");
|
||||
|
||||
if (_ssid == "" && _password == "") {
|
||||
WiFi.begin();
|
||||
} else {
|
||||
WiFi.begin(_ssid.c_str(), _password.c_str());
|
||||
#ifdef ESP32
|
||||
WiFi.setTxPower(WIFI_POWER_19_5dBm);
|
||||
#else
|
||||
WiFi.setOutputPower(20.5);
|
||||
#endif
|
||||
SerialPrint("I", "WIFI", "ssid: " + _ssid);
|
||||
}
|
||||
|
||||
while (--tries && WiFi.status() != WL_CONNECTED) {
|
||||
if (WiFi.status() == WL_CONNECT_FAILED) {
|
||||
SerialPrint("E", "WIFI", "password is not correct");
|
||||
tries = 1;
|
||||
jsonWriteInt(configOptionJson, "pass_status", 1);
|
||||
}
|
||||
Serial.print(".");
|
||||
delay(1000);
|
||||
}
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
Serial.println("");
|
||||
startAPMode();
|
||||
} else {
|
||||
Serial.println("");
|
||||
SerialPrint("I", "WIFI", "http://" + WiFi.localIP().toString());
|
||||
jsonWriteStr(configSetupJson, "ip", WiFi.localIP().toString());
|
||||
setLedStatus(LED_OFF);
|
||||
mqttInit();
|
||||
}
|
||||
SerialPrint("I", F("WIFI"), F("Network Init"));
|
||||
}
|
||||
|
||||
bool startAPMode() {
|
||||
setLedStatus(LED_ON);
|
||||
SerialPrint("I", "WIFI", "AP Mode");
|
||||
|
||||
WiFi.disconnect();
|
||||
WiFi.mode(WIFI_AP);
|
||||
|
||||
String _ssidAP = jsonReadStr(configSetupJson, "apssid");
|
||||
String _passwordAP = jsonReadStr(configSetupJson, "appass");
|
||||
|
||||
WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str());
|
||||
IPAddress myIP = WiFi.softAPIP();
|
||||
|
||||
SerialPrint("I", "WIFI", "AP IP: " + myIP.toString());
|
||||
jsonWriteStr(configSetupJson, "ip", myIP.toString());
|
||||
|
||||
//if (jsonReadInt(configOptionJson, "pass_status") != 1) {
|
||||
ts.add(
|
||||
WIFI_SCAN, 10 * 1000, [&](void*) {
|
||||
String sta_ssid = jsonReadStr(configSetupJson, "routerssid");
|
||||
|
||||
SerialPrint("I", "WIFI", "scanning for " + sta_ssid);
|
||||
|
||||
if (RouterFind(sta_ssid)) {
|
||||
ts.remove(WIFI_SCAN);
|
||||
WiFi.scanDelete();
|
||||
routerConnect();
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean RouterFind(String ssid) {
|
||||
bool res = false;
|
||||
int n = WiFi.scanComplete();
|
||||
SerialPrint("I", "WIFI", "scan result: " + String(n, DEC));
|
||||
|
||||
if (n == -2) { //Сканирование не было запущено, запускаем
|
||||
SerialPrint("I", "WIFI", "start scanning");
|
||||
WiFi.scanNetworks(true, false); //async, show_hidden
|
||||
}
|
||||
|
||||
else if (n == -1) { //Сканирование все еще выполняется
|
||||
SerialPrint("I", "WIFI", "scanning in progress");
|
||||
}
|
||||
|
||||
else if (n == 0) { //ни одна сеть не найдена
|
||||
SerialPrint("I", "WIFI", "no networks found");
|
||||
WiFi.scanNetworks(true, false);
|
||||
}
|
||||
|
||||
else if (n > 0) {
|
||||
for (int8_t i = 0; i < n; i++) {
|
||||
if (WiFi.SSID(i) == ssid) {
|
||||
res = true;
|
||||
}
|
||||
SerialPrint("I", "WIFI", (res ? "*" : "") + String(i, DEC) + ") " + WiFi.SSID(i));
|
||||
}
|
||||
}
|
||||
WiFi.scanDelete();
|
||||
return res;
|
||||
}
|
||||
|
||||
boolean isNetworkActive() {
|
||||
return WiFi.status() == WL_CONNECTED;
|
||||
}
|
||||
|
||||
uint8_t RSSIquality() {
|
||||
uint8_t res = 0;
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
int rssi = WiFi.RSSI();
|
||||
if (rssi >= -50) {
|
||||
res = 6; //"Excellent";
|
||||
} else if (rssi < -50 && rssi >= -60) {
|
||||
res = 5; //"Very good";
|
||||
} else if (rssi < -60 && rssi >= -70) {
|
||||
res = 4; //"Good";
|
||||
} else if (rssi < -70 && rssi >= -80) {
|
||||
res = 3; //"Low";
|
||||
} else if (rssi < -80 && rssi > -100) {
|
||||
res = 2; //"Very low";
|
||||
} else if (rssi <= -100) {
|
||||
res = 1; //"No signal";
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void wifiSignalInit() {
|
||||
ts.add(
|
||||
SYGNAL, 1000 * 60, [&](void*) {
|
||||
SerialPrint("I", "System", printMemoryStatus());
|
||||
|
||||
getFSInfo();
|
||||
|
||||
switch (RSSIquality()) {
|
||||
case 0:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='red'>не подключено к роутеру</font>"));
|
||||
break;
|
||||
case 1:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='red'>нет сигнала</font>"));
|
||||
break;
|
||||
case 2:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='red'>очень низкий</font>"));
|
||||
break;
|
||||
case 3:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='orange'>низкий</font>"));
|
||||
break;
|
||||
case 4:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='green'>хороший</font>"));
|
||||
break;
|
||||
case 5:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='green'>очень хороший</font>"));
|
||||
break;
|
||||
case 6:
|
||||
jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: <font color='green'>отличный</font>"));
|
||||
break;
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
316
src/Utils/statUtils.cpp
Normal file
316
src/Utils/statUtils.cpp
Normal file
@@ -0,0 +1,316 @@
|
||||
#include "Utils/StatUtils.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <EEPROM.h>
|
||||
|
||||
#include "Global.h"
|
||||
#include "ItemsList.h"
|
||||
|
||||
#ifdef ESP32
|
||||
#include <rom/rtc.h>
|
||||
#endif
|
||||
|
||||
String ESP_getResetReason(void);
|
||||
|
||||
void initSt() {
|
||||
addNewDevice();
|
||||
decide();
|
||||
if (TELEMETRY_UPDATE_INTERVAL_MIN) {
|
||||
ts.add(
|
||||
STATISTICS, TELEMETRY_UPDATE_INTERVAL_MIN * 60000, [&](void*) {
|
||||
static bool secondTime = false;
|
||||
if (secondTime) getNextNumber("totalhrs.txt");
|
||||
secondTime = true;
|
||||
updateDeviceStatus();
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
SerialPrint("I", F("Stat"), F("Stat Init"));
|
||||
}
|
||||
|
||||
void decide() {
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
uint8_t cnt = getNextNumber("stat.txt");
|
||||
SerialPrint("I", "Stat", "Total resets number: " + String(cnt));
|
||||
if (cnt <= 3) {
|
||||
Serial.println("(get)");
|
||||
getPsn();
|
||||
}
|
||||
else {
|
||||
if (cnt % 5) {
|
||||
Serial.println("(skip)");
|
||||
}
|
||||
else {
|
||||
Serial.println("(get)");
|
||||
getPsn();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void getPsn() {
|
||||
String res = getURL(F("http://ipinfo.io/?token=c60f88583ad1a4"));
|
||||
if (res != "") {
|
||||
String line = jsonReadStr(res, "loc");
|
||||
String lat = selectToMarker(line, ",");
|
||||
String lon = deleteBeforeDelimiter(line, ",");
|
||||
String geo = jsonReadStr(res, "city") + ", " + jsonReadStr(res, "country") + ", " + jsonReadStr(res, "region");
|
||||
updateDevicePsn(lat, lon, "0", geo);
|
||||
}
|
||||
}
|
||||
|
||||
String addNewDevice() {
|
||||
String ret;
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
WiFiClient client;
|
||||
HTTPClient http;
|
||||
String json = "{}";
|
||||
String mac = WiFi.macAddress().c_str();
|
||||
//==============================================
|
||||
jsonWriteStr(json, "uniqueId", mac);
|
||||
jsonWriteStr(json, "name", FIRMWARE_NAME);
|
||||
jsonWriteStr(json, "model", getChipId());
|
||||
//==============================================
|
||||
http.begin(client, serverIP + F(":8082/api/devices/"));
|
||||
http.setAuthorization("admin", "admin");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
int httpCode = http.POST(json);
|
||||
if (httpCode > 0) {
|
||||
ret = httpCode;
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
String payload = http.getString();
|
||||
ret += " " + payload;
|
||||
//saveId("statid.txt", jsonReadInt(payload, "id"));
|
||||
}
|
||||
}
|
||||
else {
|
||||
ret = http.errorToString(httpCode).c_str();
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
SerialPrint("I", "Stat", "New device registaration: " + ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
String updateDevicePsn(String lat, String lon, String accur, String geo) {
|
||||
String ret;
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
float latfl = lat.toFloat();
|
||||
float lonfl = lon.toFloat();
|
||||
randomSeed(micros());
|
||||
float c = random(2, 9);
|
||||
if (c > 5) {
|
||||
latfl = latfl + (c / 100);
|
||||
lonfl = lonfl + (c / 100);
|
||||
}
|
||||
else {
|
||||
latfl = latfl - (c / 100);
|
||||
lonfl = lonfl - (c / 100);
|
||||
}
|
||||
WiFiClient client;
|
||||
HTTPClient http;
|
||||
http.begin(client, serverIP + F(":5055/"));
|
||||
http.setAuthorization("admin", "admin");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
String mac = WiFi.macAddress().c_str();
|
||||
int httpCode = http.POST("?id=" + mac +
|
||||
"&lat=" + String(latfl) +
|
||||
"&lon=" + String(lonfl) +
|
||||
"&accuracy=" + accur + "");
|
||||
if (httpCode > 0) {
|
||||
ret = httpCode;
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
String payload = http.getString();
|
||||
ret += " " + payload;
|
||||
}
|
||||
}
|
||||
else {
|
||||
ret = http.errorToString(httpCode).c_str();
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
SerialPrint("I", "Stat", "Update device psn: " + ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
String updateDeviceStatus() {
|
||||
String ret;
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
WiFiClient client;
|
||||
HTTPClient http;
|
||||
http.begin(client, serverIP + F(":5055/"));
|
||||
http.setAuthorization("admin", "admin");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
String mac = WiFi.macAddress().c_str();
|
||||
int httpCode = http.POST("?id=" + mac +
|
||||
"&resetReason=" + ESP_getResetReason() +
|
||||
"&uptime=" + timeNow->getUptime() +
|
||||
"&uptimeTotal=" + getUptimeTotal() +
|
||||
"&version=" + FIRMWARE_VERSION +
|
||||
"&resetsTotal=" + String(getCurrentNumber("stat.txt")) +
|
||||
"&heap=" + String(ESP.getFreeHeap()) + "");
|
||||
if (httpCode > 0) {
|
||||
ret = httpCode;
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
String payload = http.getString();
|
||||
ret += " " + payload;
|
||||
}
|
||||
}
|
||||
else {
|
||||
ret = http.errorToString(httpCode).c_str();
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
SerialPrint("I", "Stat", "Update device data: " + ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
String getUptimeTotal() {
|
||||
uint8_t hrs = getCurrentNumber("totalhrs.txt");
|
||||
String hrsStr = prettySeconds(hrs * 60 * 60);
|
||||
SerialPrint("I", "Stat", "Total running time: " + hrsStr);
|
||||
return hrsStr;
|
||||
}
|
||||
|
||||
uint8_t getNextNumber(String file) {
|
||||
uint8_t number = readFile(file, 100).toInt();
|
||||
number++;
|
||||
removeFile(file);
|
||||
addFile(file, String(number));
|
||||
return number;
|
||||
}
|
||||
|
||||
uint8_t getCurrentNumber(String file) {
|
||||
uint8_t number = readFile(file, 100).toInt();
|
||||
return number;
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
String ESP_getResetReason(void) {
|
||||
return ESP.getResetReason();
|
||||
}
|
||||
#else
|
||||
String ESP32GetResetReason(uint32_t cpu_no) {
|
||||
// tools\sdk\include\esp32\rom\rtc.h
|
||||
switch (rtc_get_reset_reason((RESET_REASON)cpu_no)) {
|
||||
case POWERON_RESET:
|
||||
return F("Vbat power on reset"); // 1
|
||||
case SW_RESET:
|
||||
return F("Software reset digital core"); // 3
|
||||
case OWDT_RESET:
|
||||
return F("Legacy watch dog reset digital core"); // 4
|
||||
case DEEPSLEEP_RESET:
|
||||
return F("Deep Sleep reset digital core"); // 5
|
||||
case SDIO_RESET:
|
||||
return F("Reset by SLC module, reset digital core"); // 6
|
||||
case TG0WDT_SYS_RESET:
|
||||
return F("Timer Group0 Watch dog reset digital core"); // 7
|
||||
case TG1WDT_SYS_RESET:
|
||||
return F("Timer Group1 Watch dog reset digital core"); // 8
|
||||
case RTCWDT_SYS_RESET:
|
||||
return F("RTC Watch dog Reset digital core"); // 9
|
||||
case INTRUSION_RESET:
|
||||
return F("Instrusion tested to reset CPU"); // 10
|
||||
case TGWDT_CPU_RESET:
|
||||
return F("Time Group reset CPU"); // 11
|
||||
case SW_CPU_RESET:
|
||||
return F("Software reset CPU"); // 12
|
||||
case RTCWDT_CPU_RESET:
|
||||
return F("RTC Watch dog Reset CPU"); // 13
|
||||
case EXT_CPU_RESET:
|
||||
return F("or APP CPU, reseted by PRO CPU"); // 14
|
||||
case RTCWDT_BROWN_OUT_RESET:
|
||||
return F("Reset when the vdd voltage is not stable"); // 15
|
||||
case RTCWDT_RTC_RESET:
|
||||
return F("RTC Watch dog reset digital core and rtc module"); // 16
|
||||
default:
|
||||
return F("NO_MEAN"); // 0
|
||||
}
|
||||
}
|
||||
|
||||
String ESP_getResetReason(void) {
|
||||
return ESP32GetResetReason(0); // CPU 0
|
||||
}
|
||||
#endif
|
||||
//String getUptimeTotal() {
|
||||
// static int hrs;
|
||||
// EEPROM.begin(512);
|
||||
// hrs = eeGetInt(0);
|
||||
// SerialPrint("I","Stat","Total running hrs: " + String(hrs));
|
||||
// String hrsStr = prettySeconds(hrs * 60 * 60);
|
||||
// SerialPrint("I","Stat","Total running hrs (f): " + hrsStr);
|
||||
// return hrsStr;
|
||||
//}
|
||||
//int plusOneHour() {
|
||||
// static int hrs;
|
||||
// EEPROM.begin(512);
|
||||
// hrs = eeGetInt(0);
|
||||
// hrs++;
|
||||
// eeWriteInt(0, hrs);
|
||||
// return hrs;
|
||||
//}
|
||||
//
|
||||
//void eeWriteInt(int pos, int val) {
|
||||
// byte* p = (byte*)&val;
|
||||
// EEPROM.write(pos, *p);
|
||||
// EEPROM.write(pos + 1, *(p + 1));
|
||||
// EEPROM.write(pos + 2, *(p + 2));
|
||||
// EEPROM.write(pos + 3, *(p + 3));
|
||||
// EEPROM.commit();
|
||||
//}
|
||||
//
|
||||
//int eeGetInt(int pos) {
|
||||
// int val;
|
||||
// byte* p = (byte*)&val;
|
||||
// *p = EEPROM.read(pos);
|
||||
// *(p + 1) = EEPROM.read(pos + 1);
|
||||
// *(p + 2) = EEPROM.read(pos + 2);
|
||||
// *(p + 3) = EEPROM.read(pos + 3);
|
||||
// if (val < 0) {
|
||||
// return 0;
|
||||
// } else {
|
||||
// return val;
|
||||
// }
|
||||
//}
|
||||
//========for updating list of device=================
|
||||
/*
|
||||
void updateDeviceList() {
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
WiFiClient client;
|
||||
HTTPClient http;
|
||||
String json = "{}";
|
||||
String mac = WiFi.macAddress().c_str();
|
||||
//===============================================
|
||||
jsonWriteStr(json, "uniqueId", mac);
|
||||
jsonWriteStr(json, "name", FIRMWARE_NAME);
|
||||
jsonWriteStr(json, "model", FIRMWARE_VERSION);
|
||||
jsonWriteInt(json, "id", getId("statid.txt"));
|
||||
//===============================================
|
||||
http.begin(client, "http://") + serverIP + F(":8082/api/devices/" + mac + "/");
|
||||
http.setAuthorization("admin", "admin");
|
||||
http.addHeader("Content-Type", "application/json");
|
||||
int httpCode = http.PUT(json);
|
||||
if (httpCode > 0) {
|
||||
Serial.printf("update Device List... code: %d\n", httpCode);
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
const String& payload = http.getString();
|
||||
Serial.println("received payload:\n<<");
|
||||
Serial.println(payload);
|
||||
Serial.println(">>");
|
||||
}
|
||||
} else {
|
||||
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
|
||||
}
|
||||
http.end();
|
||||
}
|
||||
}
|
||||
|
||||
void saveId(String file, int id) {
|
||||
removeFile(file);
|
||||
addFile(file, String(id));
|
||||
}
|
||||
|
||||
int getId(String file) {
|
||||
return readFile(file, 100).toInt();
|
||||
}
|
||||
*/
|
||||
Reference in New Issue
Block a user