добавил сценарии и класс сенсора

This commit is contained in:
Dmitry Borisenko
2022-01-14 21:48:43 +01:00
parent a18552c4f4
commit e6e3497c40
20 changed files with 857 additions and 33 deletions

View File

@@ -42,7 +42,7 @@ void asyncWebServerInit() {
// динамические данные
// server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest *request) {
// request->send(200, "application/json", configLiveJson);
// request->send(200, "application/json", paramsFlashJson);
//});
//
// server.on("/config.store.json", HTTP_GET, [](AsyncWebServerRequest *request) {

46
src/Buffers.cpp Normal file
View File

@@ -0,0 +1,46 @@
#include "Buffers.h"
//генеирует событие
void eventGen2(String eventName, String eventValue) {
if (!jsonReadBool(settingsFlashJson, "scen")) {
return;
}
String event = eventName + " " + eventValue + ",";
eventBuf += event;
SerialPrint("I", "Event add", eventName + " " + eventValue);
if (jsonReadBool(settingsFlashJson, "MqttOut")) {
if (eventName != "timenow") {
publishEvent(eventName, eventValue);
}
}
}
void spaceCmdExecute(String& cmdStr) {
cmdStr += "\r\n";
cmdStr.replace("\r\n", "\n");
cmdStr.replace("\r", "\n");
while (cmdStr.length()) {
String buf = selectToMarker(cmdStr, "\n");
if (buf != "") {
sCmd.readStr(buf);
SerialPrint("I", F("Order done W"), buf);
}
cmdStr = deleteBeforeDelimiter(cmdStr, "\n");
}
}
String getValueJson(String& key) {
String live = jsonReadStr(paramsHeapJson, key);
String store = jsonReadStr(paramsFlashJson, key);
if (live != nullptr) {
return live;
} else if (store != nullptr) {
return store;
} else if (store == nullptr && live == nullptr) {
return "no value";
} else {
return "data error";
}
}

View File

@@ -10,6 +10,8 @@ void configure(String& path) {
//=============================
} else if (value == F("pwm-out")) {
//=============================
} else if (value == F("analog-adc")) {
//=============================
} else {
SerialPrint(F("E"), F("Config"), F("config.json error, type not exist"));
}

View File

@@ -7,6 +7,7 @@
TickerScheduler ts(MYTEST + 1);
WiFiClient espClient;
PubSubClient mqtt(espClient);
StringCommand sCmd;
#ifdef ASYNC_WEB_SERVER
AsyncWebServer server(80);
#endif
@@ -33,6 +34,10 @@ String settingsFlashJson = "{}"; //переменная в которой хр
String paramsFlashJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти и синхронизированна с flash памятью
String paramsHeapJson = "{}"; //переменная в которой хранятся все параметры, находится в оперативной памяти только
// buf
String orderBuf = "";
String eventBuf = "";
// Mqtt
String mqttServer = "";
int mqttPort = 0;

39
src/classes/IoTSensor.cpp Normal file
View File

@@ -0,0 +1,39 @@
#include "Utils/JsonUtils.h"
#include "Utils/SerialPrint.h"
#include "Classes/ScenarioClass3.h"
#include "Classes/IoTSensor.h"
void IoTSensor::init(String key, String id, unsigned long interval) {
_interval = interval * 1000;
_key = key;
_id = id;
}
IoTSensor::IoTSensor() {}
IoTSensor::~IoTSensor() {}
String IoTSensor::getKey() {
return _key;
}
String IoTSensor::getID() {
return _id;
};
void IoTSensor::loop() {
currentMillis = millis();
difference = currentMillis - prevMillis;
if (difference >= _interval) {
prevMillis = millis();
this->doByInterval();
}
}
void IoTSensor::regEvent(String value, String consoleInfo = "") {
eventGen2(_id, String(value));
jsonWriteStr(paramsFlashJson, _id, String(value));
publishStatus(_id, String(value));
SerialPrint("I", "Sensor", "'" + _id + "' data: " + String(value) + "' " + consoleInfo);
}
void IoTSensor::doByInterval() {}

View File

@@ -0,0 +1,3 @@
#include "Classes/ScenarioClass3.h"
Scenario* myScenario;

View File

@@ -1,12 +0,0 @@
#include "Utils/Pretty.h"
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";
}

