mirror of
https://github.com/IoTManagerProject/IoTManager.git
synced 2026-03-27 06:32:19 +03:00
remoove all
This commit is contained in:
@@ -1,166 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/SensorDallas.h"
|
||||
#include "Global.h"
|
||||
#include "Module/Terminal.h"
|
||||
|
||||
void loopCmdAdd(const String& cmdStr) {
|
||||
orderBuf += cmdStr;
|
||||
if (!cmdStr.endsWith(",")) {
|
||||
orderBuf += ",";
|
||||
}
|
||||
}
|
||||
|
||||
void fileCmdExecute(const String& filename) {
|
||||
String cmdStr = readFile(filename, 4096);
|
||||
csvCmdExecute(cmdStr);
|
||||
}
|
||||
|
||||
void csvCmdExecute(String& cmdStr) {
|
||||
cmdStr.replace(";", " ");
|
||||
cmdStr += "\r\n";
|
||||
cmdStr.replace("\r\n", "\n");
|
||||
cmdStr.replace("\r", "\n");
|
||||
int count = 0;
|
||||
while (cmdStr.length()) {
|
||||
String buf = selectToMarker(cmdStr, "\n");
|
||||
|
||||
|
||||
|
||||
buf = deleteBeforeDelimiter(buf, " "); //отсечка чекбокса
|
||||
|
||||
count++;
|
||||
if (count > 1) {
|
||||
SerialPrint("I", "Items", buf);
|
||||
String order = selectToMarker(buf, " "); //отсечка самой команды
|
||||
|
||||
if (order == F("button-out")) {
|
||||
sCmd.addCommand(order.c_str(), buttonOut);
|
||||
}
|
||||
else if (order == F("pwm-out")) {
|
||||
sCmd.addCommand(order.c_str(), pwmOut);
|
||||
}
|
||||
else if (order == F("button-in")) {
|
||||
sCmd.addCommand(order.c_str(), buttonIn);
|
||||
}
|
||||
else if (order == F("input-digit")) {
|
||||
sCmd.addCommand(order.c_str(), inputDigit);
|
||||
}
|
||||
else if (order == F("input-time")) {
|
||||
sCmd.addCommand(order.c_str(), inputTime);
|
||||
}
|
||||
else if (order == F("output-text")) {
|
||||
sCmd.addCommand(order.c_str(), textOut);
|
||||
}
|
||||
else if (order == F("analog-adc")) {
|
||||
sCmd.addCommand(order.c_str(), analogAdc);
|
||||
}
|
||||
else if (order == F("ultrasonic-cm")) {
|
||||
sCmd.addCommand(order.c_str(), ultrasonicCm);
|
||||
}
|
||||
else if (order == F("dallas-temp")) {
|
||||
sCmd.addCommand(order.c_str(), dallas);
|
||||
}
|
||||
else if (order == F("dht-temp")) {
|
||||
sCmd.addCommand(order.c_str(), dhtTemp);
|
||||
}
|
||||
else if (order == F("dht-hum")) {
|
||||
sCmd.addCommand(order.c_str(), dhtHum);
|
||||
}
|
||||
else if (order == F("bme280-temp")) {
|
||||
sCmd.addCommand(order.c_str(), bme280Temp);
|
||||
}
|
||||
else if (order == F("bme280-hum")) {
|
||||
sCmd.addCommand(order.c_str(), bme280Hum);
|
||||
}
|
||||
else if (order == F("bme280-press")) {
|
||||
sCmd.addCommand(order.c_str(), bme280Press);
|
||||
}
|
||||
else if (order == F("bmp280-temp")) {
|
||||
sCmd.addCommand(order.c_str(), bmp280Temp);
|
||||
}
|
||||
else if (order == F("bmp280-press")) {
|
||||
sCmd.addCommand(order.c_str(), bmp280Press);
|
||||
}
|
||||
else if (order == F("modbus")) {
|
||||
//sCmd.addCommand(order.c_str(), modbus);
|
||||
}
|
||||
else if (order == F("uptime")) {
|
||||
sCmd.addCommand(order.c_str(), sysUptime);
|
||||
}
|
||||
else if (order == F("logging")) {
|
||||
sCmd.addCommand(order.c_str(), logging);
|
||||
}
|
||||
else if (order == F("impuls-out")) {
|
||||
sCmd.addCommand(order.c_str(), impuls);
|
||||
}
|
||||
|
||||
|
||||
|
||||
sCmd.readStr(buf);
|
||||
}
|
||||
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
void spaceCmdExecute(String& cmdStr) {
|
||||
cmdStr += "\r\n";
|
||||
cmdStr.replace("\r\n", "\n");
|
||||
cmdStr.replace("\r", "\n");
|
||||
while (cmdStr.length()) {
|
||||
String buf = selectToMarker(cmdStr, "\n");
|
||||
sCmd.readStr(buf);
|
||||
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
|
||||
}
|
||||
}
|
||||
|
||||
void loopCmdExecute() {
|
||||
if (orderBuf.length()) {
|
||||
String tmp = selectToMarker(orderBuf, ","); //выделяем первую команду rel 5 1,
|
||||
SerialPrint("I", "CMD", "do: " + tmp);
|
||||
sCmd.readStr(tmp); //выполняем
|
||||
orderBuf = deleteBeforeDelimiter(orderBuf, ","); //осекаем
|
||||
}
|
||||
}
|
||||
|
||||
void sensorsInit() {
|
||||
ts.add(
|
||||
SENSORS10SEC, 10000, [&](void*) {
|
||||
String buf = sensorReadingMap10sec;
|
||||
while (buf.length()) {
|
||||
String tmp = selectToMarker(buf, ",");
|
||||
sCmd.readStr(tmp);
|
||||
buf = deleteBeforeDelimiter(buf, ",");
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
|
||||
ts.add(
|
||||
SENSORS30SEC, 30000, [&](void*) {
|
||||
String buf = sensorReadingMap30sec;
|
||||
while (buf.length()) {
|
||||
String tmp = selectToMarker(buf, ",");
|
||||
sCmd.readStr(tmp);
|
||||
buf = deleteBeforeDelimiter(buf, ",");
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
|
||||
void addKey(String& key, String& keyNumberTable, int number) {
|
||||
keyNumberTable += key + " " + String(number) + ",";
|
||||
}
|
||||
|
||||
int getKeyNum(String& key, String& keyNumberTable) {
|
||||
String keyNumberTableBuf = keyNumberTable;
|
||||
|
||||
int number = -1;
|
||||
while (keyNumberTableBuf.length()) {
|
||||
String tmp = selectToMarker(keyNumberTableBuf, ",");
|
||||
String keyIncomming = selectToMarker(tmp, " ");
|
||||
if (keyIncomming == key) {
|
||||
number = selectToMarkerLast(tmp, " ").toInt();
|
||||
}
|
||||
keyNumberTableBuf = deleteBeforeDelimiter(keyNumberTableBuf, ",");
|
||||
}
|
||||
return number;
|
||||
}
|
||||
38
src/Bus.cpp
38
src/Bus.cpp
@@ -1,38 +0,0 @@
|
||||
#include "Bus.h"
|
||||
#include "Class/NotAsync.h"
|
||||
#include "Global.h"
|
||||
|
||||
void busInit() {
|
||||
myNotAsyncActions->add(
|
||||
do_BUSSCAN, [&](void*) {
|
||||
String tmp = i2c_scan();
|
||||
if (tmp == "error") {
|
||||
tmp = i2c_scan();
|
||||
Serial.println(tmp);
|
||||
jsonWriteStr(configLiveJson, "i2c", tmp);
|
||||
} else {
|
||||
Serial.println(tmp);
|
||||
jsonWriteStr(configLiveJson, "i2c", tmp);
|
||||
}
|
||||
},
|
||||
nullptr);
|
||||
}
|
||||
|
||||
String i2c_scan() {
|
||||
String out;
|
||||
byte count = 0;
|
||||
Wire.begin();
|
||||
for (byte i = 8; i < 120; i++) {
|
||||
Wire.beginTransmission(i);
|
||||
if (Wire.endTransmission() == 0) {
|
||||
count++;
|
||||
out += String(count) + ". 0x" + String(i, HEX) + "; ";
|
||||
delay(1);
|
||||
}
|
||||
}
|
||||
if (count == 0) {
|
||||
return "error";
|
||||
} else {
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#include "Class/CallBackTest.h"
|
||||
|
||||
CallBackTest::CallBackTest(){};
|
||||
|
||||
void CallBackTest::loop() {
|
||||
count++;
|
||||
if (count > 5000) {
|
||||
// Проверяем что переменная содержит указатель - не пустая не null
|
||||
// и непосредственно вызываем то, на что это указывает
|
||||
// просто пишем имя - без () - это указатель на фунецию.
|
||||
// () - вызываем функцию - с пустым набором параметров
|
||||
|
||||
if (_cb != NULL) {
|
||||
_cb();
|
||||
}
|
||||
//или ровно тоже самое
|
||||
//if (_cb) _cb();
|
||||
|
||||
if (_pcb) {
|
||||
if (_pcb("SomeTextValue")) {
|
||||
Serial.println("Got true!");
|
||||
} else {
|
||||
Serial.println("Got false!");
|
||||
}
|
||||
}
|
||||
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
//передаем внутрь класса функцию любую void функцию без агрументов
|
||||
void CallBackTest::setCallback(AsyncActionCb cb) {
|
||||
_cb = cb;
|
||||
}
|
||||
|
||||
//передаем внутрь класса функцию любую void функцию с аргументами
|
||||
void CallBackTest::setCallback(AsyncParamActionCb pcb) {
|
||||
_pcb = pcb;
|
||||
}
|
||||
//CallBackTest* CB;
|
||||
|
||||
//CB->setCallback([]() {
|
||||
// Serial.println("123");
|
||||
//});
|
||||
//
|
||||
//CB->setCallback([](const String str) {
|
||||
// Serial.println(str);
|
||||
// return true;
|
||||
//});
|
||||
@@ -1,2 +0,0 @@
|
||||
#include "Class/LineParsing.h"
|
||||
LineParsing myLineParsing;
|
||||
@@ -1,30 +0,0 @@
|
||||
#include "Class/NotAsync.h"
|
||||
|
||||
NotAsync::NotAsync(uint8_t size) {
|
||||
this->items = new NotAsyncItem[size];
|
||||
this->size = size;
|
||||
}
|
||||
|
||||
NotAsync::~NotAsync() {}
|
||||
|
||||
void NotAsync::add(uint8_t i, NotAsyncCb f, void* arg) {
|
||||
this->items[i].cb = f;
|
||||
this->items[i].cb_arg = arg;
|
||||
this->items[i].is_used = true;
|
||||
}
|
||||
|
||||
void NotAsync::loop() {
|
||||
if (this->items[task].is_used) {
|
||||
handle(this->items[task].cb, this->items[task].cb_arg);
|
||||
task = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void NotAsync::make(uint8_t task) {
|
||||
this->task = task;
|
||||
}
|
||||
|
||||
void NotAsync::handle(NotAsyncCb f, void* arg) {
|
||||
f(arg);
|
||||
}
|
||||
NotAsync* myNotAsyncActions;
|
||||
@@ -1,18 +0,0 @@
|
||||
#include "Class/ScenarioClass3.h"
|
||||
Scenario* myScenario;
|
||||
|
||||
//void eventGen(String event_name, String number) {
|
||||
// if (!jsonReadBool(configSetupJson, "scen")) {
|
||||
// return;
|
||||
// }
|
||||
// SerialPrint("", "", event_name);
|
||||
// eventBuf += event_name + number + ",";
|
||||
//}
|
||||
|
||||
void eventGen2(String eventName, String eventValue) {
|
||||
if (!jsonReadBool(configSetupJson, "scen")) {
|
||||
return;
|
||||
}
|
||||
//Serial.println(eventName + " " + eventValue);
|
||||
eventBuf += eventName + " " + eventValue + ",";
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#include "Clock.h"
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
Clock* timeNow;
|
||||
void clock_init() {
|
||||
timeNow = new Clock;
|
||||
timeNow->setNtpPool(jsonReadStr(configSetupJson, "ntp"));
|
||||
timeNow->setTimezone(jsonReadStr(configSetupJson, "timezone").toInt());
|
||||
|
||||
ts.add(
|
||||
TIME_SYNC, 30000, [&](void*) {
|
||||
timeNow->hasSync();
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
341
src/FSEditor.cpp
341
src/FSEditor.cpp
@@ -1,341 +0,0 @@
|
||||
#include "FSEditor.h"
|
||||
|
||||
#ifdef ESP32
|
||||
#include "LITTLEFS.h"
|
||||
#define LittleFS LITTLEFS
|
||||
#endif
|
||||
#ifdef ESP8266
|
||||
#include <LittleFS.h>
|
||||
#endif
|
||||
|
||||
#define FS_MAXLENGTH_FILEPATH 32
|
||||
|
||||
const char *excludeListFile = "/.exclude.files";
|
||||
|
||||
typedef struct ExcludeListS {
|
||||
char *item;
|
||||
ExcludeListS *next;
|
||||
} ExcludeList;
|
||||
|
||||
static ExcludeList *excludes = NULL;
|
||||
|
||||
static bool matchWild(const char *pattern, const char *testee) {
|
||||
const char *nxPat = NULL, *nxTst = NULL;
|
||||
|
||||
while (*testee) {
|
||||
if ((*pattern == '?') || (*pattern == *testee)) {
|
||||
pattern++;
|
||||
testee++;
|
||||
continue;
|
||||
}
|
||||
if (*pattern == '*') {
|
||||
nxPat = pattern++;
|
||||
nxTst = testee;
|
||||
continue;
|
||||
}
|
||||
if (nxPat) {
|
||||
pattern = nxPat + 1;
|
||||
testee = ++nxTst;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
while (*pattern == '*') {
|
||||
pattern++;
|
||||
}
|
||||
return (*pattern == 0);
|
||||
}
|
||||
|
||||
static bool addExclude(const char *item) {
|
||||
size_t len = strlen(item);
|
||||
if (!len) {
|
||||
return false;
|
||||
}
|
||||
ExcludeList *e = (ExcludeList *)malloc(sizeof(ExcludeList));
|
||||
if (!e) {
|
||||
return false;
|
||||
}
|
||||
e->item = (char *)malloc(len + 1);
|
||||
if (!e->item) {
|
||||
free(e);
|
||||
return false;
|
||||
}
|
||||
memcpy(e->item, item, len + 1);
|
||||
e->next = excludes;
|
||||
excludes = e;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void loadExcludeList(fs::FS &_fs, const char *filename) {
|
||||
static char linebuf[FS_MAXLENGTH_FILEPATH];
|
||||
fs::File excludeFile = _fs.open(filename, "r");
|
||||
if (!excludeFile) {
|
||||
return;
|
||||
}
|
||||
if (excludeFile.isDirectory()) {
|
||||
excludeFile.close();
|
||||
return;
|
||||
}
|
||||
if (excludeFile.size() > 0) {
|
||||
uint8_t idx;
|
||||
bool isOverflowed = false;
|
||||
while (excludeFile.available()) {
|
||||
linebuf[0] = '\0';
|
||||
idx = 0;
|
||||
int lastChar;
|
||||
do {
|
||||
lastChar = excludeFile.read();
|
||||
if (lastChar != '\r') {
|
||||
linebuf[idx++] = (char)lastChar;
|
||||
}
|
||||
} while ((lastChar >= 0) && (lastChar != '\n') && (idx < FS_MAXLENGTH_FILEPATH));
|
||||
|
||||
if (isOverflowed) {
|
||||
isOverflowed = (lastChar != '\n');
|
||||
continue;
|
||||
}
|
||||
isOverflowed = (idx >= FS_MAXLENGTH_FILEPATH);
|
||||
linebuf[idx - 1] = '\0';
|
||||
if (!addExclude(linebuf)) {
|
||||
excludeFile.close();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
excludeFile.close();
|
||||
}
|
||||
|
||||
static bool isExcluded(fs::FS &_fs, const char *filename) {
|
||||
if (excludes == NULL) {
|
||||
loadExcludeList(_fs, excludeListFile);
|
||||
}
|
||||
if (strcmp(excludeListFile, filename) == 0) return true;
|
||||
ExcludeList *e = excludes;
|
||||
while (e) {
|
||||
if (matchWild(e->item, filename)) {
|
||||
return true;
|
||||
}
|
||||
e = e->next;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// WEB HANDLER IMPLEMENTATION
|
||||
|
||||
#ifdef ESP32
|
||||
FSEditor::FSEditor(const fs::FS &fs, const String &username, const String &password)
|
||||
#else
|
||||
FSEditor::FSEditor(const String &username, const String &password, const fs::FS &fs)
|
||||
#endif
|
||||
: _fs(fs), _username(username), _password(password), _authenticated(false), _startTime(0) {
|
||||
}
|
||||
|
||||
bool FSEditor::canHandle(AsyncWebServerRequest *request) {
|
||||
if (request->url().equalsIgnoreCase("/edit")) {
|
||||
if (request->method() == HTTP_GET) {
|
||||
if (request->hasParam("list"))
|
||||
return true;
|
||||
if (request->hasParam("edit")) {
|
||||
request->_tempFile = _fs.open(request->arg("edit"), "r");
|
||||
if (!request->_tempFile) {
|
||||
return false;
|
||||
}
|
||||
if (request->_tempFile.isDirectory()) {
|
||||
request->_tempFile.close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (request->hasParam("download")) {
|
||||
request->_tempFile = _fs.open(request->arg("download"), "r");
|
||||
if (!request->_tempFile) {
|
||||
return false;
|
||||
}
|
||||
if (request->_tempFile.isDirectory()) {
|
||||
request->_tempFile.close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
request->addInterestingHeader("If-Modified-Since");
|
||||
return true;
|
||||
} else if (request->method() == HTTP_POST)
|
||||
return true;
|
||||
else if (request->method() == HTTP_DELETE)
|
||||
return true;
|
||||
else if (request->method() == HTTP_PUT)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#ifdef ESP8266
|
||||
void FSEditor::getDirList(const String &path, String &output) {
|
||||
auto dir = _fs.openDir(path.c_str());
|
||||
while (dir.next()) {
|
||||
String fname = dir.fileName();
|
||||
if (!path.endsWith("/") && !fname.startsWith("/")) {
|
||||
fname = "/" + fname;
|
||||
}
|
||||
fname = path + fname;
|
||||
if (isExcluded(_fs, fname.c_str())) {
|
||||
continue;
|
||||
}
|
||||
if (dir.isDirectory()) {
|
||||
getDirList(fname, output);
|
||||
continue;
|
||||
}
|
||||
if (output != "[") output += ',';
|
||||
char buf[128];
|
||||
sprintf(buf, "{\"type\":\"file\",\"name\":\"%s\",\"size\":%d}", fname.c_str(), dir.fileSize());
|
||||
output += buf;
|
||||
}
|
||||
}
|
||||
#else
|
||||
void FSEditor::getDirList(const String &path, String &output) {
|
||||
auto dir = _fs.open(path, FILE_READ);
|
||||
dir.rewindDirectory();
|
||||
while (dir.openNextFile()) {
|
||||
String fname = dir.name();
|
||||
if (!path.endsWith("/") && !fname.startsWith("/")) {
|
||||
fname = "/" + fname;
|
||||
}
|
||||
fname = path + fname;
|
||||
if (isExcluded(_fs, fname.c_str())) {
|
||||
continue;
|
||||
}
|
||||
if (dir.isDirectory()) {
|
||||
getDirList(fname, output);
|
||||
continue;
|
||||
}
|
||||
if (output != "[") output += ',';
|
||||
char buf[128];
|
||||
sprintf(buf, "{\"type\":\"file\",\"name\":\"%s\",\"size\":%d}", fname.c_str(), dir.size());
|
||||
output += buf;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void FSEditor::handleRequest(AsyncWebServerRequest *request) {
|
||||
if (_username.length() && _password.length() && !request->authenticate(_username.c_str(), _password.c_str()))
|
||||
return request->requestAuthentication();
|
||||
|
||||
if (request->method() == HTTP_GET) {
|
||||
if (request->hasParam("list")) {
|
||||
if (request->hasParam("list")) {
|
||||
String path = request->getParam("list")->value();
|
||||
String output = "[";
|
||||
getDirList(path, output);
|
||||
output += "]";
|
||||
request->send(200, "application/json", output);
|
||||
output = String();
|
||||
}
|
||||
} else if (request->hasParam("edit") || request->hasParam("download")) {
|
||||
#ifdef ESP8266
|
||||
request->send(request->_tempFile, request->_tempFile.fullName(), String(), request->hasParam("download"));
|
||||
#else
|
||||
request->send(request->_tempFile, request->_tempFile.name(), String(), request->hasParam("download"));
|
||||
#endif
|
||||
} else {
|
||||
const char *buildTime = __DATE__ " " __TIME__ " GMT";
|
||||
if (request->header("If-Modified-Since").equals(buildTime)) {
|
||||
request->send(304);
|
||||
} else {
|
||||
AsyncWebServerResponse *response = request->beginResponse(LittleFS, "/edit.htm", "text/html");
|
||||
// response->addHeader("Content-Encoding", "gzip");
|
||||
response->addHeader("Last-Modified", buildTime);
|
||||
request->send(response);
|
||||
}
|
||||
}
|
||||
} else if (request->method() == HTTP_DELETE) {
|
||||
if (request->hasParam("path", true)) {
|
||||
if (!(_fs.remove(request->getParam("path", true)->value()))) {
|
||||
#ifdef ESP32
|
||||
_fs.rmdir(request->getParam("path", true)->value()); // try rmdir for littlefs
|
||||
#endif
|
||||
}
|
||||
|
||||
request->send(200, "", "DELETE: " + request->getParam("path", true)->value());
|
||||
} else
|
||||
request->send(404);
|
||||
} else if (request->method() == HTTP_POST) {
|
||||
if (request->hasParam("data", true, true) && _fs.exists(request->getParam("data", true, true)->value()))
|
||||
request->send(200, "", "UPLOADED: " + request->getParam("data", true, true)->value());
|
||||
|
||||
else if (request->hasParam("rawname", true) && request->hasParam("raw0", true)) {
|
||||
String rawnam = request->getParam("rawname", true)->value();
|
||||
|
||||
if (_fs.exists(rawnam)) _fs.remove(rawnam); // delete it to allow a mode
|
||||
|
||||
int k = 0;
|
||||
uint16_t i = 0;
|
||||
fs::File f = _fs.open(rawnam, "a");
|
||||
|
||||
while (request->hasParam("raw" + String(k), true)) { //raw0 .. raw1
|
||||
if (f) {
|
||||
i += f.print(request->getParam("raw" + String(k), true)->value());
|
||||
}
|
||||
k++;
|
||||
}
|
||||
f.close();
|
||||
request->send(200, "", "IPADWRITE: " + rawnam + ":" + String(i));
|
||||
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
|
||||
} else if (request->method() == HTTP_PUT) {
|
||||
if (request->hasParam("path", true)) {
|
||||
String filename = request->getParam("path", true)->value();
|
||||
if (_fs.exists(filename)) {
|
||||
request->send(200);
|
||||
} else {
|
||||
/*******************************************************/
|
||||
#ifdef ESP32
|
||||
if (strchr(filename.c_str(), '/')) {
|
||||
// For file creation, silently make subdirs as needed. If any fail,
|
||||
// it will be caught by the real file open later on
|
||||
char *pathStr = strdup(filename.c_str());
|
||||
if (pathStr) {
|
||||
// Make dirs up to the final fnamepart
|
||||
char *ptr = strchr(pathStr, '/');
|
||||
while (ptr) {
|
||||
*ptr = 0;
|
||||
_fs.mkdir(pathStr);
|
||||
*ptr = '/';
|
||||
ptr = strchr(ptr + 1, '/');
|
||||
}
|
||||
}
|
||||
free(pathStr);
|
||||
}
|
||||
#endif
|
||||
/*******************************************************/
|
||||
fs::File f = _fs.open(filename, "w");
|
||||
if (f) {
|
||||
f.write((uint8_t)0x00);
|
||||
f.close();
|
||||
request->send(200, "", "CREATE: " + filename);
|
||||
} else {
|
||||
request->send(500);
|
||||
}
|
||||
}
|
||||
} else
|
||||
request->send(400);
|
||||
}
|
||||
}
|
||||
|
||||
void FSEditor::handleUpload(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
if (!index) {
|
||||
if (!_username.length() || request->authenticate(_username.c_str(), _password.c_str())) {
|
||||
_authenticated = true;
|
||||
request->_tempFile = _fs.open(filename, "w");
|
||||
_startTime = millis();
|
||||
}
|
||||
}
|
||||
if (_authenticated && request->_tempFile) {
|
||||
if (len) {
|
||||
request->_tempFile.write(data, len);
|
||||
}
|
||||
if (final) {
|
||||
request->_tempFile.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
#include "Global.h"
|
||||
|
||||
#ifdef WS_enable
|
||||
AsyncWebSocket ws;
|
||||
//AsyncEventSource events;
|
||||
#endif
|
||||
|
||||
TickerScheduler ts(TEST + 1);
|
||||
WiFiClient espClient;
|
||||
PubSubClient mqtt(espClient);
|
||||
StringCommand sCmd;
|
||||
AsyncWebServer server(80);
|
||||
OneWire *oneWire;
|
||||
DallasTemperature sensors;
|
||||
|
||||
/*
|
||||
* Global vars
|
||||
*/
|
||||
|
||||
boolean just_load = true;
|
||||
boolean telegramInitBeen = false;
|
||||
|
||||
// Json
|
||||
String configSetupJson = "{}";
|
||||
String configLiveJson = "{}";
|
||||
String configOptionJson = "{}";
|
||||
|
||||
// Mqtt
|
||||
String chipId = "";
|
||||
String prex = "";
|
||||
String all_widgets = "";
|
||||
String scenario = "";
|
||||
|
||||
//orders and events
|
||||
String orderBuf = "";
|
||||
String eventBuf = "";
|
||||
String itemsFile = "";
|
||||
String itemsLine = "";
|
||||
|
||||
//key lists and numbers
|
||||
String impulsKeyList = "";
|
||||
int impulsEnterCounter = -1;
|
||||
|
||||
|
||||
// Sensors
|
||||
String sensorReadingMap10sec;
|
||||
String sensorReadingMap30sec;
|
||||
|
||||
// Logging
|
||||
String loggingKeyList;
|
||||
int enter_to_logging_counter;
|
||||
|
||||
// Upgrade
|
||||
String serverIP;
|
||||
|
||||
// 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 lastVersion;
|
||||
|
||||
boolean busScanFlag = false;
|
||||
boolean fsCheckFlag = false;
|
||||
boolean delElementFlag = false;
|
||||
|
||||
105
src/Init.cpp
105
src/Init.cpp
@@ -1,105 +0,0 @@
|
||||
#include "Init.h"
|
||||
#include "BufferExecute.h"
|
||||
#include "Cmd.h"
|
||||
#include "Global.h"
|
||||
#include "items/LoggingClass.h"
|
||||
#include "items/ImpulsOutClass.h"
|
||||
#include "items/SensorDallas.h"
|
||||
|
||||
void loadConfig() {
|
||||
configSetupJson = readFile("config.json", 4096);
|
||||
//configSetupJson.replace(" ", "");
|
||||
configSetupJson.replace("\r\n", "");
|
||||
|
||||
jsonWriteStr(configSetupJson, "chipID", chipId);
|
||||
jsonWriteInt(configSetupJson, "firmware_version", FIRMWARE_VERSION);
|
||||
|
||||
prex = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + chipId;
|
||||
|
||||
Serial.println(configSetupJson);
|
||||
|
||||
serverIP = jsonReadStr(configSetupJson, "serverip");
|
||||
}
|
||||
|
||||
void all_init() {
|
||||
Device_init();
|
||||
loadScenario();
|
||||
Timer_countdown_init();
|
||||
}
|
||||
|
||||
void Device_init() {
|
||||
|
||||
sensorReadingMap10sec = "";
|
||||
|
||||
//======clear dallas params======
|
||||
if (mySensorDallas2 != nullptr) {
|
||||
mySensorDallas2->clear();
|
||||
}
|
||||
//======clear logging params======
|
||||
if (myLogging != nullptr) {
|
||||
myLogging->clear();
|
||||
}
|
||||
loggingKeyList = "";
|
||||
//======clear impuls params=======
|
||||
if (myImpulsOut != nullptr) {
|
||||
myImpulsOut->clear();
|
||||
}
|
||||
impulsKeyList = "";
|
||||
impulsEnterCounter = -1;
|
||||
//================================
|
||||
|
||||
|
||||
#ifdef LAYOUT_IN_RAM
|
||||
all_widgets = "";
|
||||
#else
|
||||
removeFile(String("layout.txt"));
|
||||
#endif
|
||||
|
||||
fileCmdExecute(String(DEVICE_CONFIG_FILE));
|
||||
//outcoming_date();
|
||||
}
|
||||
//-------------------------------сценарии-----------------------------------------------------
|
||||
|
||||
void loadScenario() {
|
||||
if (jsonReadStr(configSetupJson, "scen") == "1") {
|
||||
scenario = readFile(String(DEVICE_SCENARIO_FILE), 2048);
|
||||
}
|
||||
}
|
||||
|
||||
void uptime_init() {
|
||||
ts.add(
|
||||
UPTIME, 5000, [&](void*) {
|
||||
handle_uptime();
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
|
||||
void handle_uptime() {
|
||||
jsonWriteStr(configSetupJson, "uptime", timeNow->getUptime());
|
||||
}
|
||||
|
||||
//void handle_statistics() {
|
||||
// if (isNetworkActive()) {
|
||||
// String urls = "http://backup.privet.lv/visitors/?";
|
||||
// //-----------------------------------------------------------------
|
||||
// urls += WiFi.macAddress().c_str();
|
||||
// urls += "&";
|
||||
// //-----------------------------------------------------------------
|
||||
//#ifdef ESP8266
|
||||
// urls += "iot-manager_esp8266";
|
||||
//#endif
|
||||
//#ifdef ESP32
|
||||
// urls += "iot-manager_esp32";
|
||||
//#endif
|
||||
// urls += "&";
|
||||
//#ifdef ESP8266
|
||||
// urls += ESP.getResetReason();
|
||||
//#endif
|
||||
//#ifdef ESP32
|
||||
// urls += "Power on";
|
||||
//#endif
|
||||
// urls += "&";
|
||||
// urls += String(FIRMWARE_VERSION);
|
||||
// String stat = getURL(urls);
|
||||
// }
|
||||
//}
|
||||
334
src/ItemsCmd.cpp
334
src/ItemsCmd.cpp
@@ -1,334 +0,0 @@
|
||||
//#include "BufferExecute.h"
|
||||
//
|
||||
//#include "BufferExecute.h"
|
||||
//#include "Class/NotAsync.h"
|
||||
//#include "Cmd.h"
|
||||
//#include "Global.h"
|
||||
//#include "Module/Terminal.h"
|
||||
//#include "Servo/Servos.h"
|
||||
//
|
||||
//#include "items/SensorDallas.h"
|
||||
//
|
||||
//Terminal *term = nullptr;
|
||||
//
|
||||
//boolean but[NUM_BUTTONS];
|
||||
//Bounce *buttons = new Bounce[NUM_BUTTONS];
|
||||
//
|
||||
//#ifdef ESP8266
|
||||
//SoftwareSerial *mySerial = nullptr;
|
||||
//#else
|
||||
//HardwareSerial *mySerial = nullptr;
|
||||
//#endif
|
||||
//
|
||||
//void getData();
|
||||
//
|
||||
//void cmd_init() {
|
||||
//sCmd.addCommand("button-out", buttonOut);
|
||||
//sCmd.addCommand("pwm-out", pwmOut);
|
||||
//sCmd.addCommand("button-in", buttonIn);
|
||||
|
||||
//sCmd.addCommand("input-digit", inputDigit);
|
||||
//sCmd.addCommand("input-time", inputTime);
|
||||
//sCmd.addCommand("output-text", textOut);
|
||||
|
||||
//sCmd.addCommand("analog-adc", analogAdc);
|
||||
//sCmd.addCommand("ultrasonic-cm", ultrasonicCm);
|
||||
//sCmd.addCommand("dallas-temp", dallas);
|
||||
|
||||
//sCmd.addCommand("dht-temp", dhtTemp);
|
||||
//sCmd.addCommand("dht-hum", dhtHum);
|
||||
|
||||
//sCmd.addCommand("bme280-temp", bme280Temp);
|
||||
//sCmd.addCommand("bme280-hum", bme280Hum);
|
||||
//sCmd.addCommand("bme280-press", bme280Press);
|
||||
|
||||
//sCmd.addCommand("bmp280-temp", bmp280Temp);
|
||||
//sCmd.addCommand("bmp280-press", bmp280Press);
|
||||
|
||||
//sCmd.addCommand("modbus", modbus);
|
||||
|
||||
//sCmd.addCommand("uptime", sysUptime);
|
||||
|
||||
//sCmd.addCommand("logging", logging);
|
||||
|
||||
//sCmd.addCommand("impuls-out", impuls);
|
||||
|
||||
|
||||
//}
|
||||
|
||||
// sCmd.addCommand("timerStart", timerStart_);
|
||||
// sCmd.addCommand("timerStop", timerStop_);
|
||||
|
||||
//#ifdef DHT_ENABLED
|
||||
// sCmd.addCommand("dhtT", dhtT);
|
||||
// sCmd.addCommand("dhtH", dhtH);
|
||||
// sCmd.addCommand("dhtPerception", dhtP);
|
||||
// sCmd.addCommand("dhtComfort", dhtC);
|
||||
// sCmd.addCommand("dhtDewpoint", dhtD);
|
||||
//#endif
|
||||
|
||||
//#ifdef BMP_ENABLED
|
||||
// sCmd.addCommand("bmp280T", bmp280T);
|
||||
// sCmd.addCommand("bmp280P", bmp280P);
|
||||
//#endif
|
||||
//
|
||||
//#ifdef BME_ENABLED
|
||||
// sCmd.addCommand("bme280T", bme280T);
|
||||
// sCmd.addCommand("bme280P", bme280P);
|
||||
// sCmd.addCommand("bme280H", bme280H);
|
||||
// sCmd.addCommand("bme280A", bme280A);
|
||||
//#endif
|
||||
//
|
||||
//#ifdef STEPPER_ENABLED
|
||||
// sCmd.addCommand("stepper", stepper);
|
||||
// sCmd.addCommand("stepperSet", stepperSet);
|
||||
//#endif
|
||||
//
|
||||
//#ifdef SERVO_ENABLED
|
||||
// sCmd.addCommand("servo", servo_);
|
||||
// sCmd.addCommand("servoSet", servoSet);
|
||||
//#endif
|
||||
//
|
||||
//#ifdef SERIAL_ENABLED
|
||||
// sCmd.addCommand("serialBegin", serialBegin);
|
||||
// sCmd.addCommand("serialWrite", serialWrite);
|
||||
// sCmd.addCommand("getData", getData);
|
||||
//#endif
|
||||
//
|
||||
//#ifdef LOGGING_ENABLED
|
||||
// sCmd.addCommand("logging", logging);
|
||||
//#endif
|
||||
//
|
||||
// sCmd.addCommand("mqtt", mqttOrderSend);
|
||||
// sCmd.addCommand("http", httpOrderSend);
|
||||
//
|
||||
//#ifdef PUSH_ENABLED
|
||||
// sCmd.addCommand("push", pushControl);
|
||||
//#endif
|
||||
//
|
||||
// sCmd.addCommand("firmwareUpdate", firmwareUpdate);
|
||||
// sCmd.addCommand("firmwareVersion", firmwareVersion);
|
||||
|
||||
//void text() {
|
||||
// String number = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
//
|
||||
// createWidget(widget_name, page_name, page_number, "anydata", "text" + number);
|
||||
//}
|
||||
//
|
||||
//void textSet() {
|
||||
// String number = sCmd.next();
|
||||
// String text = sCmd.next();
|
||||
// text.replace("_", " ");
|
||||
//
|
||||
// if (text.indexOf("-time") >= 0) {
|
||||
// text.replace("-time", "");
|
||||
// text.replace("#", " ");
|
||||
// text = text + " " + timeNow->getDateTimeDotFormated();
|
||||
// }
|
||||
//
|
||||
// jsonWriteStr(configLiveJson, "text" + number, text);
|
||||
// publishStatus("text" + number, text);
|
||||
//}
|
||||
//=====================================================================================================================================
|
||||
////=========================================Модуль шагового мотора======================================================================
|
||||
//#ifdef STEPPER_ENABLED
|
||||
////stepper 1 12 13
|
||||
//void stepper() {
|
||||
// String stepper_number = sCmd.next();
|
||||
// String pin_step = sCmd.next();
|
||||
// String pin_dir = sCmd.next();
|
||||
//
|
||||
// jsonWriteStr(configOptionJson, "stepper" + stepper_number, pin_step + " " + pin_dir);
|
||||
// pinMode(pin_step.toInt(), OUTPUT);
|
||||
// pinMode(pin_dir.toInt(), OUTPUT);
|
||||
//}
|
||||
//
|
||||
////stepperSet 1 100 5
|
||||
//void stepperSet() {
|
||||
// String stepper_number = sCmd.next();
|
||||
// String steps = sCmd.next();
|
||||
// jsonWriteStr(configOptionJson, "steps" + stepper_number, steps);
|
||||
// String stepper_speed = sCmd.next();
|
||||
// String pin_step = selectToMarker(jsonReadStr(configOptionJson, "stepper" + stepper_number), " ");
|
||||
// String pin_dir = deleteBeforeDelimiter(jsonReadStr(configOptionJson, "stepper" + stepper_number), " ");
|
||||
// Serial.println(pin_step);
|
||||
// Serial.println(pin_dir);
|
||||
// if (steps.toInt() > 0) digitalWrite(pin_dir.toInt(), HIGH);
|
||||
// if (steps.toInt() < 0) digitalWrite(pin_dir.toInt(), LOW);
|
||||
// if (stepper_number == "1") {
|
||||
// ts.add(
|
||||
// STEPPER1, stepper_speed.toInt(), [&](void *) {
|
||||
// int steps_int = abs(jsonReadInt(configOptionJson, "steps1") * 2);
|
||||
// static int count;
|
||||
// count++;
|
||||
// String pin_step = selectToMarker(jsonReadStr(configOptionJson, "stepper1"), " ");
|
||||
// digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt()));
|
||||
// yield();
|
||||
// if (count > steps_int) {
|
||||
// digitalWrite(pin_step.toInt(), LOW);
|
||||
// ts.remove(STEPPER1);
|
||||
// count = 0;
|
||||
// }
|
||||
// },
|
||||
// nullptr, true);
|
||||
// }
|
||||
// if (stepper_number == "2") {
|
||||
// ts.add(
|
||||
// STEPPER2, stepper_speed.toInt(), [&](void *) {
|
||||
// int steps_int = abs(jsonReadInt(configOptionJson, "steps2") * 2);
|
||||
// static int count;
|
||||
// count++;
|
||||
// String pin_step = selectToMarker(jsonReadStr(configOptionJson, "stepper2"), " ");
|
||||
// digitalWrite(pin_step.toInt(), !digitalRead(pin_step.toInt()));
|
||||
// yield();
|
||||
// if (count > steps_int) {
|
||||
// digitalWrite(pin_step.toInt(), LOW);
|
||||
// ts.remove(STEPPER2);
|
||||
// count = 0;
|
||||
// }
|
||||
// },
|
||||
// nullptr, true);
|
||||
// }
|
||||
//}
|
||||
//#endif
|
||||
////====================================================================================================================================================
|
||||
////=================================================================Сервоприводы=======================================================================
|
||||
//#ifdef SERVO_ENABLED
|
||||
////servo 1 13 50 Мой#сервопривод Сервоприводы 0 100 0 180 2
|
||||
//void servo_() {
|
||||
// String number = sCmd.next();
|
||||
// uint8_t pin = String(sCmd.next()).toInt();
|
||||
// int value = String(sCmd.next()).toInt();
|
||||
//
|
||||
// String widget = sCmd.next();
|
||||
// String page = sCmd.next();
|
||||
//
|
||||
// int min_value = String(sCmd.next()).toInt();
|
||||
// int max_value = String(sCmd.next()).toInt();
|
||||
// int min_deg = String(sCmd.next()).toInt();
|
||||
// int max_deg = String(sCmd.next()).toInt();
|
||||
//
|
||||
// String pageNumber = sCmd.next();
|
||||
//
|
||||
// jsonWriteStr(configOptionJson, "servo_pin" + number, String(pin, DEC));
|
||||
//
|
||||
// value = map(value, min_value, max_value, min_deg, max_deg);
|
||||
//
|
||||
// Servo *servo = myServo.create(number.toInt(), pin);
|
||||
// servo->write(value);
|
||||
//#ifdef ESP32
|
||||
// myServo1.attach(servo_pin.toInt(), 500, 2400);
|
||||
// myServo1.write(start_state_int);
|
||||
//#endif
|
||||
//
|
||||
// jsonWriteInt(configOptionJson, "s_min_val" + number, min_value);
|
||||
// jsonWriteInt(configOptionJson, "s_max_val" + number, max_value);
|
||||
// jsonWriteInt(configOptionJson, "s_min_deg" + number, min_deg);
|
||||
// jsonWriteInt(configOptionJson, "s_max_deg" + number, max_deg);
|
||||
//
|
||||
// jsonWriteInt(configLiveJson, "servo" + number, value);
|
||||
//
|
||||
// createWidgetParam(widget, page, pageNumber, "range", "servo" + number, "min", String(min_value), "max", String(max_value), "k", "1");
|
||||
//}
|
||||
//
|
||||
//void servoSet() {
|
||||
// String number = sCmd.next();
|
||||
// int value = String(sCmd.next()).toInt();
|
||||
//
|
||||
// value = map(value,
|
||||
// jsonReadInt(configOptionJson, "s_min_val" + number),
|
||||
// jsonReadInt(configOptionJson, "s_max_val" + number),
|
||||
// jsonReadInt(configOptionJson, "s_min_deg" + number),
|
||||
// jsonReadInt(configOptionJson, "s_max_deg" + number));
|
||||
//
|
||||
// Servo *servo = myServo.get(number.toInt());
|
||||
// if (servo) {
|
||||
// servo->write(value);
|
||||
// }
|
||||
//
|
||||
// eventGen2("servo", number);
|
||||
// jsonWriteInt(configLiveJson, "servo" + number, value);
|
||||
// publishStatus("servo" + number, String(value, DEC));
|
||||
//}
|
||||
//#endif
|
||||
////====================================================================================================================================================
|
||||
////=============================================================Модуль сериал порта=======================================================================
|
||||
//
|
||||
//#ifdef SERIAL_ENABLED
|
||||
//void serialBegin() {
|
||||
// String s_speed = sCmd.next();
|
||||
// String rxPin = sCmd.next();
|
||||
// String txPin = sCmd.next();
|
||||
//
|
||||
// if (mySerial) {
|
||||
// delete mySerial;
|
||||
// }
|
||||
//
|
||||
//#ifdef ESP8266
|
||||
// mySerial = new SoftwareSerial(rxPin.toInt(), txPin.toInt());
|
||||
// mySerial->begin(s_speed.toInt());
|
||||
//#else
|
||||
// mySerial = new HardwareSerial(2);
|
||||
// mySerial->begin(rxPin.toInt(), txPin.toInt());
|
||||
//#endif
|
||||
//
|
||||
// term = new Terminal(mySerial);
|
||||
// term->setEOL(LF);
|
||||
// term->enableColors(false);
|
||||
// term->enableControlCodes(false);
|
||||
// term->enableEcho(false);
|
||||
// term->setOnReadLine([](const char *str) {
|
||||
// String line = String(str);
|
||||
// loopCmdAdd(line);
|
||||
// });
|
||||
//}
|
||||
//
|
||||
//void getData() {
|
||||
// String param = sCmd.next();
|
||||
// String res = param.length() ? jsonReadStr(configLiveJson, param) : configLiveJson;
|
||||
// if (term) {
|
||||
// term->println(res.c_str());
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//void serialWrite() {
|
||||
// String payload = sCmd.next();
|
||||
// if (term) {
|
||||
// term->println(payload.c_str());
|
||||
// }
|
||||
//}
|
||||
//#endif
|
||||
////====================================================================================================================================================
|
||||
////=================================================Глобальные команды удаленного управления===========================================================
|
||||
//
|
||||
//void mqttOrderSend() {
|
||||
// String id = sCmd.next();
|
||||
// String order = sCmd.next();
|
||||
//
|
||||
// String all_line = jsonReadStr(configSetupJson, "mqttPrefix") + "/" + id + "/order";
|
||||
// mqtt.publish(all_line.c_str(), order.c_str(), false);
|
||||
//}
|
||||
//
|
||||
//void httpOrderSend() {
|
||||
// String ip = sCmd.next();
|
||||
// String order = sCmd.next();
|
||||
// order.replace("_", "%20");
|
||||
// String url = "http://" + ip + "/cmd?command=" + order;
|
||||
// getURL(url);
|
||||
//}
|
||||
//
|
||||
//void firmwareUpdate() {
|
||||
// myNotAsyncActions->make(do_UPGRADE);
|
||||
//}
|
||||
//
|
||||
//void firmwareVersion() {
|
||||
// String widget = sCmd.next();
|
||||
// String page = sCmd.next();
|
||||
// String pageNumber = sCmd.next();
|
||||
//
|
||||
// jsonWriteStr(configLiveJson, "firmver", FIRMWARE_VERSION);
|
||||
// createWidget(widget, page, pageNumber, "anydata", "firmver");
|
||||
//}
|
||||
@@ -1,130 +0,0 @@
|
||||
#include "ItemsList.h"
|
||||
|
||||
#include "Class/NotAsync.h"
|
||||
#include "Init.h"
|
||||
#include "Utils/StringUtils.h"
|
||||
|
||||
static const char* firstLine PROGMEM = "Удалить;Тип элемента;Id;Виджет;Имя вкладки;Имя виджета;Позиция виджета";
|
||||
|
||||
void itemsListInit() {
|
||||
myNotAsyncActions->add(
|
||||
do_deviceInit, [&](void*) {
|
||||
Device_init();
|
||||
},
|
||||
nullptr);
|
||||
|
||||
myNotAsyncActions->add(
|
||||
do_delChoosingItems, [&](void*) {
|
||||
delChoosingItems();
|
||||
},
|
||||
nullptr);
|
||||
}
|
||||
|
||||
void addItem(String name) {
|
||||
String item = readFile("items/" + name + ".txt", 1024);
|
||||
|
||||
name = deleteToMarkerLast(name, ".");
|
||||
|
||||
item.replace("id", name + "-" + String(getNewElementNumber("id.txt")));
|
||||
item.replace("order", String(getNewElementNumber("order.txt")));
|
||||
|
||||
if (item.indexOf("pin") != -1) { //all cases (random pins from available)
|
||||
item.replace("pin", "pin[" + String(getFreePinAll()) + "]");
|
||||
} else
|
||||
|
||||
if (item.indexOf("gol") != -1) { //analog
|
||||
item.replace("gol", "pin[" + String(getFreePinAnalog()) + "]");
|
||||
} else
|
||||
|
||||
if (item.indexOf("cin") != -1) { //ultrasonic
|
||||
item.replace("cin", "pin[" + String(getFreePinAll()) + "," + String(getFreePinAll()) + "]");
|
||||
} else
|
||||
|
||||
if (item.indexOf("sal") != -1) { //dallas
|
||||
item.replace("sal", "pin[2]");
|
||||
} else
|
||||
|
||||
if (item.indexOf("thd") != -1) { //dht11/22
|
||||
item.replace("thd", "pin[2]");
|
||||
}
|
||||
|
||||
item.replace("\r\n", "");
|
||||
item.replace("\r", "");
|
||||
item.replace("\n", "");
|
||||
addFile(DEVICE_CONFIG_FILE, "\n" + item);
|
||||
}
|
||||
|
||||
void addPreset(String name) {
|
||||
String preset = readFile("presets/" + name + ".txt", 4048);
|
||||
addFile(DEVICE_CONFIG_FILE, "\n" + preset);
|
||||
|
||||
name.replace(".c",".s");
|
||||
|
||||
String scenario = readFile("presets/" + name + ".txt", 4048);
|
||||
removeFile(DEVICE_SCENARIO_FILE);
|
||||
addFile(DEVICE_SCENARIO_FILE, scenario);
|
||||
}
|
||||
|
||||
void delAllItems() {
|
||||
removeFile(DEVICE_CONFIG_FILE);
|
||||
addFile(DEVICE_CONFIG_FILE, String(firstLine));
|
||||
removeFile("id.txt");
|
||||
removeFile("order.txt");
|
||||
removeFile("pins.txt");
|
||||
}
|
||||
|
||||
uint8_t getNewElementNumber(String file) {
|
||||
uint8_t number = readFile(file, 100).toInt();
|
||||
number++;
|
||||
removeFile(file);
|
||||
addFile(file, String(number));
|
||||
return number;
|
||||
}
|
||||
|
||||
uint8_t getFreePinAll() {
|
||||
#ifdef ESP8266
|
||||
uint8_t pins[] = {0, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5};
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
uint8_t pins[] = {0, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5};
|
||||
#endif
|
||||
uint8_t array_sz = sizeof(pins) / sizeof(pins[0]);
|
||||
uint8_t i = getNewElementNumber("pins.txt");
|
||||
if (i < array_sz) {
|
||||
return pins[i];
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t getFreePinAnalog() {
|
||||
#ifdef ESP8266
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
void delChoosingItems() {
|
||||
File configFile = LittleFS.open("/" + String(DEVICE_CONFIG_FILE), "r");
|
||||
if (!configFile) {
|
||||
return;
|
||||
}
|
||||
configFile.seek(0, SeekSet);
|
||||
String finalConf;
|
||||
bool firstLine = true;
|
||||
while (configFile.position() != configFile.size()) {
|
||||
String item = configFile.readStringUntil('\n');
|
||||
if (firstLine) {
|
||||
finalConf += item;
|
||||
} else {
|
||||
int checkbox = selectToMarker(item, ";").toInt();
|
||||
if (checkbox == 0) {
|
||||
finalConf += "\n" + item;
|
||||
}
|
||||
}
|
||||
firstLine = false;
|
||||
}
|
||||
removeFile(String(DEVICE_CONFIG_FILE));
|
||||
addFile(String(DEVICE_CONFIG_FILE), finalConf);
|
||||
Serial.println(finalConf);
|
||||
configFile.close();
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
#include "Module/Telnet.h"
|
||||
|
||||
bool Telnet::onInit() {
|
||||
_server = new WiFiServer(_port);
|
||||
_term = new Terminal();
|
||||
_term->enableControlCodes();
|
||||
_term->enableEcho(false);
|
||||
_term->setStream(&_client);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Telnet::onEnd() {
|
||||
delete _server;
|
||||
}
|
||||
|
||||
bool Telnet::onStart() {
|
||||
_server->begin();
|
||||
_server->setNoDelay(true);
|
||||
return true;
|
||||
}
|
||||
|
||||
void Telnet::onStop() {
|
||||
if (hasClient()) {
|
||||
_client.stop();
|
||||
}
|
||||
_server->stop();
|
||||
}
|
||||
|
||||
bool Telnet::hasClient() { return _client.connected(); }
|
||||
|
||||
void Telnet::sendData(const String& data) {
|
||||
if (hasClient()) {
|
||||
_client.write(data.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void Telnet::setCommandShell(CommandShell* shell) {
|
||||
_shell = shell;
|
||||
_shell->setTerm(_term);
|
||||
}
|
||||
|
||||
void Telnet::setEventHandler(TelnetEventHandler h) { _eventHandler = h; }
|
||||
|
||||
void Telnet::onLoop() {
|
||||
if (_server->hasClient()) {
|
||||
if (!_client) {
|
||||
_client = _server->available();
|
||||
} else {
|
||||
if (!_client.connected()) {
|
||||
_server->stop();
|
||||
_client = _server->available();
|
||||
} else {
|
||||
WiFiClient rejected;
|
||||
rejected = _server->available();
|
||||
rejected.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_lastConnected != hasClient()) {
|
||||
_lastConnected = hasClient();
|
||||
if (_lastConnected) {
|
||||
onConnect();
|
||||
} else {
|
||||
onDisconnect();
|
||||
}
|
||||
}
|
||||
|
||||
if (hasClient() && _shell != nullptr) _shell->loop();
|
||||
}
|
||||
|
||||
bool Telnet::isShellActive() {
|
||||
return _shell->active();
|
||||
}
|
||||
|
||||
void Telnet::onConnect() {
|
||||
if (_eventHandler) {
|
||||
_eventHandler(TE_CONNECTED, &_client);
|
||||
}
|
||||
}
|
||||
|
||||
void Telnet::onDisconnect() {
|
||||
if (_eventHandler) {
|
||||
_eventHandler(TE_DISCONNECTED, nullptr);
|
||||
}
|
||||
}
|
||||
@@ -1,320 +0,0 @@
|
||||
#include "Module/Terminal.h"
|
||||
|
||||
#include "Utils/TimeUtils.h"
|
||||
|
||||
#define INPUT_MAX_LENGHT 255
|
||||
|
||||
Terminal::Terminal(Stream *stream) : _stream{stream},
|
||||
_line(INPUT_MAX_LENGHT),
|
||||
_cc_pos(0),
|
||||
_color(false),
|
||||
_controlCodes(false),
|
||||
_echo(false),
|
||||
_eol(CRLF) { state = ST_NORMAL; };
|
||||
|
||||
void Terminal::setStream(Stream *stream) {
|
||||
_stream = stream;
|
||||
}
|
||||
|
||||
void Terminal::setOnReadLine(TerminalInputEventHandler h) { inputHandler_ = h; }
|
||||
|
||||
void Terminal::setOnEvent(TerminalEventHandler h) { eventHandler_ = h; }
|
||||
|
||||
bool Terminal::available() {
|
||||
return _stream != nullptr ? _stream->available() : false;
|
||||
}
|
||||
|
||||
void Terminal::setEOL(EOLType_t eol) {
|
||||
_eol = eol;
|
||||
}
|
||||
|
||||
void Terminal::enableEcho(bool enabled) {
|
||||
_echo = enabled;
|
||||
}
|
||||
|
||||
void Terminal::enableColors(bool enabled) {
|
||||
_color = enabled;
|
||||
}
|
||||
|
||||
void Terminal::enableControlCodes(bool enabled) {
|
||||
_controlCodes = enabled;
|
||||
}
|
||||
|
||||
void Terminal::quit() {}
|
||||
|
||||
void Terminal::loop() {
|
||||
if (_stream == nullptr || !_stream->available()) return;
|
||||
|
||||
byte moveX = 0;
|
||||
byte moveY = 0;
|
||||
|
||||
char c = _stream->read();
|
||||
|
||||
_lastReceived = millis();
|
||||
|
||||
if (state == ST_INACTIVE) {
|
||||
// wait for CR
|
||||
if (c == CHAR_CR) {
|
||||
if (eventHandler_) {
|
||||
eventHandler_(EVENT_OPEN, _stream);
|
||||
state = ST_NORMAL;
|
||||
}
|
||||
}
|
||||
// or ignore all other
|
||||
return;
|
||||
}
|
||||
|
||||
if (c == CHAR_LF || c == CHAR_NULL || c == CHAR_BIN)
|
||||
return;
|
||||
|
||||
// Esc
|
||||
if (c == CHAR_ESC || c == 195) {
|
||||
state = ST_ESC_SEQ;
|
||||
_cc_pos = 0;
|
||||
for (size_t i = 0; i < 2; ++i) {
|
||||
bool timeout = false;
|
||||
while (!_stream->available() &&
|
||||
!(timeout = millis_since(_lastReceived) > 10)) {
|
||||
delay(0);
|
||||
}
|
||||
if (timeout) {
|
||||
state = ST_NORMAL;
|
||||
break;
|
||||
}
|
||||
_lastReceived = millis();
|
||||
c = _stream->read();
|
||||
_cc_buf[_cc_pos] = c;
|
||||
if ((c == '[') || ((c >= 'A' && c <= 'Z') || c == '~')) {
|
||||
_cc_pos++;
|
||||
_cc_buf[++_cc_pos] = '\x00';
|
||||
}
|
||||
}
|
||||
uint8_t i;
|
||||
for (i = 0; i < 10; ++i) {
|
||||
if (strcmp(_cc_buf, keyMap[i].cc) == 0) {
|
||||
c = keyMap[i].ch;
|
||||
state = ST_NORMAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (state == ST_ESC_SEQ) {
|
||||
state = ST_NORMAL;
|
||||
return;
|
||||
}
|
||||
|
||||
// WHEN NORMAL
|
||||
if (state == ST_NORMAL) {
|
||||
if (c == CHAR_ESC) {
|
||||
if (!_line.available()) {
|
||||
// QUIT
|
||||
state = ST_INACTIVE;
|
||||
if (eventHandler_)
|
||||
eventHandler_(EVENT_CLOSE, _stream);
|
||||
} else {
|
||||
// CLEAR
|
||||
_line.clear();
|
||||
if (_controlCodes) {
|
||||
clear_line();
|
||||
} else {
|
||||
println();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (c) {
|
||||
case CHAR_CR:
|
||||
println();
|
||||
if (inputHandler_)
|
||||
inputHandler_(_line.c_str());
|
||||
_line.clear();
|
||||
moveY++;
|
||||
break;
|
||||
case CHAR_TAB:
|
||||
if (eventHandler_)
|
||||
eventHandler_(EVENT_TAB, _stream);
|
||||
return;
|
||||
case KEY_LEFT:
|
||||
if (_line.prev())
|
||||
moveX--;
|
||||
break;
|
||||
case KEY_RIGHT:
|
||||
if (_line.next())
|
||||
moveX++;
|
||||
break;
|
||||
case KEY_HOME:
|
||||
moveX = -1 * _line.home();
|
||||
break;
|
||||
case KEY_END:
|
||||
moveX = _line.end();
|
||||
break;
|
||||
case CHAR_BS:
|
||||
case KEY_DEL:
|
||||
if (_line.backspace()) {
|
||||
backsp();
|
||||
moveX--;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// printable ascii 7bit or printable 8bit ISO8859
|
||||
if ((c & '\x7F') >= 32 && (c & '\x7F') < 127)
|
||||
if (_line.write(c)) {
|
||||
if (_echo) write(c);
|
||||
moveX++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// if (controlCodesEnabled)
|
||||
// move(startY + moveY, startX + moveX);
|
||||
}
|
||||
}
|
||||
|
||||
bool Terminal::setLine(const uint8_t *ptr, size_t size) {
|
||||
_line.clear();
|
||||
if (_line.write(ptr, size))
|
||||
print(_line.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
CharBuffer &Terminal::getLine() { return _line; }
|
||||
|
||||
void Terminal::start() {
|
||||
if (_controlCodes) initscr();
|
||||
println();
|
||||
}
|
||||
|
||||
void Terminal::initscr() {
|
||||
write_P(SEQ_LOAD_G1);
|
||||
attrset(A_NORMAL);
|
||||
move(0, 0);
|
||||
clear();
|
||||
}
|
||||
|
||||
void Terminal::attrset(const uint16_t attr) {
|
||||
uint8_t i;
|
||||
|
||||
if (attr != this->attr) {
|
||||
this->write_P(SEQ_ATTRSET);
|
||||
|
||||
i = (attr & F_COLOR) >> 8;
|
||||
|
||||
if (i >= 1 && i <= 8) {
|
||||
this->write_P(SEQ_ATTRSET_FCOLOR);
|
||||
this->write(i - 1 + '0');
|
||||
}
|
||||
|
||||
i = (attr & B_COLOR) >> 12;
|
||||
|
||||
if (i >= 1 && i <= 8) {
|
||||
this->write_P(SEQ_ATTRSET_BCOLOR);
|
||||
this->write(i - 1 + '0');
|
||||
}
|
||||
|
||||
if (attr & A_REVERSE)
|
||||
this->write_P(SEQ_ATTRSET_REVERSE);
|
||||
if (attr & A_UNDERLINE)
|
||||
this->write_P(SEQ_ATTRSET_UNDERLINE);
|
||||
if (attr & A_BLINK)
|
||||
this->write_P(SEQ_ATTRSET_BLINK);
|
||||
if (attr & A_BOLD)
|
||||
this->write_P(SEQ_ATTRSET_BOLD);
|
||||
if (attr & A_DIM)
|
||||
this->write_P(SEQ_ATTRSET_DIM);
|
||||
this->write('m');
|
||||
this->attr = attr;
|
||||
}
|
||||
}
|
||||
|
||||
void Terminal::clear() { write_P(SEQ_CLEAR); }
|
||||
|
||||
void Terminal::clear_line() {
|
||||
write(CHAR_CR);
|
||||
write_P(ESC_CLEAR_EOL);
|
||||
}
|
||||
|
||||
void Terminal::move(uint8_t y, uint8_t x) {
|
||||
write_P(SEQ_CSI);
|
||||
writeByDigit(y + 1);
|
||||
write(';');
|
||||
writeByDigit(x + 1);
|
||||
write('H');
|
||||
curY = y;
|
||||
curX = x;
|
||||
}
|
||||
|
||||
void Terminal::writeByDigit(uint8_t i) {
|
||||
uint8_t ii;
|
||||
if (i >= 10) {
|
||||
if (i >= 100) {
|
||||
ii = i / 100;
|
||||
write(ii + '0');
|
||||
i -= 100 * ii;
|
||||
}
|
||||
ii = i / 10;
|
||||
write(ii + '0');
|
||||
i -= 10 * ii;
|
||||
}
|
||||
write(i + '0');
|
||||
}
|
||||
|
||||
void Terminal::backsp() {
|
||||
write(CHAR_BS);
|
||||
write(CHAR_SPACE);
|
||||
write(CHAR_BS);
|
||||
}
|
||||
|
||||
size_t Terminal::println(const char *str) {
|
||||
size_t n = print(str);
|
||||
return n += println();
|
||||
}
|
||||
|
||||
size_t Terminal::println(void) {
|
||||
size_t n = 0;
|
||||
switch (_eol) {
|
||||
case CRLF:
|
||||
n += write(CHAR_CR);
|
||||
n += write(CHAR_LF);
|
||||
break;
|
||||
case LF:
|
||||
n += write(CHAR_LF);
|
||||
break;
|
||||
case LFCR:
|
||||
n += write(CHAR_LF);
|
||||
n += write(CHAR_CR);
|
||||
break;
|
||||
case CR:
|
||||
n += write(CHAR_CR);
|
||||
break;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Terminal::write(uint8_t ch) {
|
||||
size_t n = 0;
|
||||
if (_stream)
|
||||
n = _stream->write(ch);
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Terminal::write_P(PGM_P str) {
|
||||
uint8_t ch;
|
||||
size_t n = 0;
|
||||
while ((ch = pgm_read_byte(str + n)) != '\x0') {
|
||||
_stream->write(ch);
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t Terminal::write(const uint8_t *buf, size_t size) {
|
||||
size_t n = 0;
|
||||
while (size--) {
|
||||
if (_stream->write(*buf++))
|
||||
n++;
|
||||
else
|
||||
break;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -1,288 +0,0 @@
|
||||
#include "MqttClient.h"
|
||||
|
||||
#include <LittleFS.h>
|
||||
#include "items/LoggingClass.h"
|
||||
#include "Class/NotAsync.h"
|
||||
#include "Global.h"
|
||||
#include "Init.h"
|
||||
|
||||
String mqttPrefix;
|
||||
String mqttRootDevice;
|
||||
|
||||
void mqttInit() {
|
||||
myNotAsyncActions->add(
|
||||
do_MQTTPARAMSCHANGED, [&](void*) {
|
||||
mqttReconnect();
|
||||
},
|
||||
nullptr);
|
||||
|
||||
mqtt.setCallback(mqttCallback);
|
||||
|
||||
ts.add(
|
||||
WIFI_MQTT_CONNECTION_CHECK, MQTT_RECONNECT_INTERVAL,
|
||||
[&](void*) {
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
SerialPrint("I", "WIFI", "OK");
|
||||
if (mqtt.connected()) {
|
||||
SerialPrint("I", "MQTT", "OK");
|
||||
setLedStatus(LED_OFF);
|
||||
}
|
||||
else {
|
||||
SerialPrint("E", "MQTT", "lost connection");
|
||||
mqttConnect();
|
||||
}
|
||||
}
|
||||
else {
|
||||
SerialPrint("E", "WIFI", "Lost WiFi connection");
|
||||
ts.remove(WIFI_MQTT_CONNECTION_CHECK);
|
||||
startAPMode();
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
|
||||
void mqttDisconnect() {
|
||||
SerialPrint("I", "MQTT", "disconnect");
|
||||
mqtt.disconnect();
|
||||
}
|
||||
|
||||
void mqttReconnect() {
|
||||
mqttDisconnect();
|
||||
mqttConnect();
|
||||
}
|
||||
|
||||
void mqttLoop() {
|
||||
if (!isNetworkActive() || !mqtt.connected()) {
|
||||
return;
|
||||
}
|
||||
mqtt.loop();
|
||||
}
|
||||
|
||||
void mqttSubscribe() {
|
||||
SerialPrint("I", "MQTT", "subscribe");
|
||||
mqtt.subscribe(mqttPrefix.c_str());
|
||||
mqtt.subscribe((mqttRootDevice + "/+/control").c_str());
|
||||
mqtt.subscribe((mqttRootDevice + "/order").c_str());
|
||||
mqtt.subscribe((mqttRootDevice + "/update").c_str());
|
||||
mqtt.subscribe((mqttRootDevice + "/devc").c_str());
|
||||
mqtt.subscribe((mqttRootDevice + "/devs").c_str());
|
||||
}
|
||||
|
||||
boolean mqttConnect() {
|
||||
SerialPrint("I", "MQTT", "start connection");
|
||||
String addr = jsonReadStr(configSetupJson, "mqttServer");
|
||||
if (!addr) {
|
||||
SerialPrint("E", "MQTT", "no broker address");
|
||||
return false;
|
||||
}
|
||||
int port = jsonReadInt(configSetupJson, "mqttPort");
|
||||
String user = jsonReadStr(configSetupJson, "mqttUser");
|
||||
String pass = jsonReadStr(configSetupJson, "mqttPass");
|
||||
mqttPrefix = jsonReadStr(configSetupJson, "mqttPrefix");
|
||||
mqttRootDevice = mqttPrefix + "/" + chipId;
|
||||
SerialPrint("I", "MQTT", "broker " + addr + ":" + String(port, DEC));
|
||||
SerialPrint("I", "MQTT", "topic " + mqttRootDevice);
|
||||
setLedStatus(LED_FAST);
|
||||
mqtt.setServer(addr.c_str(), port);
|
||||
bool res = false;
|
||||
if (!mqtt.connected()) {
|
||||
if (mqtt.connect(chipId.c_str(), user.c_str(), pass.c_str())) {
|
||||
SerialPrint("I", "MQTT", "connected");
|
||||
setLedStatus(LED_OFF);
|
||||
mqttSubscribe();
|
||||
res = true;
|
||||
}
|
||||
else {
|
||||
SerialPrint("E", "MQTT", "could't connect, retry in " + String(MQTT_RECONNECT_INTERVAL / 1000) + "s");
|
||||
setLedStatus(LED_FAST);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void mqttCallback(char* topic, uint8_t* payload, size_t length) {
|
||||
String topicStr = String(topic);
|
||||
SerialPrint("I", "MQTT", topicStr);
|
||||
String payloadStr;
|
||||
payloadStr.reserve(length + 1);
|
||||
for (size_t i = 0; i < length; i++) {
|
||||
payloadStr += (char)payload[i];
|
||||
}
|
||||
|
||||
SerialPrint("I", "MQTT", payloadStr);
|
||||
|
||||
if (payloadStr.startsWith("HELLO")) {
|
||||
SerialPrint("I", "MQTT", "Full update");
|
||||
publishWidgets();
|
||||
publishState();
|
||||
#ifdef LOGGING_ENABLED
|
||||
choose_log_date_and_send();
|
||||
#endif
|
||||
|
||||
}
|
||||
else if (topicStr.indexOf("control")) {
|
||||
|
||||
String key = selectFromMarkerToMarker(topicStr, "/", 3);
|
||||
|
||||
orderBuf += key;
|
||||
orderBuf += " ";
|
||||
orderBuf += payloadStr;
|
||||
orderBuf += ",";
|
||||
|
||||
}
|
||||
else if (topicStr.indexOf("order")) {
|
||||
payloadStr.replace("_", " ");
|
||||
orderBuf += payloadStr;
|
||||
orderBuf += ",";
|
||||
|
||||
}
|
||||
else if (topicStr.indexOf("update")) {
|
||||
if (payloadStr == "1") {
|
||||
myNotAsyncActions->make(do_UPGRADE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean publish(const String& topic, const String& data) {
|
||||
if (mqtt.beginPublish(topic.c_str(), data.length(), false)) {
|
||||
mqtt.print(data);
|
||||
return mqtt.endPublish();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean publishData(const String& topic, const String& data) {
|
||||
String path = mqttRootDevice + "/" + topic;
|
||||
if (!publish(path, data)) {
|
||||
SerialPrint("[E]", "MQTT", "on publish data");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean publishChart(const String& topic, const String& data) {
|
||||
String path = mqttRootDevice + "/" + topic + "/status";
|
||||
if (!publish(path, data)) {
|
||||
SerialPrint("[E]", "MQTT", "on publish chart");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
boolean publishControl(String id, String topic, String state) {
|
||||
String path = mqttPrefix + "/" + id + "/" + topic + "/control";
|
||||
return mqtt.publish(path.c_str(), state.c_str(), false);
|
||||
}
|
||||
|
||||
boolean publishChart_test(const String& topic, const String& data) {
|
||||
String path = mqttRootDevice + "/" + topic + "/status";
|
||||
return mqtt.publish(path.c_str(), data.c_str(), false);
|
||||
}
|
||||
|
||||
boolean publishStatus(const String& topic, const String& data) {
|
||||
String path = mqttRootDevice + "/" + topic + "/status";
|
||||
String json = "{}";
|
||||
jsonWriteStr(json, "status", data);
|
||||
return mqtt.publish(path.c_str(), json.c_str(), false);
|
||||
}
|
||||
|
||||
#ifdef LAYOUT_IN_RAM
|
||||
void publishWidgets() {
|
||||
if (all_widgets != "") {
|
||||
int counter = 0;
|
||||
String line;
|
||||
int psn_1 = 0;
|
||||
int psn_2;
|
||||
do {
|
||||
psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n
|
||||
line = all_widgets.substring(psn_1, psn_2);
|
||||
line.replace("\n", "");
|
||||
line.replace("\r\n", "");
|
||||
//jsonWriteStr(line, "id", String(counter));
|
||||
//jsonWriteStr(line, "pageId", String(counter));
|
||||
counter++;
|
||||
sendMQTT("config", line);
|
||||
Serial.println("[V] " + line);
|
||||
psn_1 = psn_2 + 1;
|
||||
} while (psn_2 + 2 < all_widgets.length());
|
||||
getMemoryLoad("I after send all widgets");
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef LAYOUT_IN_RAM
|
||||
void publishWidgets() {
|
||||
auto file = seekFile("layout.txt");
|
||||
if (!file) {
|
||||
SerialPrint("[E]", "MQTT", "no file layout.txt");
|
||||
return;
|
||||
}
|
||||
while (file.available()) {
|
||||
String payload = file.readStringUntil('\n');
|
||||
SerialPrint("I", "MQTT", "widgets: " + payload);
|
||||
publishData("config", payload);
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
#endif
|
||||
|
||||
void publishState() {
|
||||
// берет строку json и ключи превращает в топики а значения колючей в них посылает
|
||||
String str = configLiveJson;
|
||||
str.replace("{", "");
|
||||
str.replace("}", "");
|
||||
str += ",";
|
||||
|
||||
while (str.length()) {
|
||||
String tmp = selectToMarker(str, ",");
|
||||
|
||||
String topic = selectToMarker(tmp, "\":");
|
||||
topic.replace("\"", "");
|
||||
|
||||
String state = selectToMarkerLast(tmp, "\":");
|
||||
state.replace("\"", "");
|
||||
|
||||
if (topic != "timenow") {
|
||||
publishStatus(topic, state);
|
||||
}
|
||||
str = deleteBeforeDelimiter(str, ",");
|
||||
}
|
||||
}
|
||||
|
||||
const String getStateStr() {
|
||||
switch (mqtt.state()) {
|
||||
case -4:
|
||||
return F("no respond");
|
||||
break;
|
||||
case -3:
|
||||
return F("connection was broken");
|
||||
break;
|
||||
case -2:
|
||||
return F("connection failed");
|
||||
break;
|
||||
case -1:
|
||||
return F("client disconnected");
|
||||
break;
|
||||
case 0:
|
||||
return F("client connected");
|
||||
break;
|
||||
case 1:
|
||||
return F("doesn't support the requested version");
|
||||
break;
|
||||
case 2:
|
||||
return F("rejected the client identifier");
|
||||
break;
|
||||
case 3:
|
||||
return F("unable to accept the connection");
|
||||
break;
|
||||
case 4:
|
||||
return F("wrong username/password");
|
||||
break;
|
||||
case 5:
|
||||
return F("not authorized to connect");
|
||||
break;
|
||||
default:
|
||||
return F("unspecified");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
#include "MqttDiscovery.h"
|
||||
|
||||
namespace Discovery {
|
||||
|
||||
static const char json_is_defined[] = "is_defined";
|
||||
static const char jsonId[] = "id";
|
||||
static const char jsonBatt[] = "batt";
|
||||
static const char jsonLux[] = "lux";
|
||||
static const char jsonPres[] = "pres";
|
||||
static const char jsonFer[] = "fer";
|
||||
static const char jsonMoi[] = "moi";
|
||||
static const char jsonHum[] = "hum";
|
||||
static const char jsonTemp[] = "tem";
|
||||
static const char jsonStep[] = "steps";
|
||||
static const char jsonWeight[] = "weight";
|
||||
static const char jsonPresence[] = "presence";
|
||||
static const char jsonAltim[] = "altim";
|
||||
static const char jsonAltif[] = "altift";
|
||||
static const char jsonTempf[] = "tempf";
|
||||
static const char jsonMsg[] = "message";
|
||||
static const char jsonVal[] = "value";
|
||||
static const char jsonVolt[] = "volt";
|
||||
static const char jsonCurrent[] = "current";
|
||||
static const char jsonPower[] = "power";
|
||||
static const char jsonGpio[] = "gpio";
|
||||
static const char jsonFtcd[] = "ftcd";
|
||||
static const char jsonWm2[] = "wattsm2";
|
||||
static const char jsonAdc[] = "adc";
|
||||
static const char jsonPa[] = "pa";
|
||||
|
||||
const String getValueJson(const char* str) {
|
||||
char buf[32];
|
||||
sprintf(buf, "{{ value_json.%s }}", str);
|
||||
return buf;
|
||||
}
|
||||
|
||||
void createDiscovery(
|
||||
const char* type, const char* name, const char* clazz,
|
||||
const char* value_template, const char* payload_on, const char* payload_off,
|
||||
const char* maasure_unit, int off_delay, const char* has_payload, const char* no_payload,
|
||||
const char* avail_topi, const char* cmd_topic, const char* state_topic, bool child) {
|
||||
//const char* unique_id = getUniqueId(name).c_str();
|
||||
}
|
||||
|
||||
void createADC(const char* name) {
|
||||
createDiscovery(
|
||||
"Type", "Name", "Clazz",
|
||||
"Value", "Payload", "NoPayload",
|
||||
"Measure", 0, "HasPayload", "NoPayload",
|
||||
"", "", "", false);
|
||||
}
|
||||
|
||||
void createSwitch(const char* name) {
|
||||
createDiscovery(
|
||||
"Type", "Name", "Clazz",
|
||||
"Value", "Payload", "NoPayload",
|
||||
"Measure", 0, "HasPayload", "NoPayload",
|
||||
"", "", "", false);
|
||||
}
|
||||
// component,
|
||||
// type,
|
||||
// name,
|
||||
// availability topic,
|
||||
// device class,
|
||||
// value template, payload on, payload off, unit of measurement
|
||||
const char* BMEsensor[6][8] = {
|
||||
{"sensor", "tempc", "bme", "temperature", "", "", "°C"}, //jsonTemp
|
||||
{"sensor", "tempf", "bme", "temperature", "", "", "°F"}, //jsonTempf
|
||||
{"sensor", "pa", "bme", "", "", "", "hPa"}, //jsonPa
|
||||
{"sensor", "hum", "bme", "humidity", "", "", "%"}, // jsonHum
|
||||
{"sensor", "altim", "bme", "", "", "", "m"}, //jsonAltim
|
||||
{"sensor", "altift", "bme", "", "", "", "ft"} // jsonAltif
|
||||
};
|
||||
|
||||
} // namespace Discovery
|
||||
@@ -1,60 +0,0 @@
|
||||
#include "Global.h"
|
||||
|
||||
void Push_init() {
|
||||
server.on("/pushingboxDate", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
if (request->hasArg("pushingbox_id")) {
|
||||
jsonWriteStr(configSetupJson, "pushingbox_id", request->getParam("pushingbox_id")->value());
|
||||
}
|
||||
|
||||
saveConfig();
|
||||
|
||||
request->send(200, "text/text", "ok"); // отправляем ответ о выполнении
|
||||
});
|
||||
}
|
||||
|
||||
void pushControl() {
|
||||
String title = sCmd.next();
|
||||
title.replace("#", " ");
|
||||
String body = sCmd.next();
|
||||
body.replace("#", " ");
|
||||
|
||||
static String body_old;
|
||||
|
||||
const char* logServer = "api.pushingbox.com";
|
||||
String deviceId = jsonReadStr(configSetupJson, "pushingbox_id");
|
||||
|
||||
//Serial.println("- starting client");
|
||||
|
||||
WiFiClient client_push;
|
||||
|
||||
//Serial.println("- connecting to pushing server: " + String(logServer));
|
||||
if (!client_push.connect(logServer, 80)) {
|
||||
//Serial.println("- not connected");
|
||||
} else {
|
||||
//Serial.println("- succesfully connected");
|
||||
|
||||
String postStr = "devid=";
|
||||
postStr += String(deviceId);
|
||||
|
||||
postStr += "&title=";
|
||||
postStr += String(title);
|
||||
|
||||
postStr += "&body=";
|
||||
postStr += String(body);
|
||||
|
||||
postStr += "\r\n\r\n";
|
||||
|
||||
//Serial.println("- sending data...");
|
||||
|
||||
client_push.print(F("POST /pushingbox HTTP/1.1\n"));
|
||||
client_push.print(F("Host: api.pushingbox.com\n"));
|
||||
client_push.print(F("Connection: close\n"));
|
||||
client_push.print(F("Content-Type: application/x-www-form-urlencoded\n"));
|
||||
client_push.print(F("Content-Length: "));
|
||||
client_push.print(postStr.length());
|
||||
client_push.print("\n\n");
|
||||
client_push.print(postStr);
|
||||
}
|
||||
client_push.stop();
|
||||
//Serial.println("- stopping the client");
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
#include "RemoteOrdersUdp.h"
|
||||
#include <Arduino.h>
|
||||
#include "Global.h"
|
||||
|
||||
#ifdef UDP_ENABLED
|
||||
AsyncUDP asyncUdp;
|
||||
|
||||
void asyncUdpInit() {
|
||||
//if (asyncUdp.listen(1234)) {
|
||||
if (asyncUdp.listenMulticast(IPAddress(239, 255, 255, 255), 1234)) {
|
||||
asyncUdp.onPacket([](AsyncUDPPacket packet) {
|
||||
//Serial.print("UDP Packet Type: ");
|
||||
//Serial.print(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast");
|
||||
//
|
||||
//Serial.print(", From: ");
|
||||
//Serial.print(packet.remoteIP());
|
||||
//Serial.print(":");
|
||||
//Serial.print(packet.remotePort());
|
||||
//
|
||||
//Serial.print(", To: ");
|
||||
//Serial.print(packet.localIP());
|
||||
//Serial.print(":");
|
||||
//Serial.print(packet.localPort());
|
||||
//
|
||||
//Serial.print(", Length: ");
|
||||
//Serial.print(packet.length());
|
||||
//
|
||||
//Serial.print(", Data: ");
|
||||
//Serial.write(packet.data(), packet.length());
|
||||
|
||||
String data = uint8tToString(packet.data(), packet.length());
|
||||
Serial.print("[i] [udp] Packet received: '");
|
||||
Serial.print(data);
|
||||
if (udpPacketValidation(data)) {
|
||||
udpPacketParse(data);
|
||||
//Serial.println("', Packet valid");
|
||||
} else {
|
||||
//Serial.println("', Packet invalid");
|
||||
}
|
||||
|
||||
//reply to the client
|
||||
|
||||
packet.printf("Got %u bytes of data", packet.length());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
String uint8tToString(uint8_t* data, size_t len) {
|
||||
String ret;
|
||||
while (len--) {
|
||||
ret += (char)*data++;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
bool udpPacketValidation(String& data) {
|
||||
if (data.indexOf("iotm;") != -1 && data.indexOf(getChipId()) != -1) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//iotm;chipid;button-out-1_1
|
||||
void udpPacketParse(String& data) {
|
||||
data = selectFromMarkerToMarker(data, ";", 2);
|
||||
data.replace("_", " ");
|
||||
orderBuf += data + ",";
|
||||
}
|
||||
#endif
|
||||
62
src/SSDP.cpp
62
src/SSDP.cpp
@@ -1,62 +0,0 @@
|
||||
#include "SSDP.h"
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
#ifdef SSDP_ENABLED
|
||||
#ifdef ESP8266
|
||||
#include <ESP8266SSDP.h>
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
#include <ESP32SSDP.h>
|
||||
#endif
|
||||
|
||||
String xmlNode(String tags, String data);
|
||||
|
||||
String decToHex(uint32_t decValue, byte desiredStringLength);
|
||||
|
||||
void SsdpInit() {
|
||||
server.on("/description.xml", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
String ssdpSend = F("<root xmlns=\"urn:schemas-upnp-org:device-1-0\">");
|
||||
String ssdpHeder = xmlNode(F("major"), "1");
|
||||
ssdpHeder += xmlNode(F("minor"), "0");
|
||||
ssdpHeder = xmlNode(F("specVersion"), ssdpHeder);
|
||||
ssdpHeder += xmlNode(F("URLBase"), "http://" + WiFi.localIP().toString());
|
||||
String ssdpDescription = xmlNode(F("deviceType"), F("upnp:rootdevice"));
|
||||
ssdpDescription += xmlNode(F("friendlyName"), jsonReadStr(configSetupJson, F("name")));
|
||||
ssdpDescription += xmlNode(F("presentationURL"), "/");
|
||||
ssdpDescription += xmlNode(F("serialNumber"), getChipId());
|
||||
#ifdef ESP8266
|
||||
ssdpDescription += xmlNode(F("modelName"), F("ESP8266"));
|
||||
#endif
|
||||
#ifdef ESP32
|
||||
ssdpDescription += xmlNode(F("modelName"), F("ESP32"));
|
||||
#endif
|
||||
ssdpDescription += xmlNode(F("modelNumber"), getChipId());
|
||||
ssdpDescription += xmlNode(F("modelURL"), F("https://github.com/IoTManagerProject/IoTManager/wiki"));
|
||||
ssdpDescription += xmlNode(F("manufacturer"), F("Borisenko Dmitry"));
|
||||
ssdpDescription += xmlNode(F("manufacturerURL"), F("https://github.com/IoTManagerProject/IoTManager"));
|
||||
ssdpDescription += xmlNode(F("UDN"), "uuid:38323636-4558-4dda-9188-cda0e6" + decToHex(ESP_getChipId(), 6));
|
||||
ssdpDescription = xmlNode("device", ssdpDescription);
|
||||
ssdpHeder += ssdpDescription;
|
||||
ssdpSend += ssdpHeder;
|
||||
ssdpSend += "</root>";
|
||||
Serial.println("->!!!SSDP Get request received");
|
||||
request->send(200, "text/xml", ssdpSend);
|
||||
});
|
||||
//Если версия 2.0.0 закаментируйте следующую строчку
|
||||
SSDP.setDeviceType(F("upnp:rootdevice"));
|
||||
SSDP.setSchemaURL(F("description.xml"));
|
||||
SSDP.begin();
|
||||
}
|
||||
|
||||
String xmlNode(String tags, String data) {
|
||||
String temp = "<" + tags + ">" + data + "</" + tags + ">";
|
||||
return temp;
|
||||
}
|
||||
|
||||
String decToHex(uint32_t decValue, byte desiredStringLength) {
|
||||
String hexString = String(decValue, HEX);
|
||||
while (hexString.length() < desiredStringLength) hexString = "0" + hexString;
|
||||
return hexString;
|
||||
}
|
||||
#endif
|
||||
405
src/Sensors.cpp
405
src/Sensors.cpp
@@ -1,405 +0,0 @@
|
||||
//#include "Cmd.h"
|
||||
//#include "Global.h"
|
||||
|
||||
//GMedian<10, int> medianFilter;
|
||||
//
|
||||
//Adafruit_BMP280 bmp;
|
||||
//Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor();
|
||||
//Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor();
|
||||
//
|
||||
//Adafruit_BME280 bme;
|
||||
//Adafruit_Sensor *bme_temp = bme.getTemperatureSensor();
|
||||
//Adafruit_Sensor *bme_pressure = bme.getPressureSensor();
|
||||
//Adafruit_Sensor *bme_humidity = bme.getHumiditySensor();
|
||||
|
||||
///const String perceptionStr(byte value);
|
||||
///const String comfortStr(ComfortState value);
|
||||
|
||||
//void bmp280T_reading();
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
////=========================================================================================================================================
|
||||
////=========================================Модуль сенсоров DHT=============================================================================
|
||||
//#ifdef DHT_ENABLED
|
||||
////dhtT t 2 dht11 Температура#DHT,#t°C Датчики any-data 1
|
||||
//void dhtT() {
|
||||
// String value_name = sCmd.next();
|
||||
// String pin = sCmd.next();
|
||||
// String sensor_type = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //dhtT_value_name = value_name;
|
||||
// if (sensor_type == "dht11") {
|
||||
// dht.setup(pin.toInt(), DHTesp::DHT11);
|
||||
// }
|
||||
// if (sensor_type == "dht22") {
|
||||
// dht.setup(pin.toInt(), DHTesp::DHT22);
|
||||
// }
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// //sensors_reading_map[4] = 1;
|
||||
//}
|
||||
//
|
||||
//void dhtT_reading() {
|
||||
// float value = 0;
|
||||
// static int counter;
|
||||
// if (dht.getStatus() != 0 && counter < 5) {
|
||||
// // publishStatus(dhtT_value_name, String(dht.getStatusString()));
|
||||
// counter++;
|
||||
// } else {
|
||||
// counter = 0;
|
||||
// value = dht.getTemperature();
|
||||
// if (String(value) != "nan") {
|
||||
// //eventGen2(dhtT_value_name, "");
|
||||
// //jsonWriteStr(configLiveJson, dhtT_value_name, String(value));
|
||||
// // publishStatus(dhtT_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + dhtT_value_name + "' data: " + String(value));
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
////dhtH h 2 dht11 Влажность#DHT,#t°C Датчики any-data 1
|
||||
//void dhtH() {
|
||||
// String value_name = sCmd.next();
|
||||
// String pin = sCmd.next();
|
||||
// String sensor_type = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //dhtH_value_name = value_name;
|
||||
// if (sensor_type == "dht11") {
|
||||
// dht.setup(pin.toInt(), DHTesp::DHT11);
|
||||
// }
|
||||
// if (sensor_type == "dht22") {
|
||||
// dht.setup(pin.toInt(), DHTesp::DHT22);
|
||||
// }
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// //sensors_reading_map[5] = 1;
|
||||
//}
|
||||
//
|
||||
//void dhtH_reading() {
|
||||
// float value = 0;
|
||||
// static int counter;
|
||||
// if (dht.getStatus() != 0 && counter < 5) {
|
||||
// // publishStatus(dhtH_value_name, String(dht.getStatusString()));
|
||||
// counter++;
|
||||
// } else {
|
||||
// counter = 0;
|
||||
// value = dht.getHumidity();
|
||||
// if (String(value) != "nan") {
|
||||
// //eventGen2(dhtH_value_name, "");
|
||||
// //jsonWriteStr(configLiveJson, dhtH_value_name, String(value));
|
||||
// // publishStatus(dhtH_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + dhtH_value_name + "' data: " + String(value));
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
////dhtPerception Восприятие: Датчики 4
|
||||
//void dhtP() {
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// createWidgetByType(widget_name, page_name, page_number, "any-data", "dhtPerception");
|
||||
// //sensors_reading_map[6] = 1;
|
||||
//}
|
||||
//
|
||||
//void dhtP_reading() {
|
||||
// byte value;
|
||||
// if (dht.getStatus() != 0) {
|
||||
// publishStatus("dhtPerception", String(dht.getStatusString()));
|
||||
// } else {
|
||||
// //value = dht.computePerception(jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false);
|
||||
// String final_line = perceptionStr(value);
|
||||
// jsonWriteStr(configLiveJson, "dhtPerception", final_line);
|
||||
// eventGen2("dhtPerception", "");
|
||||
// publishStatus("dhtPerception", final_line);
|
||||
// if (mqtt.connected()) {
|
||||
// SerialPrint("I", "Sensor", "'dhtPerception' data: " + final_line);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
//
|
||||
////dhtComfort Степень#комфорта: Датчики 3
|
||||
//void dhtC() {
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// createWidgetByType(widget_name, page_name, page_number, "anydata", "dhtComfort");
|
||||
// //sensors_reading_map[7] = 1;
|
||||
//}
|
||||
//
|
||||
//void dhtC_reading() {
|
||||
// ComfortState cf;
|
||||
// if (dht.getStatus() != 0) {
|
||||
// publishStatus("dhtComfort", String(dht.getStatusString()));
|
||||
// } else {
|
||||
// //dht.getComfortRatio(cf, jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false);
|
||||
// String final_line = comfortStr(cf);
|
||||
// jsonWriteStr(configLiveJson, "dhtComfort", final_line);
|
||||
// eventGen2("dhtComfort", "");
|
||||
// publishStatus("dhtComfort", final_line);
|
||||
// SerialPrint("I", "Sensor", "'dhtComfort' send date " + final_line);
|
||||
// }
|
||||
//}
|
||||
//
|
||||
//const String perceptionStr(byte value) {
|
||||
// String res;
|
||||
// switch (value) {
|
||||
// case 0:
|
||||
// res = F("Сухой воздух");
|
||||
// break;
|
||||
// case 1:
|
||||
// res = F("Комфортно");
|
||||
// break;
|
||||
// case 2:
|
||||
// res = F("Уютно");
|
||||
// break;
|
||||
// case 3:
|
||||
// res = F("Хорошо");
|
||||
// break;
|
||||
// case 4:
|
||||
// res = F("Неудобно");
|
||||
// break;
|
||||
// case 5:
|
||||
// res = F("Довольно неудобно");
|
||||
// break;
|
||||
// case 6:
|
||||
// res = F("Очень неудобно");
|
||||
// break;
|
||||
// case 7:
|
||||
// res = F("Невыносимо");
|
||||
// default:
|
||||
// res = F("Unknown");
|
||||
// break;
|
||||
// }
|
||||
// return res;
|
||||
//}
|
||||
//
|
||||
//const String comfortStr(ComfortState value) {
|
||||
// String res;
|
||||
// switch (value) {
|
||||
// case Comfort_OK:
|
||||
// res = F("Отлично");
|
||||
// break;
|
||||
// case Comfort_TooHot:
|
||||
// res = F("Очень жарко");
|
||||
// break;
|
||||
// case Comfort_TooCold:
|
||||
// res = F("Очень холодно");
|
||||
// break;
|
||||
// case Comfort_TooDry:
|
||||
// res = F("Очень сухо");
|
||||
// break;
|
||||
// case Comfort_TooHumid:
|
||||
// res = F("Очень влажно");
|
||||
// break;
|
||||
// case Comfort_HotAndHumid:
|
||||
// res = F("Жарко и влажно");
|
||||
// break;
|
||||
// case Comfort_HotAndDry:
|
||||
// res = F("Жарко и сухо");
|
||||
// break;
|
||||
// case Comfort_ColdAndHumid:
|
||||
// res = F("Холодно и влажно");
|
||||
// break;
|
||||
// case Comfort_ColdAndDry:
|
||||
// res = F("Холодно и сухо");
|
||||
// break;
|
||||
// default:
|
||||
// res = F("Неизвестно");
|
||||
// break;
|
||||
// };
|
||||
// return res;
|
||||
//}
|
||||
//
|
||||
////dhtDewpoint Точка#росы: Датчики 5
|
||||
//void dhtD() {
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// createWidgetByType(widget_name, page_name, page_number, "anydata", "dhtDewpoint");
|
||||
// //sensors_reading_map[8] = 1;
|
||||
//}
|
||||
//
|
||||
//void dhtD_reading() {
|
||||
// float value;
|
||||
// if (dht.getStatus() != 0) {
|
||||
// publishStatus("dhtDewpoint", String(dht.getStatusString()));
|
||||
// } else {
|
||||
// //value = dht.computeDewPoint(jsonReadStr(configLiveJson, dhtT_value_name).toFloat(), jsonReadStr(configLiveJson, dhtH_value_name).toFloat(), false);
|
||||
// jsonWriteInt(configLiveJson, "dhtDewpoint", value);
|
||||
// eventGen2("dhtDewpoint", "");
|
||||
// publishStatus("dhtDewpoint", String(value));
|
||||
// SerialPrint("I", "Sensor", "'dhtDewpoint' data: " + String(value));
|
||||
// }
|
||||
//}
|
||||
//#endif
|
||||
//=========================================i2c bus esp8266 scl-4 sda-5 ====================================================================
|
||||
//=========================================================================================================================================
|
||||
//=========================================Модуль сенсоров bmp280==========================================================================
|
||||
|
||||
////bmp280T temp1 0x76 Температура#bmp280 Датчики any-data 1
|
||||
//void bmp280T() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bmp280T_value_name = value_name;
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// bmp.begin(hexStringToUint8(address));
|
||||
// bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
|
||||
// Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
|
||||
// Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
|
||||
// Adafruit_BMP280::FILTER_X16, /* Filtering. */
|
||||
// Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
|
||||
// //bmp_temp->printSensorDetails();
|
||||
// //sensors_reading_map[9] = 1;
|
||||
//}
|
||||
//
|
||||
//void bmp280T_reading() {
|
||||
// float value = 0;
|
||||
// sensors_event_t temp_event;
|
||||
// bmp_temp->getEvent(&temp_event);
|
||||
// value = temp_event.temperature;
|
||||
// //jsonWriteStr(configLiveJson, bmp280T_value_name, String(value));
|
||||
// //eventGen2(bmp280T_value_name, "");
|
||||
// // publishStatus(bmp280T_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + bmp280T_value_name + "' data: " + String(value));
|
||||
//}
|
||||
//
|
||||
////bmp280P press1 0x76 Давление#bmp280 Датчики any-data 2
|
||||
//void bmp280P() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bmp280P_value_name = value_name;
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// bmp.begin(hexStringToUint8(address));
|
||||
// bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */
|
||||
// Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */
|
||||
// Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */
|
||||
// Adafruit_BMP280::FILTER_X16, /* Filtering. */
|
||||
// Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */
|
||||
// //bmp_temp->printSensorDetails();
|
||||
// //sensors_reading_map[10] = 1;
|
||||
//}
|
||||
//
|
||||
//void bmp280P_reading() {
|
||||
// float value = 0;
|
||||
// sensors_event_t pressure_event;
|
||||
// bmp_pressure->getEvent(&pressure_event);
|
||||
// value = pressure_event.pressure;
|
||||
// value = value / 1.333224;
|
||||
// //jsonWriteStr(configLiveJson, bmp280P_value_name, String(value));
|
||||
// //eventGen2(bmp280P_value_name, "");
|
||||
// // publishStatus(bmp280P_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + bmp280P_value_name + "' data: " + String(value));
|
||||
//}
|
||||
//
|
||||
////=========================================================================================================================================
|
||||
////=============================================Модуль сенсоров bme280======================================================================
|
||||
////bme280T temp1 0x76 Температура#bmp280 Датчики any-data 1
|
||||
//void bme280T() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bme280T_value_name = value_name;
|
||||
// //createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// //bme.begin(hexStringToUint8(address));
|
||||
// //sensors_reading_map[11] = 1;
|
||||
//}
|
||||
//
|
||||
//void bme280T_reading() {
|
||||
// float value = 0;
|
||||
// value = bme.readTemperature();
|
||||
// //jsonWriteStr(configLiveJson, bme280T_value_name, String(value));
|
||||
// //eventGen2(bme280T_value_name, "");
|
||||
// // publishStatus(bme280T_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + bme280T_value_name + "' data: " + String(value));
|
||||
//}
|
||||
//
|
||||
////bme280P pres1 0x76 Давление#bmp280 Датчики any-data 1
|
||||
//void bme280P() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bme280P_value_name = value_name;
|
||||
// //createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// //bme.begin(hexStringToUint8(address));
|
||||
// //sensors_reading_map[12] = 1;
|
||||
//}
|
||||
//
|
||||
//void bme280P_reading() {
|
||||
// float value = 0;
|
||||
// value = bme.readPressure();
|
||||
// value = value / 1.333224 / 100;
|
||||
// //jsonWriteStr(configLiveJson, bme280P_value_name, String(value));
|
||||
// //eventGen2(bme280P_value_name, "");
|
||||
// // publishStatus(bme280P_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + bme280P_value_name + "' data: " + String(value));
|
||||
//}
|
||||
//
|
||||
////bme280H hum1 0x76 Влажность#bmp280 Датчики any-data 1
|
||||
//void bme280H() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bme280H_value_name = value_name;
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// bme.begin(hexStringToUint8(address));
|
||||
// //sensors_reading_map[13] = 1;
|
||||
//}
|
||||
//
|
||||
//void bme280H_reading() {
|
||||
// float value = 0;
|
||||
// value = bme.readHumidity();
|
||||
// //jsonWriteStr(configLiveJson, bme280H_value_name, String(value));
|
||||
// //eventGen2(bme280H_value_name, "");
|
||||
// // publishStatus(bme280H_value_name, String(value));
|
||||
// //SerialPrint("I", "Sensor", "'" + bme280H_value_name + "' data: " + String(value));
|
||||
//}
|
||||
//
|
||||
////bme280A altit1 0x76 Высота#bmp280 Датчики any-data 1
|
||||
//void bme280A() {
|
||||
// String value_name = sCmd.next();
|
||||
// String address = sCmd.next();
|
||||
// String widget_name = sCmd.next();
|
||||
// String page_name = sCmd.next();
|
||||
// String type = sCmd.next();
|
||||
// String page_number = sCmd.next();
|
||||
// //bme280A_value_name = value_name;
|
||||
// createWidgetByType(widget_name, page_name, page_number, type, value_name);
|
||||
// bme.begin(hexStringToUint8(address));
|
||||
// //sensors_reading_map[14] = 1;
|
||||
//}
|
||||
//
|
||||
//void bme280A_reading() {
|
||||
// float value = bme.readAltitude(1013.25);
|
||||
// //jsonWriteStr(configLiveJson, bme280A_value_name, String(value, 2));
|
||||
//
|
||||
// //eventGen2(bme280A_value_name, "");
|
||||
//
|
||||
// // publishStatus(bme280A_value_name, String(value));
|
||||
//
|
||||
// //SerialPrint("I", "Sensor", "'" + bme280A_value_name + "' data: " + String(value));
|
||||
//}
|
||||
@@ -1,40 +0,0 @@
|
||||
#include "Servo/Servos.h"
|
||||
|
||||
Servos myServo;
|
||||
|
||||
Servos::Servos(){};
|
||||
|
||||
Servo *Servos::create(uint8_t num, uint8_t pin) {
|
||||
// Ищем среди ранее созданных
|
||||
for (size_t i = 0; i < _items.size(); i++) {
|
||||
auto item = _items.at(i);
|
||||
if (item.num == num) {
|
||||
if (item.pin != pin) {
|
||||
item.obj->attach(pin);
|
||||
item.pin = pin;
|
||||
};
|
||||
return item.obj;
|
||||
}
|
||||
}
|
||||
// Добавляем новый
|
||||
Servo_t newItem{num, pin};
|
||||
newItem.obj = new Servo();
|
||||
newItem.obj->attach(pin);
|
||||
_items.push_back(newItem);
|
||||
return newItem.obj;
|
||||
}
|
||||
|
||||
Servo *Servos::get(uint8_t num) {
|
||||
// Ищем среди ранее созданных
|
||||
for (size_t i = 0; i < _items.size(); i++) {
|
||||
auto item = _items.at(i);
|
||||
if (item.num == num) {
|
||||
return item.obj;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
size_t Servos::count() {
|
||||
return _items.size();
|
||||
}
|
||||
112
src/Telegram.cpp
112
src/Telegram.cpp
@@ -1,112 +0,0 @@
|
||||
#include "Telegram.h"
|
||||
|
||||
|
||||
CTBot* myBot{ nullptr };
|
||||
|
||||
void telegramInit() {
|
||||
if (isTelegramEnabled()) {
|
||||
telegramInitBeen = true;
|
||||
sCmd.addCommand("telegram", sendTelegramMsg);
|
||||
String token = jsonReadStr(configSetupJson, "telegramApi");
|
||||
if (!myBot) {
|
||||
myBot = new CTBot();
|
||||
}
|
||||
myBot->setTelegramToken(token);
|
||||
myBot->enableUTF8Encoding(true);
|
||||
if (myBot->testConnection()) {
|
||||
SerialPrint("I", "Telegram", "Connected");
|
||||
}
|
||||
else {
|
||||
SerialPrint("E", "Telegram", "Not connected");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void handleTelegram() {
|
||||
if (telegramInitBeen) {
|
||||
if (isTelegramEnabled()) {
|
||||
TBMessage msg;
|
||||
static unsigned long prevMillis;
|
||||
unsigned long currentMillis = millis();
|
||||
unsigned long difference = currentMillis - prevMillis;
|
||||
if (difference >= 5000) {
|
||||
prevMillis = millis();
|
||||
if (myBot->getNewMessage(msg)) {
|
||||
SerialPrint("->", "Telegram", "chat ID: " + String(msg.sender.id) + ", msg: " + String(msg.text));
|
||||
jsonWriteInt(configSetupJson, "chatId", msg.sender.id);
|
||||
saveConfig();
|
||||
telegramMsgParse(String(msg.text));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void telegramMsgParse(String msg) {
|
||||
if (msg.indexOf("set") != -1) {
|
||||
msg = deleteBeforeDelimiter(msg, "_");
|
||||
msg.replace("_", " ");
|
||||
orderBuf += String(msg) + ",";
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "order done");
|
||||
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg));
|
||||
}
|
||||
else if (msg.indexOf("get") != -1) {
|
||||
msg = deleteBeforeDelimiter(msg, "_");
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), jsonReadStr(configLiveJson, msg));
|
||||
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg));
|
||||
}
|
||||
else if (msg.indexOf("all") != -1) {
|
||||
String list = returnListOfParams();
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), list);
|
||||
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + "\n" + list);
|
||||
}
|
||||
else {
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "Wrong order, use /all to get all values, /get_id to get value, or /set_id_value to set value");
|
||||
}
|
||||
}
|
||||
|
||||
void sendTelegramMsg() {
|
||||
String msg = sCmd.next();
|
||||
String type = sCmd.next();
|
||||
msg.replace("#", " ");
|
||||
if (type == "1") {
|
||||
static String prevMsg;
|
||||
if (prevMsg != msg) {
|
||||
prevMsg = msg;
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
|
||||
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
|
||||
}
|
||||
} else if (type == "2") {
|
||||
myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg);
|
||||
SerialPrint("<-", "Telegram", "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg);
|
||||
}
|
||||
}
|
||||
|
||||
bool isTelegramEnabled() {
|
||||
return jsonReadBool(configSetupJson, "telegonof");
|
||||
}
|
||||
|
||||
|
||||
String returnListOfParams() {
|
||||
String cmdStr = readFile(DEVICE_CONFIG_FILE, 4096);
|
||||
cmdStr += "\r\n";
|
||||
cmdStr.replace("\r\n", "\n");
|
||||
cmdStr.replace("\r", "\n");
|
||||
int count = 0;
|
||||
String out;
|
||||
while (cmdStr.length()) {
|
||||
String buf = selectToMarker(cmdStr, "\n");
|
||||
count++;
|
||||
if (count > 1) {
|
||||
String id = selectFromMarkerToMarker(buf, ";", 2);
|
||||
String value = jsonReadStr(configLiveJson, id);
|
||||
String page = selectFromMarkerToMarker(buf, ";", 4);
|
||||
page.replace("#", " ");
|
||||
String name = selectFromMarkerToMarker(buf, ";", 5);
|
||||
name.replace("#", " ");
|
||||
out += page + " " + " " + name + " " + value + "\n";
|
||||
}
|
||||
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
#include "Global.h"
|
||||
|
||||
//================================================================================================================
|
||||
//=========================================Таймеры=================================================================
|
||||
void Timer_countdown_init() {
|
||||
ts.add(
|
||||
TIMER_COUNTDOWN, 1000, [&](void*) {
|
||||
String old_line = jsonReadStr(configOptionJson, "timers");
|
||||
if (old_line != "") {
|
||||
//Serial.println(old_line);
|
||||
int i = 0;
|
||||
do {
|
||||
String timer = selectFromMarkerToMarker(old_line, ",", i);
|
||||
//Serial.print("timer no " + String(i) + ": ");
|
||||
//Serial.println(timer);
|
||||
if (timer == "not found" || timer == "") return;
|
||||
int number = selectToMarker(timer, ":").toInt();
|
||||
int time = readTimer(number);
|
||||
if (time == 0) {
|
||||
delTimer(String(number));
|
||||
jsonWriteStr(configLiveJson, "timer" + String(number), "0");
|
||||
eventGen2("timer", String(number));
|
||||
} else {
|
||||
time--;
|
||||
addTimer(String(number), String(time));
|
||||
}
|
||||
i++;
|
||||
} while (i <= 9);
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
|
||||
void timerStart_() {
|
||||
String number = sCmd.next();
|
||||
String period_of_time = sCmd.next();
|
||||
String type = sCmd.next();
|
||||
if (period_of_time.indexOf("digit") != -1) {
|
||||
//period_of_time = add_set(period_of_time);
|
||||
period_of_time = jsonReadStr(configLiveJson, period_of_time);
|
||||
}
|
||||
if (type == "sec") period_of_time = period_of_time;
|
||||
if (type == "min") period_of_time = String(period_of_time.toInt() * 60);
|
||||
if (type == "hours") period_of_time = String(period_of_time.toInt() * 60 * 60);
|
||||
addTimer(number, period_of_time);
|
||||
jsonWriteStr(configLiveJson, "timer" + number, "1");
|
||||
}
|
||||
void addTimer(String number, String time) {
|
||||
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
|
||||
String new_timer = number + ":" + time;
|
||||
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо заменить
|
||||
if (psn1 != -1) { //если он есть
|
||||
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
|
||||
String timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо заменить
|
||||
///tmp.replace(timer, new_timer); //заменяем таймер на новый (во всей стороке)
|
||||
tmp.replace(timer + ",", "");
|
||||
tmp += new_timer + ",";
|
||||
} else { //если его нет
|
||||
tmp += new_timer + ",";
|
||||
}
|
||||
jsonWriteStr(configOptionJson, "timers", tmp);
|
||||
//Serial.println("ura");
|
||||
}
|
||||
|
||||
void timerStop_() {
|
||||
String number = sCmd.next();
|
||||
delTimer(number);
|
||||
}
|
||||
|
||||
void delTimer(String number) {
|
||||
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
|
||||
int psn1 = tmp.indexOf(number + ":"); //0 ищем позицию таймера который надо удалить
|
||||
if (psn1 != -1) { //если он есть
|
||||
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
|
||||
String timer = tmp.substring(psn1, psn2) + ","; //1:60, выделяем таймер который надо удалить
|
||||
tmp.replace(timer, ""); //удаляем таймер
|
||||
jsonWriteStr(configOptionJson, "timers", tmp);
|
||||
}
|
||||
}
|
||||
|
||||
int readTimer(int number) {
|
||||
String tmp = jsonReadStr(configOptionJson, "timers"); //1:60,2:120,
|
||||
int psn1 = tmp.indexOf(String(number) + ":"); //0 ищем позицию таймера который надо прочитать
|
||||
String timer;
|
||||
if (psn1 != -1) { //если он есть
|
||||
int psn2 = tmp.indexOf(",", psn1); //4 от этой позиции находим позицию запятой
|
||||
timer = tmp.substring(psn1, psn2); //1:60 выделяем таймер который надо прочитать
|
||||
timer = deleteBeforeDelimiter(timer, ":");
|
||||
}
|
||||
return timer.toInt();
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
#include "Upgrade.h"
|
||||
|
||||
#include "Class/NotAsync.h"
|
||||
#ifdef ESP8266
|
||||
#include "ESP8266.h"
|
||||
#else
|
||||
#include <HTTPUpdate.h>
|
||||
#endif
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
void upgradeInit() {
|
||||
myNotAsyncActions->add(
|
||||
do_UPGRADE, [&](void*) {
|
||||
upgrade_firmware(3);
|
||||
},
|
||||
nullptr);
|
||||
|
||||
myNotAsyncActions->add(
|
||||
do_GETLASTVERSION, [&](void*) {
|
||||
getLastVersion();
|
||||
},
|
||||
nullptr);
|
||||
|
||||
if (isNetworkActive()) {
|
||||
getLastVersion();
|
||||
if (lastVersion > 0) {
|
||||
SerialPrint("I", "Update", "available version: " + String(lastVersion));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void getLastVersion() {
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
#ifdef ESP8266
|
||||
String tmp = getURL( serverIP + F("/projects/iotmanager/esp8266/esp8266ver/esp8266ver.txt"));
|
||||
#else
|
||||
String tmp = getURL( serverIP + F("/projects/iotmanager/esp32/esp32ver/esp32ver.txt"));
|
||||
#endif
|
||||
if (tmp == "error") {
|
||||
lastVersion = -1;
|
||||
} else {
|
||||
lastVersion = tmp.toInt();
|
||||
}
|
||||
} else {
|
||||
lastVersion = -2;
|
||||
}
|
||||
jsonWriteInt(configSetupJson, "last_version", lastVersion);
|
||||
}
|
||||
|
||||
void upgrade_firmware(int type) {
|
||||
String scenario_ForUpdate;
|
||||
String devconfig_ForUpdate;
|
||||
String configSetup_ForUpdate;
|
||||
|
||||
scenario_ForUpdate = readFile(String(DEVICE_SCENARIO_FILE), 4000);
|
||||
devconfig_ForUpdate = readFile(String(DEVICE_CONFIG_FILE), 4000);
|
||||
configSetup_ForUpdate = configSetupJson;
|
||||
|
||||
if (type == 1) { //only build
|
||||
if (upgradeBuild()) restartEsp();
|
||||
}
|
||||
|
||||
else if (type == 2) { //only spiffs
|
||||
if (upgradeFS()) {
|
||||
writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate);
|
||||
writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate);
|
||||
writeFile("config.json", configSetup_ForUpdate);
|
||||
restartEsp();
|
||||
}
|
||||
}
|
||||
|
||||
else if (type == 3) { //spiffs and build
|
||||
if (upgradeFS()) {
|
||||
writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate);
|
||||
writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate);
|
||||
writeFile("config.json", configSetup_ForUpdate);
|
||||
saveConfig();
|
||||
if (upgradeBuild()) {
|
||||
restartEsp();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool upgradeFS() {
|
||||
WiFiClient wifiClient;
|
||||
bool ret = false;
|
||||
Serial.println("Start upgrade LittleFS, please wait...");
|
||||
#ifdef ESP8266
|
||||
ESPhttpUpdate.rebootOnUpdate(false);
|
||||
t_httpUpdate_return retFS = ESPhttpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp8266/littlefs/littlefs.bin"));
|
||||
#else
|
||||
httpUpdate.rebootOnUpdate(false);
|
||||
HTTPUpdateResult retFS = httpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp32/littlefs/spiffs.bin"));
|
||||
#endif
|
||||
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...");
|
||||
|
||||
#ifdef ESP8266
|
||||
ESPhttpUpdate.rebootOnUpdate(false);
|
||||
t_httpUpdate_return retBuild = ESPhttpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp8266/firmware/firmware.bin"));
|
||||
#else
|
||||
httpUpdate.rebootOnUpdate(false);
|
||||
HTTPUpdateResult retBuild = httpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp32/firmware/firmware.bin"));
|
||||
#endif
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
#include "Utils/FileUtils.h"
|
||||
#include "Utils/SerialPrint.h"
|
||||
#include "Utils/StringUtils.h"
|
||||
|
||||
|
||||
|
||||
const String filepath(const String& filename) {
|
||||
return filename.startsWith("/") ? filename : "/" + filename;
|
||||
}
|
||||
|
||||
bool fileSystemInit() {
|
||||
if (!LittleFS.begin()) {
|
||||
SerialPrint("[E]","Files","init");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void removeFile(const String& filename) {
|
||||
String path = filepath(filename);
|
||||
if (LittleFS.exists(path)) {
|
||||
if (!LittleFS.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 = LittleFS.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 = LittleFS.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 = LittleFS.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 = LittleFS.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 (!LittleFS.exists(srcPath)) {
|
||||
SerialPrint("[E]","Files","not exist: " + srcPath);
|
||||
return false;
|
||||
}
|
||||
if (LittleFS.exists(dstPath)) {
|
||||
if (!overwrite) {
|
||||
SerialPrint("[E]","Files","already exist: " + dstPath);
|
||||
return false;
|
||||
}
|
||||
LittleFS.remove(dstPath);
|
||||
}
|
||||
auto srcFile = LittleFS.open(srcPath, "r");
|
||||
auto dstFile = LittleFS.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 = LittleFS.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 = LittleFS.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;
|
||||
}
|
||||
|
||||
const String getFileSize(const String filename) {
|
||||
String filepath(filename);
|
||||
auto file = LittleFS.open(filepath, "r");
|
||||
if (!file) {
|
||||
return "failed";
|
||||
}
|
||||
size_t size = file.size();
|
||||
file.close();
|
||||
return String(size);
|
||||
}
|
||||
|
||||
const String getFSSizeInfo() {
|
||||
String res;
|
||||
#ifdef ESP8266
|
||||
FSInfo info;
|
||||
if (LittleFS.info(info)) {
|
||||
res = prettyBytes(info.usedBytes) + " of " + prettyBytes(info.totalBytes);
|
||||
} else {
|
||||
res = "error";
|
||||
}
|
||||
#else
|
||||
res = prettyBytes(LittleFS.usedBytes()) + " of " + prettyBytes(LittleFS.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);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
#include "Utils/SerialPrint.h"
|
||||
|
||||
#include "Global.h"
|
||||
|
||||
void SerialPrint(String errorLevel, String module, String msg) {
|
||||
//if (module == "Stat") {
|
||||
Serial.println(prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg);
|
||||
//}
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
#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 itemsCount(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;
|
||||
}
|
||||
|
||||
boolean isDigitStr(const String& str) {
|
||||
for (size_t i = 0; i < str.length(); i++) {
|
||||
if (!isDigit(str.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return str.length();
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,250 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
*/
|
||||
@@ -1,213 +0,0 @@
|
||||
#include "Utils/TimeUtils.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);
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#include "Utils/WebUtils.h"
|
||||
#include "ESPAsyncWebServer.h"
|
||||
|
||||
String getURL(const String& urls) {
|
||||
String res = "";
|
||||
HTTPClient http;
|
||||
http.begin(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;
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
#include "Utils/WiFiUtils.h"
|
||||
|
||||
void routerConnect() {
|
||||
setLedStatus(LED_SLOW);
|
||||
WiFi.mode(WIFI_STA);
|
||||
byte tries = 20;
|
||||
|
||||
String _ssid = jsonReadStr(configSetupJson, "routerssid");
|
||||
String _password = jsonReadStr(configSetupJson, "routerpass");
|
||||
//WiFi.persistent(false);
|
||||
|
||||
if (_ssid == "" && _password == "") {
|
||||
WiFi.begin();
|
||||
} else {
|
||||
WiFi.begin(_ssid.c_str(), _password.c_str());
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,309 +0,0 @@
|
||||
#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);
|
||||
}
|
||||
}
|
||||
|
||||
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 city = jsonReadStr(res, "city");
|
||||
//String country = jsonReadStr(res, "country");
|
||||
//String region = jsonReadStr(res, "region");
|
||||
updateDevicePsn(lat, lon, "0");
|
||||
}
|
||||
}
|
||||
|
||||
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 ret;
|
||||
if ((WiFi.status() == WL_CONNECTED)) {
|
||||
float latfl = lat.toFloat();
|
||||
float lonfl = lon.toFloat();
|
||||
randomSeed(micros());
|
||||
float latc = random(1, 9)/100;
|
||||
randomSeed(micros());
|
||||
float lonc = random(1, 9)/100;
|
||||
latfl = latfl + latc;
|
||||
lonfl = lonfl + lonc;
|
||||
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() +
|
||||
"&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();
|
||||
}
|
||||
*/
|
||||
290
src/Web.cpp
290
src/Web.cpp
@@ -1,290 +0,0 @@
|
||||
#include "Web.h"
|
||||
#include "Class/NotAsync.h"
|
||||
#include "Global.h"
|
||||
#include "Init.h"
|
||||
#include "ItemsList.h"
|
||||
#include "items/LoggingClass.h"
|
||||
#include "Telegram.h"
|
||||
|
||||
bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) {
|
||||
if (request->hasArg("preset")) {
|
||||
preset = request->getParam("preset")->value().toInt();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void web_init() {
|
||||
server.on("/set", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
//==============================set.device.json====================================================================================================
|
||||
if (request->hasArg("addItem")) {
|
||||
String name = request->getParam("addItem")->value();
|
||||
addItem(name);
|
||||
request->redirect("/?set.device");
|
||||
}
|
||||
|
||||
if (request->hasArg("addPreset")) {
|
||||
String name = request->getParam("addPreset")->value();
|
||||
addPreset(name);
|
||||
request->redirect("/?set.device");
|
||||
}
|
||||
|
||||
if (request->hasArg("delChoosingItems")) {
|
||||
myNotAsyncActions->make(do_delChoosingItems);
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("delAllItems")) {
|
||||
delAllItems();
|
||||
request->redirect("/?set.device");
|
||||
}
|
||||
|
||||
if (request->hasArg("saveItems")) {
|
||||
myNotAsyncActions->make(do_deviceInit);
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("scen")) {
|
||||
bool value = request->getParam("scen")->value().toInt();
|
||||
jsonWriteBool(configSetupJson, "scen", value);
|
||||
saveConfig();
|
||||
loadScenario();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("sceninit")) {
|
||||
loadScenario();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
#ifdef LOGGING_ENABLED
|
||||
if (request->hasArg("cleanlog")) {
|
||||
clean_log_date();
|
||||
request->send(200);
|
||||
}
|
||||
#endif
|
||||
|
||||
//==============================wifi settings=============================================
|
||||
if (request->hasArg("devname")) {
|
||||
jsonWriteStr(configSetupJson, "name", request->getParam("devname")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("routerssid")) {
|
||||
jsonWriteStr(configSetupJson, "routerssid", request->getParam("routerssid")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("routerpass")) {
|
||||
jsonWriteStr(configSetupJson, "routerpass", request->getParam("routerpass")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("apssid")) {
|
||||
jsonWriteStr(configSetupJson, "apssid", request->getParam("apssid")->value());
|
||||
saveConfig();
|
||||
request->send(200, "text/text", "OK");
|
||||
}
|
||||
|
||||
if (request->hasArg("appass")) {
|
||||
jsonWriteStr(configSetupJson, "appass", request->getParam("appass")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("weblogin")) {
|
||||
jsonWriteStr(configSetupJson, "weblogin", request->getParam("weblogin")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("webpass")) {
|
||||
jsonWriteStr(configSetupJson, "webpass", request->getParam("webpass")->value());
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("timezone")) {
|
||||
String timezoneStr = request->getParam("timezone")->value();
|
||||
jsonWriteStr(configSetupJson, "timezone", timezoneStr);
|
||||
saveConfig();
|
||||
timeNow->setTimezone(timezoneStr.toInt());
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("ntp")) {
|
||||
String ntpStr = request->getParam("ntp")->value();
|
||||
jsonWriteStr(configSetupJson, "ntp", ntpStr);
|
||||
saveConfig();
|
||||
timeNow->setNtpPool(ntpStr);
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("blink")) {
|
||||
bool value = request->getParam("blink")->value().toInt();
|
||||
jsonWriteBool(configSetupJson, "blink", value);
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("device")) {
|
||||
if (request->getParam("device")->value() == "ok") {
|
||||
ESP.restart();
|
||||
}
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("test")) {
|
||||
if (request->getParam("test")->value() == "ok") {
|
||||
Serial.println("test pass");
|
||||
}
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
//==============================mqtt settings=============================================
|
||||
|
||||
if (request->hasArg("mqttServer")) {
|
||||
jsonWriteStr(configSetupJson, "mqttServer", request->getParam("mqttServer")->value());
|
||||
saveConfig();
|
||||
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
|
||||
request->send(200);
|
||||
}
|
||||
if (request->hasArg("mqttPort")) {
|
||||
int port = (request->getParam("mqttPort")->value()).toInt();
|
||||
jsonWriteInt(configSetupJson, "mqttPort", port);
|
||||
saveConfig();
|
||||
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
|
||||
request->send(200);
|
||||
}
|
||||
if (request->hasArg("mqttPrefix")) {
|
||||
jsonWriteStr(configSetupJson, "mqttPrefix", request->getParam("mqttPrefix")->value());
|
||||
saveConfig();
|
||||
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
|
||||
request->send(200);
|
||||
}
|
||||
if (request->hasArg("mqttUser")) {
|
||||
jsonWriteStr(configSetupJson, "mqttUser", request->getParam("mqttUser")->value());
|
||||
saveConfig();
|
||||
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
|
||||
request->send(200);
|
||||
}
|
||||
if (request->hasArg("mqttPass")) {
|
||||
jsonWriteStr(configSetupJson, "mqttPass", request->getParam("mqttPass")->value());
|
||||
saveConfig();
|
||||
myNotAsyncActions->make(do_MQTTPARAMSCHANGED);
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("mqttsend")) {
|
||||
myNotAsyncActions->make(do_MQTTUDP);
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
if (request->hasArg("mqttcheck")) {
|
||||
String buf = "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + getStateStr();
|
||||
|
||||
String payload = "{}";
|
||||
jsonWriteStr(payload, "title", buf);
|
||||
jsonWriteStr(payload, "class", "pop-up");
|
||||
|
||||
request->send(200, "text/html", payload);
|
||||
}
|
||||
|
||||
//==============================push settings=============================================
|
||||
if (request->hasArg("telegramApi")) {
|
||||
jsonWriteStr(configSetupJson, "telegramApi", request->getParam("telegramApi")->value());
|
||||
//telegramInit();
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
if (request->hasArg("telegonof")) {
|
||||
bool value = request->getParam("telegonof")->value().toInt();
|
||||
jsonWriteBool(configSetupJson, "telegonof", value);
|
||||
//telegramInit();
|
||||
saveConfig();
|
||||
request->send(200);
|
||||
}
|
||||
|
||||
//==============================utilities settings=============================================
|
||||
if (request->hasArg("i2c")) {
|
||||
myNotAsyncActions->make(do_BUSSCAN);
|
||||
request->redirect("/?set.utilities");
|
||||
}
|
||||
|
||||
//==============================developer settings=============================================
|
||||
if (request->hasArg("serverip")) {
|
||||
jsonWriteStr(configSetupJson, "serverip", request->getParam("serverip")->value());
|
||||
saveConfig();
|
||||
serverIP = jsonReadStr(configSetupJson, "serverip");
|
||||
request->send(200);
|
||||
}
|
||||
});
|
||||
|
||||
//==============================list of items=====================================================
|
||||
//server.on("/del", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
// if (request->hasArg("file")) {
|
||||
// itemsFile = request->getParam("file")->value();
|
||||
// }
|
||||
// if (request->hasArg("line")) {
|
||||
// itemsLine = request->getParam("line")->value();
|
||||
// }
|
||||
// delElementFlag = true;
|
||||
// Device_init();
|
||||
// request->redirect("/?setn.device");
|
||||
//});
|
||||
|
||||
/*
|
||||
* Check
|
||||
*/
|
||||
server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
myNotAsyncActions->make(do_GETLASTVERSION);
|
||||
SerialPrint("I", "Update", "firmware version: " + String(lastVersion));
|
||||
|
||||
String msg = "";
|
||||
if (lastVersion == FIRMWARE_VERSION) {
|
||||
msg = F("Актуальная версия прошивки уже установлена.");
|
||||
}
|
||||
else if (lastVersion > FIRMWARE_VERSION) {
|
||||
msg = F("Новая версия прошивки<a href=\"#\" class=\"btn btn-block btn-danger\" onclick=\"send_request(this, '/upgrade');setTimeout(function(){ location.href='/?set.device'; }, 90000);html('my-block','<span class=loader></span>Идет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить</a>");
|
||||
}
|
||||
else if (lastVersion == -1) {
|
||||
msg = F("Cервер не найден. Попробуйте повторить позже...");
|
||||
}
|
||||
else if (lastVersion == -2) {
|
||||
msg = F("Устройство не подключено к роутеру!");
|
||||
}
|
||||
else if (lastVersion < FIRMWARE_VERSION) {
|
||||
msg = F("Ошибка версии. Попробуйте повторить позже...");
|
||||
}
|
||||
|
||||
// else if (lastVersion == "") {
|
||||
//msg = F("Нажмите на кнопку \"обновить прошивку\" повторно...");
|
||||
//} else if (lastVersion == "less") {
|
||||
//msg = F("Обновление \"по воздуху\" не поддерживается!");
|
||||
//} else if (lastVersion == "notsupported") {
|
||||
// msg = F("Обновление возможно только через usb!");
|
||||
//}
|
||||
|
||||
String tmp = "{}";
|
||||
jsonWriteStr(tmp, "title", "<button class=\"close\" onclick=\"toggle('my-block')\">×</button>" + msg);
|
||||
jsonWriteStr(tmp, "class", "pop-up");
|
||||
request->send(200, "text/html", tmp);
|
||||
});
|
||||
|
||||
/*
|
||||
* Upgrade
|
||||
*/
|
||||
server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) {
|
||||
myNotAsyncActions->make(do_UPGRADE);
|
||||
request->send(200, "text/html");
|
||||
});
|
||||
}
|
||||
|
||||
void setConfigParam(const char* param, const String& value) {
|
||||
SerialPrint("I", "Web", "set " + String(param) + ": " + value);
|
||||
jsonWriteStr(configSetupJson, param, value);
|
||||
saveConfig();
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
#include "HttpServer.h"
|
||||
#include "BufferExecute.h"
|
||||
#include "Utils/FileUtils.h"
|
||||
#include "Utils/WebUtils.h"
|
||||
#include "FSEditor.h"
|
||||
|
||||
namespace HttpServer {
|
||||
|
||||
|
||||
/* Forward declaration */
|
||||
void initOta();
|
||||
void initMDNS();
|
||||
void initWS();
|
||||
|
||||
void init() {
|
||||
String login = jsonReadStr(configSetupJson, "weblogin");
|
||||
String pass = jsonReadStr(configSetupJson, "webpass");
|
||||
#ifdef ESP32
|
||||
server.addHandler(new FSEditor(LittleFS, login, pass));
|
||||
#else
|
||||
server.addHandler(new FSEditor(login, pass));
|
||||
#endif
|
||||
|
||||
server.serveStatic("/css/", LittleFS, "/css/").setCacheControl("max-age=600");
|
||||
server.serveStatic("/js/", LittleFS, "/js/").setCacheControl("max-age=600");
|
||||
server.serveStatic("/favicon.ico", LittleFS, "/favicon.ico").setCacheControl("max-age=600");
|
||||
server.serveStatic("/icon.jpeg", LittleFS, "/icon.jpeg").setCacheControl("max-age=600");
|
||||
|
||||
server.serveStatic("/", LittleFS, "/").setDefaultFile("index.htm").setAuthentication(login.c_str(), pass.c_str());
|
||||
|
||||
server.onNotFound([](AsyncWebServerRequest *request) {
|
||||
SerialPrint("[E]","WebServer","not found:\n" + getRequestInfo(request));
|
||||
request->send(404);
|
||||
});
|
||||
|
||||
server.onFileUpload([](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) {
|
||||
// TODO
|
||||
if (!index) {
|
||||
SerialPrint("I","WebServer","start upload " + filename);
|
||||
}
|
||||
if (final) {
|
||||
SerialPrint("I","WebServer","finish upload: " + prettyBytes(index + len));
|
||||
}
|
||||
});
|
||||
|
||||
// динамические данные
|
||||
server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(200, "application/json", configLiveJson);
|
||||
});
|
||||
|
||||
// данные не являющиеся событиями
|
||||
server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(200, "application/json", configOptionJson);
|
||||
});
|
||||
|
||||
// для хранения постоянных данных
|
||||
server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(200, "application/json", configSetupJson);
|
||||
});
|
||||
|
||||
server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
String cmdStr = request->getParam("command")->value();
|
||||
SerialPrint("I","WebServer","do: " + cmdStr);
|
||||
loopCmdAdd(cmdStr);
|
||||
request->send(200, "text/html", "OK");
|
||||
});
|
||||
|
||||
server.begin();
|
||||
|
||||
initOta();
|
||||
initMDNS();
|
||||
initWS();
|
||||
}
|
||||
|
||||
void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
|
||||
#ifdef WS_enable
|
||||
if (type == WS_EVT_CONNECT) {
|
||||
Serial.printf("ws[%s][%u] connect\n", server->url(), client->id());
|
||||
client->printf(json.c_str(), client->id());
|
||||
//client->ping();
|
||||
} else if (type == WS_EVT_DISCONNECT) {
|
||||
Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id());
|
||||
} else if (type == WS_EVT_ERROR) {
|
||||
Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data);
|
||||
} else if (type == WS_EVT_PONG) {
|
||||
Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : "");
|
||||
} else if (type == WS_EVT_DATA) {
|
||||
AwsFrameInfo *info = (AwsFrameInfo *)arg;
|
||||
String msg = "";
|
||||
if (info->final && info->index == 0 && info->len == len) {
|
||||
//the whole message is in a single frame and we got all of it's data
|
||||
Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len);
|
||||
|
||||
if (info->opcode == WS_TEXT) {
|
||||
for (size_t i = 0; i < info->len; i++) {
|
||||
msg += (char)data[i];
|
||||
}
|
||||
} else {
|
||||
char buff[3];
|
||||
for (size_t i = 0; i < info->len; i++) {
|
||||
sprintf(buff, "%02x ", (uint8_t)data[i]);
|
||||
msg += buff;
|
||||
}
|
||||
}
|
||||
Serial.printf("%s\n", msg.c_str());
|
||||
|
||||
if (info->opcode == WS_TEXT)
|
||||
client->text("{}");
|
||||
else
|
||||
client->binary("{}");
|
||||
} else {
|
||||
//message is comprised of multiple frames or the frame is split into multiple packets
|
||||
if (info->index == 0) {
|
||||
if (info->num == 0)
|
||||
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
|
||||
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
|
||||
}
|
||||
|
||||
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT) ? "text" : "binary", info->index, info->index + len);
|
||||
|
||||
if (info->opcode == WS_TEXT) {
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
msg += (char)data[i];
|
||||
}
|
||||
} else {
|
||||
char buff[3];
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
sprintf(buff, "%02x ", (uint8_t)data[i]);
|
||||
msg += buff;
|
||||
}
|
||||
}
|
||||
Serial.printf("%s\n", msg.c_str());
|
||||
|
||||
if ((info->index + len) == info->len) {
|
||||
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
|
||||
if (info->final) {
|
||||
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary");
|
||||
if (info->message_opcode == WS_TEXT)
|
||||
client->text("I got your text message");
|
||||
else
|
||||
client->binary("I got your binary message");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
;
|
||||
}
|
||||
|
||||
void initMDNS() {
|
||||
#ifdef MDNS_ENABLED
|
||||
MDNS.addService("http", "tcp", 80);
|
||||
// TODO Add Adduino OTA
|
||||
#endif
|
||||
;
|
||||
}
|
||||
|
||||
void initOta() {
|
||||
#ifdef OTA_UPDATES_ENABLED
|
||||
ArduinoOTA.onStart([]() {
|
||||
events.send("Update Start", "ota");
|
||||
});
|
||||
ArduinoOTA.onEnd([]() {
|
||||
events.send("Update End", "ota");
|
||||
});
|
||||
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
|
||||
char p[32];
|
||||
sprintf(p, "Progress: %u%%\n", (progress / (total / 100)));
|
||||
events.send(p, "ota");
|
||||
});
|
||||
ArduinoOTA.onError([](ota_error_t error) {
|
||||
if (error == OTA_AUTH_ERROR)
|
||||
events.send("Auth Failed", "ota");
|
||||
else if (error == OTA_BEGIN_ERROR)
|
||||
events.send("Begin Failed", "ota");
|
||||
else if (error == OTA_CONNECT_ERROR)
|
||||
events.send("Connect Failed", "ota");
|
||||
else if (error == OTA_RECEIVE_ERROR)
|
||||
events.send("Recieve Failed", "ota");
|
||||
else if (error == OTA_END_ERROR)
|
||||
events.send("End Failed", "ota");
|
||||
});
|
||||
ArduinoOTA.setHostname(hostName);
|
||||
ArduinoOTA.begin();
|
||||
#endif
|
||||
;
|
||||
}
|
||||
|
||||
void initWS() {
|
||||
#ifdef WS_enable
|
||||
ws.onEvent(onWsEvent);
|
||||
server.addHandler(&ws);
|
||||
events.onConnect([](AsyncEventSourceClient *client) {
|
||||
client->send("", NULL, millis(), 1000);
|
||||
});
|
||||
server.addHandler(&events);
|
||||
#endif
|
||||
;
|
||||
}
|
||||
|
||||
} // namespace HttpServer
|
||||
@@ -1,92 +0,0 @@
|
||||
#include "Global.h"
|
||||
|
||||
|
||||
const String getWidgetFile(const String& name);
|
||||
|
||||
bool loadWidget(const String& filename, String& buf) {
|
||||
buf = readFile(getWidgetFile(filename), 2048);
|
||||
bool res = !(buf == "Failed" || buf == "Large");
|
||||
if (!res) {
|
||||
SerialPrint("[E]","Widgets","on load" + filename);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
void createWidget(String descr, String page, String order, String filename, String topic) {
|
||||
String buf = "{}";
|
||||
if (!loadWidget(filename, buf)) {
|
||||
return;
|
||||
}
|
||||
descr.replace("#", " ");
|
||||
page.replace("#", " ");
|
||||
|
||||
jsonWriteStr(buf, "page", page);
|
||||
jsonWriteStr(buf, "order", order);
|
||||
jsonWriteStr(buf, "descr", descr);
|
||||
jsonWriteStr(buf, "topic", prex + "/" + topic);
|
||||
|
||||
#ifdef LAYOUT_IN_RAM
|
||||
all_widgets += widget + "\r\n";
|
||||
#else
|
||||
addFileLn("layout.txt", buf);
|
||||
#endif
|
||||
}
|
||||
|
||||
//TODO Вот эта процедура, и несколько оберток
|
||||
void createWidgetParam(String widget, String page, String pageNumber, String filename, String topic,
|
||||
String name1, String param1, String name2, String param2, String name3, String param3) {
|
||||
String buf = "";
|
||||
if (!loadWidget(filename, buf)) {
|
||||
return;
|
||||
}
|
||||
|
||||
widget.replace("#", " ");
|
||||
page.replace("#", " ");
|
||||
|
||||
jsonWriteStr(buf, "page", page);
|
||||
jsonWriteStr(buf, "order", pageNumber);
|
||||
jsonWriteStr(buf, "descr", widget);
|
||||
jsonWriteStr(buf, "topic", prex + "/" + topic);
|
||||
|
||||
if (name1) jsonWriteStr(buf, name1, param1);
|
||||
if (name2) jsonWriteStr(buf, name2, param2);
|
||||
if (name3) jsonWriteStr(buf, name3, param3);
|
||||
|
||||
#ifdef LAYOUT_IN_RAM
|
||||
all_widgets += widget + "\r\n";
|
||||
#else
|
||||
addFileLn("layout.txt", buf);
|
||||
#endif
|
||||
}
|
||||
|
||||
void createChart(String widget, String page, String pageNumber, String filename, String topic,
|
||||
String maxCount) {
|
||||
String buf = "";
|
||||
if (!loadWidget(filename, buf)) {
|
||||
return;
|
||||
}
|
||||
|
||||
widget.replace("#", " ");
|
||||
page.replace("#", " ");
|
||||
|
||||
jsonWriteStr(buf, "page", page);
|
||||
jsonWriteStr(buf, "order", pageNumber);
|
||||
//jsonWriteStr(widget, "descr", widget_name);
|
||||
jsonWriteStr(buf, "series", widget);
|
||||
jsonWriteStr(buf, "maxCount", maxCount);
|
||||
jsonWriteStr(buf, "topic", prex + "/" + topic);
|
||||
|
||||
#ifdef LAYOUT_IN_RAM
|
||||
all_widgets += widget + "\r\n";
|
||||
#else
|
||||
addFileLn("layout.txt", buf);
|
||||
#endif
|
||||
}
|
||||
|
||||
void createWidgetByType(String widget, String page, String pageNumber, String type, String topic) {
|
||||
createWidget(widget, page, pageNumber, getWidgetFile(type), topic);
|
||||
}
|
||||
|
||||
const String getWidgetFile(const String& name) {
|
||||
return "/widgets/" + name + ".json";
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/ButtonInClass.h"
|
||||
//==========================================Модуль физических кнопок========================================
|
||||
//button-in switch1 toggle Кнопки Свет 1 pin[2] db[20]
|
||||
//==========================================================================================================
|
||||
|
||||
boolean but[NUM_BUTTONS];
|
||||
Bounce *buttons = new Bounce[NUM_BUTTONS];
|
||||
|
||||
ButtonInClass myButtonIn;
|
||||
void buttonIn() {
|
||||
myButtonIn.update();
|
||||
String key = myButtonIn.gkey();
|
||||
String pin = myButtonIn.gpin();
|
||||
sCmd.addCommand(key.c_str(), buttonInSet);
|
||||
myButtonIn.init();
|
||||
myButtonIn.switchStateSetDefault();
|
||||
myButtonIn.clear();
|
||||
}
|
||||
|
||||
void buttonInSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myButtonIn.switchChangeVirtual(key, state);
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
#include "items/ButtonOutClass.h"
|
||||
|
||||
#include "BufferExecute.h"
|
||||
//==========================================Модуль кнопок===================================================
|
||||
//button-out light toggle Кнопки Свет 1 pin[12] inv[1] st[1]
|
||||
//==========================================================================================================
|
||||
ButtonOutClass myButtonOut;
|
||||
void buttonOut() {
|
||||
myButtonOut.update();
|
||||
String key = myButtonOut.gkey();
|
||||
String pin = myButtonOut.gpin();
|
||||
String inv = myButtonOut.ginv();
|
||||
sCmd.addCommand(key.c_str(), buttonOutSet);
|
||||
myButtonOut.init();
|
||||
myButtonOut.pinStateSetDefault();
|
||||
myButtonOut.clear();
|
||||
}
|
||||
|
||||
void buttonOutSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myButtonOut.pinChange(key, state);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
#include "items/ImpulsOutClass.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "BufferExecute.h"
|
||||
#include "Class/LineParsing.h"
|
||||
#include "Global.h"
|
||||
#include "BufferExecute.h"
|
||||
|
||||
ImpulsOutClass::ImpulsOutClass(unsigned int impulsPin) {
|
||||
_impulsPin = impulsPin;
|
||||
pinMode(impulsPin, OUTPUT);
|
||||
}
|
||||
|
||||
ImpulsOutClass::~ImpulsOutClass() {}
|
||||
|
||||
void ImpulsOutClass::execute(unsigned long impulsPeriod, unsigned int impulsCount) {
|
||||
_impulsPeriod = impulsPeriod;
|
||||
_impulsCount = impulsCount * 2;
|
||||
_impulsCountBuf = _impulsCount;
|
||||
}
|
||||
|
||||
void ImpulsOutClass::loop() {
|
||||
currentMillis = millis();
|
||||
unsigned long difference = currentMillis - prevMillis;
|
||||
if (_impulsCountBuf > 0) {
|
||||
if (difference > _impulsPeriod) {
|
||||
_impulsCountBuf--;
|
||||
prevMillis = millis();
|
||||
yield();
|
||||
digitalWrite(_impulsPin, !digitalRead(_impulsPin));
|
||||
yield();
|
||||
}
|
||||
}
|
||||
if (_impulsCountBuf <= 0) {
|
||||
digitalWrite(_impulsPin, LOW);
|
||||
}
|
||||
}
|
||||
|
||||
MyImpulsOutVector* myImpulsOut = nullptr;
|
||||
|
||||
void impuls() {
|
||||
myLineParsing.update();
|
||||
String key = myLineParsing.gkey();
|
||||
String pin = myLineParsing.gpin();
|
||||
myLineParsing.clear();
|
||||
|
||||
impulsEnterCounter++;
|
||||
addKey(key, impulsKeyList, impulsEnterCounter);
|
||||
|
||||
static bool firstTime = true;
|
||||
if (firstTime) myImpulsOut = new MyImpulsOutVector();
|
||||
firstTime = false;
|
||||
myImpulsOut->push_back(ImpulsOutClass(pin.toInt()));
|
||||
|
||||
sCmd.addCommand(key.c_str(), impulsExecute);
|
||||
}
|
||||
|
||||
void impulsExecute() {
|
||||
String key = sCmd.order();
|
||||
String impulsPeriod = sCmd.next();
|
||||
String impulsCount = sCmd.next();
|
||||
|
||||
int number = getKeyNum(key, impulsKeyList);
|
||||
|
||||
if (myImpulsOut != nullptr) {
|
||||
if (number != -1) {
|
||||
myImpulsOut->at(number).execute(impulsPeriod.toInt(), impulsCount.toInt());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/InputClass.h"
|
||||
//==========================================Модуль ввода цифровых значений==================================
|
||||
//input-digit digit1 inputDigit Ввод Введите.цифру 4 st[60]
|
||||
//==========================================================================================================
|
||||
InputClass myInputDigit;
|
||||
void inputDigit() {
|
||||
myInputDigit.update();
|
||||
String key = myInputDigit.gkey();
|
||||
sCmd.addCommand(key.c_str(), inputDigitSet);
|
||||
myInputDigit.inputSetDefaultFloat();
|
||||
myInputDigit.clear();
|
||||
}
|
||||
|
||||
void inputDigitSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myInputDigit.inputSetFloat(key, state);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/InputClass.h"
|
||||
//==========================================Модуль ввода времени============================================
|
||||
//==========================================================================================================
|
||||
InputClass myInputTime;
|
||||
void inputTime() {
|
||||
myInputTime.update();
|
||||
String key = myInputTime.gkey();
|
||||
sCmd.addCommand(key.c_str(), inputTimeSet);
|
||||
myInputTime.inputSetDefaultStr();
|
||||
myInputTime.clear();
|
||||
}
|
||||
|
||||
void inputTimeSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myInputTime.inputSetStr(key, state);
|
||||
}
|
||||
|
||||
void handle_time_init() {
|
||||
ts.add(
|
||||
TIME, 1000, [&](void*) {
|
||||
String timenow = timeNow->getTimeWOsec();
|
||||
static String prevTime;
|
||||
if (prevTime != timenow) {
|
||||
prevTime = timenow;
|
||||
jsonWriteStr(configLiveJson, "timenow", timenow);
|
||||
eventGen2("timenow", timenow);
|
||||
}
|
||||
},
|
||||
nullptr, true);
|
||||
}
|
||||
@@ -1,124 +0,0 @@
|
||||
#include "items/LoggingClass.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "Class/LineParsing.h"
|
||||
#include "Global.h"
|
||||
#include "BufferExecute.h"
|
||||
|
||||
LoggingClass::LoggingClass(unsigned long period, unsigned int maxPoints, String loggingValueKey, String key) {
|
||||
_period = period * 1000;
|
||||
_maxPoints = maxPoints;
|
||||
_loggingValueKey = loggingValueKey;
|
||||
_key = key;
|
||||
}
|
||||
|
||||
LoggingClass::~LoggingClass() {}
|
||||
|
||||
void LoggingClass::loop() {
|
||||
currentMillis = millis();
|
||||
unsigned long difference = currentMillis - prevMillis;
|
||||
if (difference >= _period) {
|
||||
prevMillis = millis();
|
||||
addNewDelOldData("logs/" + _key + ".txt", _maxPoints, jsonReadStr(configLiveJson, _loggingValueKey));
|
||||
}
|
||||
}
|
||||
|
||||
void LoggingClass::addNewDelOldData(const String filename, size_t maxPoints, String payload) {
|
||||
String logData = readFile(filename, 5120);
|
||||
size_t lines_cnt = itemsCount(logData, "\r\n");
|
||||
|
||||
SerialPrint("I", "Logging", "http://" + WiFi.localIP().toString() + "/" + filename + " (" + String(lines_cnt, DEC) + ")");
|
||||
|
||||
if ((lines_cnt > maxPoints + 1) || !lines_cnt) {
|
||||
removeFile(filename);
|
||||
lines_cnt = 0;
|
||||
}
|
||||
|
||||
if (payload != "") {
|
||||
if (lines_cnt > maxPoints) {
|
||||
logData = deleteBeforeDelimiter(logData, "\r\n");
|
||||
if (timeNow->hasTimeSynced()) {
|
||||
logData += timeNow->getTimeUnix() + " " + payload + "\r\n";
|
||||
writeFile(filename, logData);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (timeNow->hasTimeSynced()) {
|
||||
addFileLn(filename, timeNow->getTimeUnix() + " " + payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MyLoggingVector* myLogging = nullptr;
|
||||
|
||||
void logging() {
|
||||
myLineParsing.update();
|
||||
String loggingValueKey = myLineParsing.gval();
|
||||
String key = myLineParsing.gkey();
|
||||
String interv = myLineParsing.gint();
|
||||
String maxcnt = myLineParsing.gcnt();
|
||||
myLineParsing.clear();
|
||||
|
||||
loggingKeyList += key + ",";
|
||||
|
||||
static bool firstTime = true;
|
||||
if (firstTime) myLogging = new MyLoggingVector();
|
||||
firstTime = false;
|
||||
myLogging->push_back(LoggingClass(interv.toInt(), maxcnt.toInt(), loggingValueKey, key));
|
||||
}
|
||||
|
||||
void choose_log_date_and_send() {
|
||||
String all_line = loggingKeyList;
|
||||
while (all_line.length() != 0) {
|
||||
String tmp = selectToMarker(all_line, ",");
|
||||
sendLogData("logs/" + tmp + ".txt", tmp);
|
||||
all_line = deleteBeforeDelimiter(all_line, ",");
|
||||
}
|
||||
}
|
||||
|
||||
void sendLogData(String file, String topic) {
|
||||
String log_date = readFile(file, 5120);
|
||||
if (log_date != "failed") {
|
||||
log_date.replace("\r\n", "\n");
|
||||
log_date.replace("\r", "\n");
|
||||
String buf = "{}";
|
||||
String json_array;
|
||||
String unix_time;
|
||||
String value;
|
||||
while (log_date.length()) {
|
||||
String tmp = selectToMarker(log_date, "\n");
|
||||
log_date = deleteBeforeDelimiter(log_date, "\n");
|
||||
unix_time = selectToMarker(tmp, " ");
|
||||
jsonWriteInt(buf, "x", unix_time.toInt());
|
||||
value = deleteBeforeDelimiter(tmp, " ");
|
||||
jsonWriteFloat(buf, "y1", value.toFloat());
|
||||
if (log_date.length() < 3) {
|
||||
json_array += buf;
|
||||
}
|
||||
else {
|
||||
json_array += buf + ",";
|
||||
}
|
||||
buf = "{}";
|
||||
}
|
||||
unix_time = "";
|
||||
value = "";
|
||||
log_date = "";
|
||||
json_array = "{\"status\":[" + json_array + "]}";
|
||||
//SerialPrint("I", "module", json_array);
|
||||
|
||||
publishChart(topic, json_array);
|
||||
}
|
||||
}
|
||||
|
||||
void clean_log_date() {
|
||||
#ifdef ESP8266
|
||||
auto dir = LittleFS.openDir("logs");
|
||||
while (dir.next()) {
|
||||
String fname = dir.fileName();
|
||||
SerialPrint("I", "System", fname);
|
||||
removeFile("logs/" + fname);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/OutputTextClass.h"
|
||||
//===============================================Модуль вывода текста============================================
|
||||
//output-text;id;anydata;Вывод;Сигнализация;order;st[Обнаружено.движение]
|
||||
//===============================================================================================================
|
||||
OutputTextClass myOutputText;
|
||||
void textOut() {
|
||||
myOutputText.update();
|
||||
String key = myOutputText.gkey();
|
||||
sCmd.addCommand(key.c_str(), textOutSet);
|
||||
myOutputText.OutputModuleStateSetDefault();
|
||||
myOutputText.clear();
|
||||
}
|
||||
|
||||
void textOutSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
myOutputText.OutputModuleChange(key, state);
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/PwmOutClass.h"
|
||||
//==========================================Модуль управления ШИМ===================================================
|
||||
//pwm-out volume range Кнопки Свет 1 pin[12] st[500]
|
||||
//==================================================================================================================
|
||||
PwmOutClass myPwmOut;
|
||||
void pwmOut() {
|
||||
myPwmOut.update();
|
||||
String key = myPwmOut.gkey();
|
||||
String pin = myPwmOut.gpin();
|
||||
String inv = myPwmOut.ginv();
|
||||
sCmd.addCommand(key.c_str(), pwmOutSet);
|
||||
jsonWriteStr(configOptionJson, key + "_pin", pin);
|
||||
myPwmOut.pwmModeSet();
|
||||
myPwmOut.pwmStateSetDefault();
|
||||
myPwmOut.clear();
|
||||
}
|
||||
|
||||
void pwmOutSet() {
|
||||
String key = sCmd.order();
|
||||
String state = sCmd.next();
|
||||
String pin = jsonReadStr(configOptionJson, key + "_pin");
|
||||
myPwmOut.pwmChange(key, pin, state);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/SensorAnalogClass.h"
|
||||
#ifdef ANALOG_ENABLED
|
||||
//==============================================Модуль аналогового сенсора===========================================================================================
|
||||
//===================================================================================================================================================================
|
||||
SensorAnalogClass mySensorAnalog;
|
||||
void analogAdc() {
|
||||
mySensorAnalog.update();
|
||||
String key = mySensorAnalog.gkey();
|
||||
sCmd.addCommand(key.c_str(), analogReading);
|
||||
sensorReadingMap10sec += key + ",";
|
||||
mySensorAnalog.SensorAnalogInit();
|
||||
mySensorAnalog.clear();
|
||||
}
|
||||
|
||||
void analogReading() {
|
||||
String key = sCmd.order();
|
||||
String pin = jsonReadStr(configOptionJson, key + "_pin");
|
||||
mySensorAnalog.SensorAnalogRead(key, pin);
|
||||
}
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
#include "items/SensorBme280Class.h"
|
||||
|
||||
#include "BufferExecute.h"
|
||||
//#ifdef SensorBme280Enabled
|
||||
//=========================================Модуль ультрозвукового дальномера==================================================================
|
||||
//bme280-temp;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//bme280-hum;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//bme280-press;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//=========================================================================================================================================
|
||||
SensorBme280Class mySensorBme280;
|
||||
|
||||
void bme280Temp() {
|
||||
mySensorBme280.update();
|
||||
String key = mySensorBme280.gkey();
|
||||
sCmd.addCommand(key.c_str(), bme280ReadingTemp);
|
||||
mySensorBme280.SensorBme280Init();
|
||||
mySensorBme280.clear();
|
||||
}
|
||||
void bme280ReadingTemp() {
|
||||
String key = sCmd.order();
|
||||
mySensorBme280.SensorBme280ReadTmp(key);
|
||||
}
|
||||
|
||||
void bme280Hum() {
|
||||
mySensorBme280.update();
|
||||
String key = mySensorBme280.gkey();
|
||||
sCmd.addCommand(key.c_str(), bme280ReadingHum);
|
||||
mySensorBme280.SensorBme280Init();
|
||||
mySensorBme280.clear();
|
||||
}
|
||||
void bme280ReadingHum() {
|
||||
String key = sCmd.order();
|
||||
mySensorBme280.SensorBme280ReadHum(key);
|
||||
}
|
||||
|
||||
void bme280Press() {
|
||||
mySensorBme280.update();
|
||||
String key = mySensorBme280.gkey();
|
||||
sCmd.addCommand(key.c_str(), bme280ReadingPress);
|
||||
mySensorBme280.SensorBme280Init();
|
||||
mySensorBme280.clear();
|
||||
}
|
||||
void bme280ReadingPress() {
|
||||
String key = sCmd.order();
|
||||
mySensorBme280.SensorBme280ReadPress(key);
|
||||
}
|
||||
//#endif
|
||||
@@ -1,35 +0,0 @@
|
||||
#include "items/SensorBmp280Class.h"
|
||||
|
||||
#include "BufferExecute.h"
|
||||
//#ifdef SensorBmp280Enabled
|
||||
//=========================================Модуль ультрозвукового дальномера==================================================================
|
||||
//bmp280-temp;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//bmp280-hum;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//bmp280-press;id;anydata;Сенсоры;Температура;order;c[1]
|
||||
//=========================================================================================================================================
|
||||
SensorBmp280Class mySensorBmp280;
|
||||
|
||||
void bmp280Temp() {
|
||||
mySensorBmp280.update();
|
||||
String key = mySensorBmp280.gkey();
|
||||
sCmd.addCommand(key.c_str(), bmp280ReadingTemp);
|
||||
mySensorBmp280.SensorBmp280Init();
|
||||
mySensorBmp280.clear();
|
||||
}
|
||||
void bmp280ReadingTemp() {
|
||||
String key = sCmd.order();
|
||||
mySensorBmp280.SensorBmp280ReadTmp(key);
|
||||
}
|
||||
|
||||
void bmp280Press() {
|
||||
mySensorBmp280.update();
|
||||
String key = mySensorBmp280.gkey();
|
||||
sCmd.addCommand(key.c_str(), bmp280ReadingPress);
|
||||
mySensorBmp280.SensorBmp280Init();
|
||||
mySensorBmp280.clear();
|
||||
}
|
||||
void bmp280ReadingPress() {
|
||||
String key = sCmd.order();
|
||||
mySensorBmp280.SensorBmp280ReadPress(key);
|
||||
}
|
||||
//#endif
|
||||
@@ -1,54 +0,0 @@
|
||||
#include "items/SensorDallas.h"
|
||||
#include "Class/LineParsing.h"
|
||||
#include "Global.h"
|
||||
#include "BufferExecute.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
SensorDallas::SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String key) {
|
||||
_interval = interval * 1000;
|
||||
_key = key;
|
||||
_pin = pin;
|
||||
_index = index;
|
||||
|
||||
oneWire = new OneWire((uint8_t)_pin);
|
||||
sensors.setOneWire(oneWire);
|
||||
sensors.begin();
|
||||
sensors.setResolution(12);
|
||||
}
|
||||
|
||||
SensorDallas::~SensorDallas() {}
|
||||
|
||||
void SensorDallas::loop() {
|
||||
currentMillis = millis();
|
||||
unsigned long difference = currentMillis - prevMillis;
|
||||
if (difference >= _interval) {
|
||||
prevMillis = millis();
|
||||
readDallas();
|
||||
}
|
||||
}
|
||||
|
||||
void SensorDallas::readDallas() {
|
||||
sensors.requestTemperaturesByIndex(_index);
|
||||
float value = sensors.getTempCByIndex(_index);
|
||||
eventGen2(_key, String(value));
|
||||
jsonWriteStr(configLiveJson, _key, String(value));
|
||||
publishStatus(_key, String(value));
|
||||
SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(value));
|
||||
}
|
||||
|
||||
MySensorDallasVector* mySensorDallas2 = nullptr;
|
||||
|
||||
void dallas() {
|
||||
myLineParsing.update();
|
||||
String interval = myLineParsing.gint();
|
||||
String pin = myLineParsing.gpin();
|
||||
String index = myLineParsing.gindex();
|
||||
String key = myLineParsing.gkey();
|
||||
myLineParsing.clear();
|
||||
|
||||
static bool firstTime = true;
|
||||
if (firstTime) mySensorDallas2 = new MySensorDallasVector();
|
||||
firstTime = false;
|
||||
mySensorDallas2->push_back(SensorDallas(interval.toInt(), pin.toInt(), index.toInt(), key));
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
#include "items/SensorDhtClass.h"
|
||||
|
||||
#include "BufferExecute.h"
|
||||
//#ifdef SensorDhtEnabled
|
||||
//=========================================DHT Sensor==================================================================
|
||||
//dht-temp;id;anydata;Сенсоры;Температура;order;pin;type[dht11];c[1]
|
||||
//dht-hum;id;anydata;Сенсоры;Влажность;order;pin;type[dht11];c[1]
|
||||
//=========================================================================================================================================
|
||||
SensorDhtClass mySensorDht;
|
||||
void dhtTemp() {
|
||||
mySensorDht.update();
|
||||
String key = mySensorDht.gkey();
|
||||
sCmd.addCommand(key.c_str(), dhtReadingTemp);
|
||||
mySensorDht.SensorDhtInit();
|
||||
mySensorDht.clear();
|
||||
}
|
||||
void dhtReadingTemp() {
|
||||
String key = sCmd.order();
|
||||
mySensorDht.SensorDhtReadTemp(key);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void dhtHum() {
|
||||
mySensorDht.update();
|
||||
String key = mySensorDht.gkey();
|
||||
sCmd.addCommand(key.c_str(), dhtReadingHum);
|
||||
mySensorDht.SensorDhtInit();
|
||||
mySensorDht.clear();
|
||||
}
|
||||
void dhtReadingHum() {
|
||||
String key = sCmd.order();
|
||||
mySensorDht.SensorDhtReadHum(key);
|
||||
}
|
||||
//#endif
|
||||
@@ -1,23 +0,0 @@
|
||||
//#include "items/SensorModbusClass.h"
|
||||
//
|
||||
//#include "BufferExecute.h"
|
||||
////#ifdef SensorModbusEnabled
|
||||
////=========================================Модуль modbus===================================================================================
|
||||
////modbus;id;anydata;Сенсоры;Температура;order;addr[1];regaddr[0];c[1]
|
||||
////=========================================================================================================================================
|
||||
//SensorModbusClass mySensorModbus;
|
||||
//
|
||||
//void modbus() {
|
||||
// mySensorModbus.update();
|
||||
// String key = mySensorModbus.gkey();
|
||||
// sCmd.addCommand(key.c_str(), modbusReading);
|
||||
// mySensorModbus.SensorModbusInit();
|
||||
// mySensorModbus.clear();
|
||||
//}
|
||||
//void modbusReading() {
|
||||
// String key = sCmd.order();
|
||||
// String addr = sCmd.next();
|
||||
// String regaddr = sCmd.next();
|
||||
// mySensorModbus.SensorModbusRead(key, addr.toInt(), regaddr.toInt());
|
||||
//}
|
||||
////#endif
|
||||
@@ -1,20 +0,0 @@
|
||||
#include "BufferExecute.h"
|
||||
#include "items/SensorUltrasonicClass.h"
|
||||
//#ifdef SensorUltrasonicEnabled
|
||||
//=========================================Модуль ультрозвукового дальномера==================================================================
|
||||
//ultrasonic-cm;id;anydata;Сенсоры;Расстояние;order;pin[12,13];map[1,100,1,100];c[1]
|
||||
//=========================================================================================================================================
|
||||
SensorUltrasonic mySensorUltrasonic;
|
||||
void ultrasonicCm() {
|
||||
mySensorUltrasonic.update();
|
||||
String key = mySensorUltrasonic.gkey();
|
||||
sCmd.addCommand(key.c_str(), ultrasonicReading);
|
||||
mySensorUltrasonic.init();
|
||||
mySensorUltrasonic.clear();
|
||||
}
|
||||
|
||||
void ultrasonicReading() {
|
||||
String key = sCmd.order();
|
||||
mySensorUltrasonic.SensorUltrasonicRead(key);
|
||||
}
|
||||
//#endif
|
||||
@@ -1,20 +0,0 @@
|
||||
#include "Class/LineParsing.h"
|
||||
#include "BufferExecute.h"
|
||||
#include "Global.h"
|
||||
#include <Arduino.h>
|
||||
|
||||
void sysUptime() {
|
||||
myLineParsing.update();
|
||||
String key = myLineParsing.gkey();
|
||||
sCmd.addCommand(key.c_str(), uptimeReading);
|
||||
sensorReadingMap30sec += key + ",";
|
||||
myLineParsing.clear();
|
||||
}
|
||||
|
||||
void uptimeReading() {
|
||||
String key = sCmd.order();
|
||||
String uptime = timeNow->getUptime();
|
||||
jsonWriteStr(configLiveJson, key, uptime);
|
||||
publishStatus(key, uptime);
|
||||
SerialPrint("I", "Sensor", "'" + key + "' data: " + uptime);
|
||||
}
|
||||
150
src/main.cpp
150
src/main.cpp
@@ -1,150 +0,0 @@
|
||||
|
||||
#include <SSDP.h>
|
||||
|
||||
#include "BufferExecute.h"
|
||||
#include "Bus.h"
|
||||
#include "Class/CallBackTest.h"
|
||||
#include "Class/NotAsync.h"
|
||||
#include "Class/ScenarioClass3.h"
|
||||
#include "Cmd.h"
|
||||
#include "Global.h"
|
||||
#include "Init.h"
|
||||
#include "ItemsList.h"
|
||||
#include "RemoteOrdersUdp.h"
|
||||
#include "Utils/StatUtils.h"
|
||||
#include "Utils/Timings.h"
|
||||
#include "Utils/WebUtils.h"
|
||||
#include "items/ButtonInClass.h"
|
||||
#include "items/LoggingClass.h"
|
||||
#include "items/ImpulsOutClass.h"
|
||||
#include "items/SensorDallas.h"
|
||||
#include "Telegram.h"
|
||||
|
||||
void not_async_actions();
|
||||
|
||||
Timings metric;
|
||||
boolean initialized = false;
|
||||
|
||||
void setup() {
|
||||
WiFi.setAutoConnect(false);
|
||||
WiFi.persistent(false);
|
||||
|
||||
Serial.begin(115200);
|
||||
Serial.flush();
|
||||
Serial.println();
|
||||
Serial.println("--------------started----------------");
|
||||
|
||||
setChipId();
|
||||
|
||||
myNotAsyncActions = new NotAsync(do_LAST);
|
||||
myScenario = new Scenario();
|
||||
|
||||
fileSystemInit();
|
||||
SerialPrint("I", "FS", "FS Init");
|
||||
|
||||
loadConfig();
|
||||
SerialPrint("I", "Conf", "Config Init");
|
||||
|
||||
clock_init();
|
||||
SerialPrint("I", "Time", "Clock Init");
|
||||
|
||||
handle_time_init();
|
||||
SerialPrint("I", "Time", "Handle time init(");
|
||||
|
||||
sensorsInit();
|
||||
SerialPrint("I", "Sensors", "Sensors Init");
|
||||
|
||||
itemsListInit();
|
||||
SerialPrint("I", "Items", "Items Init");
|
||||
|
||||
all_init();
|
||||
SerialPrint("I", "Init", "Init Init");
|
||||
|
||||
routerConnect();
|
||||
SerialPrint("I", "WIFI", "Network Init");
|
||||
|
||||
telegramInit();
|
||||
SerialPrint("I", "Telegram", "Telegram Init");
|
||||
|
||||
uptime_init();
|
||||
SerialPrint("I", "Uptime", "Uptime Init");
|
||||
|
||||
upgradeInit();
|
||||
SerialPrint("I", "Update", "Updater Init");
|
||||
|
||||
HttpServer::init();
|
||||
SerialPrint("I", "HTTP", "HttpServer Init");
|
||||
|
||||
web_init();
|
||||
SerialPrint("I", "Web", "WebAdmin Init");
|
||||
|
||||
initSt();
|
||||
SerialPrint("I", "Stat", "Stat Init");
|
||||
|
||||
#ifdef UDP_ENABLED
|
||||
SerialPrint("I", "UDP", "Udp Init");
|
||||
asyncUdpInit();
|
||||
#endif
|
||||
|
||||
SerialPrint("I", "Bus", "Bus Init");
|
||||
busInit();
|
||||
|
||||
#ifdef SSDP_ENABLED
|
||||
SerialPrint("I", "SSDP", "Ssdp Init");
|
||||
SsdpInit();
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
//esp_log_level_set("esp_littlefs", ESP_LOG_NONE);
|
||||
|
||||
ts.add(
|
||||
TEST, 1000 * 60, [&](void*) {
|
||||
SerialPrint("I", "System", printMemoryStatus());
|
||||
},
|
||||
nullptr, true);
|
||||
|
||||
just_load = false;
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (!initialized) {
|
||||
return;
|
||||
}
|
||||
#ifdef OTA_UPDATES_ENABLED
|
||||
ArduinoOTA.handle();
|
||||
#endif
|
||||
#ifdef WS_enable
|
||||
ws.cleanupClients();
|
||||
#endif
|
||||
timeNow->loop();
|
||||
mqttLoop();
|
||||
myButtonIn.loop();
|
||||
myScenario->loop();
|
||||
loopCmdExecute();
|
||||
//loopSerial();
|
||||
|
||||
myNotAsyncActions->loop();
|
||||
ts.update();
|
||||
|
||||
handleTelegram();
|
||||
|
||||
if (myLogging != nullptr) {
|
||||
for (unsigned int i = 0; i < myLogging->size(); i++) {
|
||||
myLogging->at(i).loop();
|
||||
}
|
||||
}
|
||||
|
||||
if (myImpulsOut != nullptr) {
|
||||
for (unsigned int i = 0; i < myImpulsOut->size(); i++) {
|
||||
myImpulsOut->at(i).loop();
|
||||
}
|
||||
}
|
||||
|
||||
if (mySensorDallas2 != nullptr) {
|
||||
for (unsigned int i = 0; i < mySensorDallas2->size(); i++) {
|
||||
mySensorDallas2->at(i).loop();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user