170
src/utils/StringUtils.cpp Normal file
View File

@@ -0,0 +1,170 @@
#include "Utils/StringUtils.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";
}
//преобразовываем байтовый массив в человеческий вид HEX в строке
void hex2string(byte array[], unsigned int len, char buffer[]) {
for (unsigned int i = 0; i < len; i++) {
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i * 2 + 0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i * 2 + 1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len * 2] = '\0';
}
inline unsigned char ChartoHex(char ch) {
return ((ch >= 'A') ? (ch - 'A' + 0xA) : (ch - '0')) & 0x0F;
}
// str - указатель на массив символов
// bytes - выходной буфер
// функция возвращает колл-во байт
//
int string2hex(const char* str, unsigned char* bytes) {
unsigned char Hi, Lo;
int i = 0;
while ((Hi = *str++) && (Lo = *str++)) {
bytes[i++] = (ChartoHex(Hi) << 4) | ChartoHex(Lo);
}
return i;
}
uint8_t hexStringToUint8(String hex) {
uint8_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x00 && tmp <= 0xFF) {
return tmp;
}
}
uint16_t hexStringToUint16(String hex) {
uint16_t tmp = strtol(hex.c_str(), NULL, 0);
if (tmp >= 0x0000 && tmp <= 0xFFFF) {
return tmp;
}
}
size_t itemsCount2(String str, const String& separator) {
// если строки поиск нет сразу выход
if (str.indexOf(separator) == -1) {
return 0;
}
// добавим для корректного поиска
str += separator;
size_t cnt = 0;
while (str.length()) {
// отбросим проверенный блок до разделителя
str = deleteBeforeDelimiter(str, separator);
cnt++;
}
return cnt;
}
size_t itemsCount(String& str, const char* delim) {
size_t cnt = 0;
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
char* token;
while ((token = strtok_r(cstr, delim, &cstr))) {
cnt++;
// printf("%s\n", token);
}
delete[] cstr;
return cnt;
}
char* stringToChar(String& str) {
char* mychar = new char[str.length() + 1];
strcpy(mychar, str.c_str());
return mychar;
}
boolean isDigitStr(const String& str) {
for (size_t i = 0; i < str.length(); i++) {
if (!isDigit(str.charAt(i))) {
return false;
}
}
return str.length();
}
boolean isDigitDotCommaStr(const String& str) {
for (size_t i = 0; i < str.length(); i++) {
char latter = str.charAt(i);
if (!isDigit(latter) && latter != '.' && latter != '-') {
return false;
}
}
return true;
}
String prettyBytes(size_t size) {
if (size < 1024)
return String(size) + "b";
else if (size < (1024 * 1024))
return String(size / 1024.0) + "kB";
else if (size < (1024 * 1024 * 1024))
return String(size / 1024.0 / 1024.0) + "MB";
else
return String(size / 1024.0 / 1024.0 / 1024.0) + "GB";
}

View File

@@ -115,18 +115,18 @@ void breakEpochToTime(unsigned long epoch, Time_t& tm) {
tm.valid = (epoch > MIN_DATETIME);
}
//void timeInit() {
// ts.add(
// TIME, 1000, [&](void*) {
// String timenow = timeNow->getTimeWOsec();
// static String prevTime;
// if (prevTime != timenow) {
// prevTime = timenow;
// jsonWriteStr(configLiveJson, "timenow", timenow);
// eventGen2("timenow", timenow);
// SerialPrint("i", F("NTP"), timenow);
// }
// },
// nullptr, true);
// SerialPrint("i", F("NTP"), F("Handle time init"));
//}
// void timeInit() {
// ts.add(
// TIME, 1000, [&](void*) {
// String timenow = timeNow->getTimeWOsec();
// static String prevTime;
// if (prevTime != timenow) {
// prevTime = timenow;
// jsonWriteStr(paramsFlashJson, "timenow", timenow);
// eventGen2("timenow", timenow);
// SerialPrint("i", F("NTP"), timenow);
// }
// },
// nullptr, true);
// SerialPrint("i", F("NTP"), F("Handle time init"));
// }