diff --git a/data/config.json b/data/config.json
index 8c8b402a..562ff604 100644
--- a/data/config.json
+++ b/data/config.json
@@ -3,8 +3,8 @@
"chipID": "",
"apssid": "IoTmanager",
"appass": "",
- "routerssid": "VOLODYA",
- "routerpass": "BELCHENKO",
+ "routerssid": "rise",
+ "routerpass": "hostel3333",
"timezone": 2,
"ntp": "pool.ntp.org",
"mqttServer": "91.204.228.124",
@@ -17,7 +17,7 @@
"weblogin": "admin",
"webpass": "admin",
"udponoff": "1",
- "blink": "0",
+ "blink": "1",
"oneWirePin": "2",
"serverip": "http://206.189.49.244"
}
\ No newline at end of file
diff --git a/data/items/button-out.npin.txt b/data/items/button-out.npin.txt
index 380b815f..33bb17da 100644
--- a/data/items/button-out.npin.txt
+++ b/data/items/button-out.npin.txt
@@ -1 +1 @@
-0;button-out;id;toggleSunMoon;Кнопки;Освещение;order;st[0]
\ No newline at end of file
+0;button-out;id;toggle;Кнопки;Освещение;order;st[0]
\ No newline at end of file
diff --git a/data/items/dallas-temp.txt b/data/items/dallas-temp.txt
index a6b87c28..0da8bdca 100644
--- a/data/items/dallas-temp.txt
+++ b/data/items/dallas-temp.txt
@@ -1 +1 @@
-0;dallas-temp;id;anydataTemp;Сенсоры;Температура;order;sal;c[1]
\ No newline at end of file
+0;dallas-temp;id;anydataTemp;Сенсоры;Температура;order;sal;index[0];int[10]
\ No newline at end of file
diff --git a/data/items/impuls-out.txt b/data/items/impuls-out.txt
new file mode 100644
index 00000000..99994ae5
--- /dev/null
+++ b/data/items/impuls-out.txt
@@ -0,0 +1 @@
+0;impuls-out;id;na;na;na;order;pin
\ No newline at end of file
diff --git a/data/presets/dal.c.txt b/data/presets/dal.c.txt
new file mode 100644
index 00000000..7cd73ce5
--- /dev/null
+++ b/data/presets/dal.c.txt
@@ -0,0 +1,5 @@
+0;dallas-temp;temp;anydataTemp;Термостат;Температура;1;pin[2];index[0];int[10]
+0;logging;log;chart;Термостат;История;2;val[temp];int[60];cnt[100]
+0;input-digit;inputU;inputDigit;Термостат;Верхний#порог;3;st[30]
+0;input-digit;inputL;inputDigit;Термостат;Нижний#порог;4;st[20]
+0;button-out;button;toggle;Термостат;Нагрев;5;pin[12];st[0]
\ No newline at end of file
diff --git a/data/presets/dal.s.txt b/data/presets/dal.s.txt
new file mode 100644
index 00000000..43f05cc5
--- /dev/null
+++ b/data/presets/dal.s.txt
@@ -0,0 +1,6 @@
+temp > inputU
+button 0
+end
+temp < inputL
+button 1
+end
\ No newline at end of file
diff --git a/data/presets/dht.c.txt b/data/presets/dht.c.txt
new file mode 100644
index 00000000..2c9acd11
--- /dev/null
+++ b/data/presets/dht.c.txt
@@ -0,0 +1,5 @@
+0;dht-hum;hum;anydataHum;Теплица;Влажность;1;pin[2];type[dht11];c[1]
+0;logging;log;chart;Теплица;Влажность;2;val[hum];int[60];cnt[100]
+0;input-digit;inputU;inputDigit;Теплица;Верхний#порог;3;st[45]
+0;input-digit;inputL;inputDigit;Теплица;Нижний#порог;4;st[35]
+0;button-out;button;toggle;Теплица;Полив;5;pin[12];st[0]
\ No newline at end of file
diff --git a/data/presets/dht.s.txt b/data/presets/dht.s.txt
new file mode 100644
index 00000000..bbf78407
--- /dev/null
+++ b/data/presets/dht.s.txt
@@ -0,0 +1,6 @@
+hum > inputU
+button 0
+end
+hum < inputL
+button 1
+end
\ No newline at end of file
diff --git a/data/set.device.json b/data/set.device.json
index 1a94ee8d..9dd95abc 100644
--- a/data/set.device.json
+++ b/data/set.device.json
@@ -43,14 +43,14 @@
},
{
"type": "h4",
- "title": "LittleFS version: 262"
+ "title": "LittleFS version: 264"
},
{
"type": "hr"
},
{
"type": "dropdown",
- "name": "help-url",
+ "name": "help-url1",
"class": "btn btn-default",
"style": "display:inline",
"title": {
@@ -74,12 +74,23 @@
"/set?addItem=bme280-press": "17.Датчик давления bme280",
"/set?addItem=bmp280-temp": "18.Датчик температуры bmp280",
"/set?addItem=bmp280-press": "19.Датчик давления bmp280",
- "/set?addItem=modbus": "20.Прочитать регистр modbus устройства",
+ "/set?addItem=impuls-out": "20.Создать импульсы через заданный промежуток времени (управление шд)",
+ "/set?addItem=modbus": "21.Прочитать регистр modbus устройства",
"/set?addItem=logging": "a.Логгирование и вывод в график любой величины",
"/set?addItem=uptime": "b.Отобразить время работы устройства"
}
},
-
+ {
+ "type": "dropdown",
+ "name": "help-url2",
+ "class": "btn btn-default",
+ "style": "display:inline",
+ "title": {
+ "#": "Выберите пресет из списка",
+ "/set?addPreset=dal.c": "1.Термостат на основе ds18b20 (устройство держит заданный уровень температуры)",
+ "/set?addPreset=dht.c": "2.Контроль влажности на основе DHT (устройство держит заданный уровень влажности)"
+ }
+ },
{
"type": "hr"
},
@@ -116,7 +127,7 @@
},
{
"type": "text",
- "title": "
После любого изменения таблицы элементов, включая удаление/добавление строк, необходимо нажать кнопку СОХРАНИТЬ ТАБЛИЦУ
"
+ "title": "После любого изменения таблицы элементов, включая удаление/добавление строк, необходимо нажать кнопку СОХРАНИТЬ ТАБЛИЦУ. Иногда, для корректной работы необходимо перезагрузить устройство после финального завершения его настройки
"
},
{
"type": "h2",
diff --git a/include/BufferExecute.h b/include/BufferExecute.h
index 85252a36..076d73da 100644
--- a/include/BufferExecute.h
+++ b/include/BufferExecute.h
@@ -1,8 +1,10 @@
#pragma once
#include
-extern void loopCmdAdd(const String &cmdStr);
-extern void fileCmdExecute(const String &filename);
-extern void csvCmdExecute(String &cmdStr);
-extern void spaceCmdExecute(String &cmdStr);
-extern void loopCmdExecute();
\ No newline at end of file
+extern void loopCmdAdd(const String& cmdStr);
+extern void fileCmdExecute(const String& filename);
+extern void csvCmdExecute(String& cmdStr);
+extern void spaceCmdExecute(String& cmdStr);
+extern void loopCmdExecute();
+extern void addKey(String& key, String& keyNumberTable, int number);
+extern int getKeyNum(String& key, String& keyNumberTable);
\ No newline at end of file
diff --git a/include/Class/LineParsing.h b/include/Class/LineParsing.h
index 3543b581..99a807f1 100644
--- a/include/Class/LineParsing.h
+++ b/include/Class/LineParsing.h
@@ -24,6 +24,7 @@ class LineParsing {
String _int;
String _cnt;
String _val;
+ String _index;
public:
LineParsing() :
@@ -44,7 +45,8 @@ class LineParsing {
_type{""},
_int{""},
_cnt{""},
- _val{""}
+ _val{""},
+ _index{""}
{};
@@ -98,6 +100,9 @@ class LineParsing {
if (arg.indexOf("val[") != -1) {
_val = extractInner(arg);
}
+ if (arg.indexOf("index[") != -1) {
+ _index = extractInner(arg);
+ }
}
}
@@ -155,12 +160,16 @@ class LineParsing {
String gint() {
return _int;
}
- String gmaxcnt() {
+ String gcnt() {
return _cnt;
}
- String gvalue() {
+ String gval() {
return _val;
}
+ String gindex() {
+ return _index;
+ }
+
void clear() {
_key = "";
@@ -180,6 +189,7 @@ class LineParsing {
_int = "";
_cnt = "";
_val = "";
+ _index = "";
}
String extractInnerDigit(String str) {
diff --git a/include/Class/ScenarioClass.h b/include/Class/ScenarioClass.h
index 3a241112..b3a1f064 100644
--- a/include/Class/ScenarioClass.h
+++ b/include/Class/ScenarioClass.h
@@ -4,7 +4,7 @@
#include "Global.h"
class Scenario {
- protected:
+protected:
String _scenarioTmp;
String _condition;
String _conditionParam;
@@ -15,16 +15,16 @@ class Scenario {
String _eventParam;
String _eventValue;
- public:
- Scenario() : _scenarioTmp{""},
- _condition{""},
- _conditionParam{""},
- _conditionSign{""},
- _conditionValue{""},
- _scenBlok{""},
- _event{""},
- _eventParam{""},
- _eventValue{""} {};
+public:
+ Scenario() : _scenarioTmp{ "" },
+ _condition{ "" },
+ _conditionParam{ "" },
+ _conditionSign{ "" },
+ _conditionValue{ "" },
+ _scenBlok{ "" },
+ _event{ "" },
+ _eventParam{ "" },
+ _eventValue{ "" } {};
void load() {
_scenarioTmp = scenario;
@@ -69,19 +69,28 @@ class Scenario {
if (_conditionSign == "=") {
flag = _eventValue == _conditionValue;
- } else if (_conditionSign == "!=") {
+ }
+ else if (_conditionSign == "!=") {
flag = _eventValue != _conditionValue;
- } else if (_conditionSign == "<") {
- flag = _eventValue.toInt() < _conditionValue.toInt();
- } else if (_conditionSign == ">") {
- flag = _eventValue.toInt() > _conditionValue.toInt();
- } else if (_conditionSign == ">=") {
- flag = _eventValue.toInt() >= _conditionValue.toInt();
- } else if (_conditionSign == "<=") {
- flag = _eventValue.toInt() <= _conditionValue.toInt();
+ }
+ else if (_conditionSign == "<") {
+ flag = _eventValue.toFloat() < _conditionValue.toFloat();
+ }
+ else if (_conditionSign == ">") {
+ flag = _eventValue.toFloat() > _conditionValue.toFloat();
+ }
+ else if (_conditionSign == ">=") {
+ flag = _eventValue.toFloat() >= _conditionValue.toFloat();
+ }
+ else if (_conditionSign == "<=") {
+ flag = _eventValue.toFloat() <= _conditionValue.toFloat();
}
- if (flag) Serial.println("I Scenario event: " + _condition);
+ if (flag) {
+ //SerialPrint("I", "Scenario", "event value: " + _eventValue);
+ //SerialPrint("I", "Scenario", "condition value: " + _conditionValue);
+ SerialPrint("I", "Scenario", "event: " + _condition);
+ }
return flag;
}
@@ -97,7 +106,12 @@ class Scenario {
this->calculate2();
if (this->isConditionSatisfied()) { //если вошедшее событие выполняет условие сценария
_scenBlok = deleteBeforeDelimiter(_scenBlok, "\n");
- //Serial.println(" [>] Making: " + _scenBlok);
+ String forPrint = _scenBlok;
+ forPrint.replace("end", "");
+ forPrint.replace("\r\n", "");
+ forPrint.replace("\r", "");
+ forPrint.replace("\n", "");
+ SerialPrint("I", "Scenario", "making: " + forPrint);
spaceCmdExecute(_scenBlok);
}
}
@@ -110,4 +124,5 @@ class Scenario {
return jsonReadBool(configSetupJson, "scen") && eventBuf != "";
}
};
+
extern Scenario* myScenario;
\ No newline at end of file
diff --git a/include/Consts.h b/include/Consts.h
index 0fbb2765..0f7b483f 100644
--- a/include/Consts.h
+++ b/include/Consts.h
@@ -1,45 +1,32 @@
#pragma once
-//
-// Firmware
-//
+//===========Firmware=============================================================================================================================================
#ifdef ESP8266
#define FIRMWARE_NAME "esp8266-iotm"
-#define FIRMWARE_VERSION 262
+#define FIRMWARE_VERSION 264
#endif
#ifdef ESP32
#define FIRMWARE_NAME "esp32-iotm"
#define FIRMWARE_VERSION 259
#endif
-
#define FLASH_4MB true
-//
-// System
-//
+//===========FSystem==============================================================================================================================================
#define NUM_BUTTONS 6
#define LED_PIN 2
-//
-// MQTT
-//
+//===========MQTT=================================================================================================================================================
#define MQTT_RECONNECT_INTERVAL 20000
-//
-// Telemetry
-//
+//==========Telemetry=============================================================================================================================================
#define TELEMETRY_UPDATE_INTERVAL_MIN 60
-
-//
-// Configuration
-//
+//=========Configuration==========================================================================================================================================
#define DEVICE_CONFIG_FILE "s.conf.csv"
#define DEVICE_SCENARIO_FILE "s.scen.txt"
-//
-// System parts
-//
+
+//=========System parts===========================================================================================================================================
//#define OTA_UPDATES_ENABLED
//#define MDNS_ENABLED
//#define WEBSOCKET_ENABLED
@@ -47,9 +34,7 @@
//#define UDP_ENABLED
//#define SSDP_ENABLED
-//
-// Sensors enable/disable
-//
+//=========Sensors enable/disable=================================================================================================================================
#define TANK_LEVEL_SAMPLES 10
#define LEVEL_ENABLED
#define ANALOG_ENABLED
@@ -58,15 +43,13 @@
#define BMP_ENABLED
#define BME_ENABLED
-//
-// Gears enable/disable
-//
+
+//=========Gears enable/disable===================================================================================================================================
#define STEPPER_ENABLED
#define SERVO_ENABLED
-//
-// Other enable/disable
-//
+
+//========Other enable/disable====================================================================================================================================
#define LOGGING_ENABLED
#define SERIAL_ENABLED
#define PUSH_ENABLED
@@ -84,6 +67,7 @@ struct Time_t {
unsigned long valid;
};
+//================================================================================================================================================================
enum TimerTask_t { WIFI_SCAN,
WIFI_MQTT_CONNECTION_CHECK,
SENSORS10SEC,
diff --git a/include/Global.h b/include/Global.h
index fc9646a5..b4bcb7c5 100644
--- a/include/Global.h
+++ b/include/Global.h
@@ -40,8 +40,7 @@ extern WiFiClient espClient;
extern PubSubClient mqtt;
extern StringCommand sCmd;
extern AsyncWebServer server;
-extern DallasTemperature sensors;
-extern OneWire* oneWire;
+
extern boolean but[NUM_BUTTONS];
extern Bounce* buttons;
@@ -65,23 +64,20 @@ extern String eventBuf;
extern String itemsFile;
extern String itemsLine;
+//key lists and numbers
+extern String impulsKeyList;
+extern int impulsEnterCounter;
+
// Sensors
extern String sensorReadingMap10sec;
extern String sensorReadingMap30sec;
-extern int8_t dallasEnterCounter;
-extern String logging_value_names_list;
+
+extern String loggingKeyList;
extern int enter_to_logging_counter;
extern int scenario_line_status[40];
extern int lastVersion;
-//Global functions
-// Logging
-extern void logging();
-extern void deleteOldDate(String filename, size_t max_lines, String date_to_add);
-
-
-
// Main
extern void setChipId();
extern void saveConfig();
diff --git a/include/ItemsCmd.h b/include/ItemsCmd.h
index 24d04b67..39bbca79 100644
--- a/include/ItemsCmd.h
+++ b/include/ItemsCmd.h
@@ -51,3 +51,5 @@ extern void sysUptime();
extern void uptimeReading();
extern void logging();
+
+extern void impuls();
diff --git a/include/ItemsList.h b/include/ItemsList.h
index 940db0b5..c0b716ec 100644
--- a/include/ItemsList.h
+++ b/include/ItemsList.h
@@ -5,6 +5,7 @@
extern void itemsListInit();
extern void addItem(String name);
+extern void addPreset(String name);
extern void delChoosingItems();
extern void delAllItems();
extern uint8_t getNewElementNumber(String file);
diff --git a/include/items/ButtonOutClass.h b/include/items/ButtonOutClass.h
index 46590814..bd3587c3 100644
--- a/include/items/ButtonOutClass.h
+++ b/include/items/ButtonOutClass.h
@@ -5,8 +5,8 @@
#include "Global.h"
class ButtonOutClass : public LineParsing {
- public:
- ButtonOutClass() : LineParsing(){};
+public:
+ ButtonOutClass() : LineParsing() {};
void init() {
if (_pin != "") {
@@ -28,12 +28,13 @@ class ButtonOutClass : public LineParsing {
if (inv == "") {
digitalWrite(pinInt, state.toInt());
- } else {
+ }
+ else {
digitalWrite(pinInt, !state.toInt());
}
eventGen(key, "");
jsonWriteInt(configLiveJson, key, state.toInt());
- publishStatus(key, state);
+ publishStatus(key, state);
}
};
diff --git a/include/items/ImpulsOutClass.h b/include/items/ImpulsOutClass.h
new file mode 100644
index 00000000..1d9f9fa6
--- /dev/null
+++ b/include/items/ImpulsOutClass.h
@@ -0,0 +1,31 @@
+#pragma once
+#include
+
+#include "Global.h"
+
+class ImpulsOutClass;
+
+typedef std::vector MyImpulsOutVector;
+
+class ImpulsOutClass {
+ public:
+ ImpulsOutClass(unsigned int impulsPin);
+ ~ImpulsOutClass();
+
+ void loop();
+ void execute(unsigned long impulsPeriod, unsigned int impulsCount);
+
+ private:
+ unsigned long currentMillis;
+ unsigned long prevMillis;
+
+ unsigned long _impulsPeriod = 0;
+ unsigned int _impulsCount = 0;
+ unsigned int _impulsCountBuf = 0;
+ unsigned int _impulsPin = 0;
+
+};
+
+extern MyImpulsOutVector* myImpulsOut;
+
+extern void impulsExecute();
diff --git a/include/items/SensorDallas.h b/include/items/SensorDallas.h
new file mode 100644
index 00000000..3feeb572
--- /dev/null
+++ b/include/items/SensorDallas.h
@@ -0,0 +1,36 @@
+#pragma once
+#include "Global.h"
+#include
+
+extern DallasTemperature sensors;
+extern OneWire* oneWire;
+
+class SensorDallas;
+
+typedef std::vector MySensorDallasVector;
+
+class SensorDallas {
+public:
+
+ SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String key);
+ ~SensorDallas();
+
+ void loop();
+ void readDallas();
+
+private:
+
+ unsigned long currentMillis;
+ unsigned long prevMillis;
+ unsigned long _interval;
+ String _key;
+ unsigned int _pin;
+ unsigned int _index;
+
+};
+
+extern MySensorDallasVector* mySensorDallas2;
+
+extern void dallas();
+
+
diff --git a/include/items/SensorDallasClass.h b/include/items/SensorDallasClass.h
deleted file mode 100644
index 203bd7f0..00000000
--- a/include/items/SensorDallasClass.h
+++ /dev/null
@@ -1,45 +0,0 @@
-#pragma once
-#include
-#include "Class/LineParsing.h"
-#include "Global.h"
-#include "items/SensorConvertingClass.h"
-
-class SensorDallasClass : public SensorConvertingClass {
- public:
- SensorDallasClass() : SensorConvertingClass(){};
-
- void SensorDallasInit() {
- oneWire = new OneWire((uint8_t)_pin.toInt());
- sensors.setOneWire(oneWire);
- sensors.begin();
- sensors.setResolution(48);
-
- sensorReadingMap10sec += _key + ",";
- dallasEnterCounter++;
-
- jsonWriteInt(configOptionJson, _key + "_num", dallasEnterCounter);
- jsonWriteStr(configOptionJson, _key + "_map", _map);
- jsonWriteStr(configOptionJson, _key + "_с", _c);
- }
-
- void SensorDallasRead(String key) {
- float value;
- byte num = sensors.getDS18Count();
- sensors.requestTemperatures();
-
- int cnt = jsonReadInt(configOptionJson, key + "_num");
-
- for (byte i = 0; i < num; i++) {
- if (i == cnt) {
- value = sensors.getTempCByIndex(i);
- //value = this->mapping(key, value);
- float valueFl = this->correction(key, value);
- eventGen(key, "");
- jsonWriteStr(configLiveJson, key, String(valueFl));
- publishStatus(key, String(valueFl));
- SerialPrint("I", "Sensor", "'" + key + "' data: " + String(valueFl));
- }
- }
- }
-};
-extern SensorDallasClass mySensorDallas;
\ No newline at end of file
diff --git a/src/BufferExecute.cpp b/src/BufferExecute.cpp
index 83d6ab45..ca6ec574 100644
--- a/src/BufferExecute.cpp
+++ b/src/BufferExecute.cpp
@@ -3,19 +3,19 @@
#include "Global.h"
#include "Module/Terminal.h"
-void loopCmdAdd(const String &cmdStr) {
+void loopCmdAdd(const String& cmdStr) {
orderBuf += cmdStr;
if (!cmdStr.endsWith(",")) {
orderBuf += ",";
}
}
-void fileCmdExecute(const String &filename) {
+void fileCmdExecute(const String& filename) {
String cmdStr = readFile(filename, 4096);
csvCmdExecute(cmdStr);
}
-void csvCmdExecute(String &cmdStr) {
+void csvCmdExecute(String& cmdStr) {
cmdStr.replace(";", " ");
cmdStr += "\r\n";
cmdStr.replace("\r\n", "\n");
@@ -30,7 +30,7 @@ void csvCmdExecute(String &cmdStr) {
}
}
-void spaceCmdExecute(String &cmdStr) {
+void spaceCmdExecute(String& cmdStr) {
cmdStr += "\r\n";
cmdStr.replace("\r\n", "\n");
cmdStr.replace("\r", "\n");
@@ -52,7 +52,7 @@ void loopCmdExecute() {
void sensorsInit() {
ts.add(
- SENSORS10SEC, 10000, [&](void *) {
+ SENSORS10SEC, 10000, [&](void*) {
String buf = sensorReadingMap10sec;
while (buf.length()) {
String tmp = selectToMarker(buf, ",");
@@ -63,7 +63,7 @@ void sensorsInit() {
nullptr, true);
ts.add(
- SENSORS30SEC, 30000, [&](void *) {
+ SENSORS30SEC, 30000, [&](void*) {
String buf = sensorReadingMap30sec;
while (buf.length()) {
String tmp = selectToMarker(buf, ",");
@@ -74,3 +74,21 @@ void sensorsInit() {
nullptr, true);
}
+void addKey(String& key, String& keyNumberTable, int number) {
+ keyNumberTable += key + " " + String(number) + ",";
+}
+
+int getKeyNum(String& key, String& keyNumberTable) {
+ String keyNumberTableBuf = keyNumberTable;
+ //SerialPrint("","",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;
+}
diff --git a/src/Global.cpp b/src/Global.cpp
index c47fe17e..a6d8ae9e 100644
--- a/src/Global.cpp
+++ b/src/Global.cpp
@@ -33,17 +33,20 @@ String scenario = "";
//orders and events
String orderBuf = "";
String eventBuf = "";
-
String itemsFile = "";
String itemsLine = "";
+//key lists and numbers
+String impulsKeyList = "";
+int impulsEnterCounter = -1;
+
+
// Sensors
-int8_t dallasEnterCounter = -1;
String sensorReadingMap10sec;
String sensorReadingMap30sec;
// Logging
-String logging_value_names_list;
+String loggingKeyList;
int enter_to_logging_counter;
// Upgrade
diff --git a/src/Init.cpp b/src/Init.cpp
index e8cccfdb..4b75d60f 100644
--- a/src/Init.cpp
+++ b/src/Init.cpp
@@ -1,8 +1,10 @@
#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);
@@ -26,36 +28,27 @@ void all_init() {
}
void Device_init() {
+
sensorReadingMap10sec = "";
- dallasEnterCounter = -1;
+
+ //======clear dallas params======
+ if (mySensorDallas2 != nullptr) {
+ mySensorDallas2->clear();
+ }
+
+ //======clear logging params======
if (myLogging != nullptr) {
myLogging->clear();
}
- logging_value_names_list = "";
-
+ loggingKeyList = "";
+
+ //======clear impuls params=======
+ if (myImpulsOut != nullptr) {
+ myImpulsOut->clear();
+ }
+ impulsKeyList = "";
+ impulsEnterCounter = -1;
- //enter_to_logging_counter = LOG1 - 1;
- //analog_value_names_list = "";
- //enter_to_analog_counter = 0;
- //dallas_value_name = "";
- //enter_to_dallas_counter = 0;
- //levelPr_value_name = "";
- //ultrasonicCm_value_name = "";
- //dhtT_value_name = "";
- //dhtH_value_name = "";
- //bmp280T_value_name = "";
- //bmp280P_value_name = "";
- //bme280T_value_name = "";
- //bme280P_value_name = "";
- //bme280H_value_name = "";
- //bme280A_value_name = "";
- //int array_sz = sizeof(sensors_reading_map) / sizeof(sensors_reading_map[0]);
- //for (int i = 0; i < array_sz; i++) {
- // sensors_reading_map[i] = 0;
- //}
- //for (int i = LOG1; i <= LOG5; i++) {
- // ts.remove(i);
- //}
#ifdef LAYOUT_IN_RAM
all_widgets = "";
diff --git a/src/ItemsCmd.cpp b/src/ItemsCmd.cpp
index 2a949050..4876b5e3 100644
--- a/src/ItemsCmd.cpp
+++ b/src/ItemsCmd.cpp
@@ -7,6 +7,8 @@
#include "Module/Terminal.h"
#include "Servo/Servos.h"
+#include "items/SensorDallas.h"
+
Terminal *term = nullptr;
boolean but[NUM_BUTTONS];
@@ -31,7 +33,7 @@ void cmd_init() {
sCmd.addCommand("analog-adc", analogAdc);
sCmd.addCommand("ultrasonic-cm", ultrasonicCm);
- sCmd.addCommand("dallas-temp", dallasTemp);
+ sCmd.addCommand("dallas-temp", dallas);
sCmd.addCommand("dht-temp", dhtTemp);
sCmd.addCommand("dht-hum", dhtHum);
@@ -49,6 +51,8 @@ void cmd_init() {
sCmd.addCommand("logging", logging);
+ sCmd.addCommand("impuls-out", impuls);
+
handle_time_init();
}
diff --git a/src/ItemsList.cpp b/src/ItemsList.cpp
index d6803b23..d4d1cf8a 100644
--- a/src/ItemsList.cpp
+++ b/src/ItemsList.cpp
@@ -54,6 +54,17 @@ void addItem(String name) {
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));
diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp
index 6c94d73c..2210cbb3 100644
--- a/src/MqttClient.cpp
+++ b/src/MqttClient.cpp
@@ -26,11 +26,13 @@ void mqttInit() {
if (mqtt.connected()) {
SerialPrint("I", "MQTT", "OK");
setLedStatus(LED_OFF);
- } else {
+ }
+ else {
SerialPrint("E", "MQTT", "lost connection");
mqttConnect();
}
- } else {
+ }
+ else {
SerialPrint("E", "WIFI", "Lost WiFi connection");
ts.remove(WIFI_MQTT_CONNECTION_CHECK);
startAPMode();
@@ -89,7 +91,8 @@ boolean mqttConnect() {
setLedStatus(LED_OFF);
mqttSubscribe();
res = true;
- } else {
+ }
+ else {
SerialPrint("E", "MQTT", "could't connect, retry in " + String(MQTT_RECONNECT_INTERVAL / 1000) + "s");
setLedStatus(LED_FAST);
}
@@ -116,8 +119,9 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
choose_log_date_and_send();
#endif
- } else if (topicStr.indexOf("control")) {
-
+ }
+ else if (topicStr.indexOf("control")) {
+
String key = selectFromMarkerToMarker(topicStr, "/", 3);
orderBuf += key;
@@ -125,12 +129,14 @@ void mqttCallback(char* topic, uint8_t* payload, size_t length) {
orderBuf += payloadStr;
orderBuf += ",";
- } else if (topicStr.indexOf("order")) {
+ }
+ else if (topicStr.indexOf("order")) {
payloadStr.replace("_", " ");
orderBuf += payloadStr;
orderBuf += ",";
- } else if (topicStr.indexOf("update")) {
+ }
+ else if (topicStr.indexOf("update")) {
if (payloadStr == "1") {
myNotAsyncActions->make(do_UPGRADE);
}
@@ -245,38 +251,38 @@ void publishState() {
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;
+ 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;
}
}
diff --git a/src/Scenario.cpp b/src/Scenario.cpp
index 2399d178..ce0ec90d 100644
--- a/src/Scenario.cpp
+++ b/src/Scenario.cpp
@@ -8,68 +8,68 @@ boolean isScenarioEnabled() {
return jsonReadBool(configSetupJson, "scen") && eventBuf != "";
}
-void loopScenario() {
- if (!isScenarioEnabled()) {
- return;
- }
- String scenarioTmp = scenario;
- scenarioTmp += "\n";
- scenarioTmp.replace("\r\n", "\n");
- scenarioTmp.replace("\r", "\n");
-
- while (scenarioTmp.length()) {
- String scenBlok = selectToMarker(scenarioTmp, "end"); //выделяем первый сценарий
- if (!scenBlok.length()) {
- return;
- }
-
- size_t i = 0;
- i++;
- if (scenario_line_status[i] == 1) {
- String condition = selectToMarker(scenBlok, "\n"); //выделяем условие
-
- String conditionParam = selectFromMarkerToMarker(condition, " ", 0); //выделяем параметр условия
- String order = eventBuf;
- String eventParam = selectToMarker(order, ","); //выделяем параметр события
-
- if (conditionParam == eventParam) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку
-
- String conditionSign = selectFromMarkerToMarker(condition, " ", 1); //выделяем знак (=)
-
- String conditionValue = selectFromMarkerToMarker(condition, " ", 2); //выделяем значение (1)
-
- boolean flag = false;
-
- String eventParam = jsonReadStr(configLiveJson, conditionParam); //получаем значение этого параметра события из json
-
- if (conditionSign == "=") {
- flag = eventParam == conditionValue;
- } else if (conditionSign == "!=") {
- flag = eventParam != conditionValue;
- } else if (conditionSign == "<") {
- flag = eventParam.toInt() < conditionValue.toInt();
- } else if (conditionSign == ">") {
- flag = eventParam.toInt() > conditionValue.toInt();
- } else if (conditionSign == ">=") {
- flag = eventParam.toInt() >= conditionValue.toInt();
- } else if (conditionSign == "<=") {
- flag = eventParam.toInt() <= conditionValue.toInt();
- }
-
- if (flag) {
- scenBlok = deleteBeforeDelimiter(scenBlok, "\n"); // удаляем строку самого сценария оставляя только команды
- SerialPrint("I","module","do: " + scenBlok);
- spaceCmdExecute(scenBlok); // выполняем все команды
- }
- }
- }
- scenarioTmp = deleteBeforeDelimiter(scenarioTmp, "end\n"); //удаляем первый сценарий
- }
-
- String eventBufTmp = eventBuf; //читаем файл событий
- eventBufTmp = deleteBeforeDelimiter(eventBufTmp, ","); //удаляем выполненное событие
- eventBuf = eventBufTmp; //записываем обновленный файл событий
-}
+//void loopScenario() {
+// if (!isScenarioEnabled()) {
+// return;
+// }
+// String scenarioTmp = scenario;
+// scenarioTmp += "\n";
+// scenarioTmp.replace("\r\n", "\n");
+// scenarioTmp.replace("\r", "\n");
+//
+// while (scenarioTmp.length()) {
+// String scenBlok = selectToMarker(scenarioTmp, "end"); //выделяем первый сценарий
+// if (!scenBlok.length()) {
+// return;
+// }
+//
+// size_t i = 0;
+// i++;
+// if (scenario_line_status[i] == 1) {
+// String condition = selectToMarker(scenBlok, "\n"); //выделяем условие
+//
+// String conditionParam = selectFromMarkerToMarker(condition, " ", 0); //выделяем параметр условия
+// String order = eventBuf;
+// String eventParam = selectToMarker(order, ","); //выделяем параметр события
+//
+// if (conditionParam == eventParam) { //если поступившее событие равно событию заданному buttonSet1 в файле начинаем его обработку
+//
+// String conditionSign = selectFromMarkerToMarker(condition, " ", 1); //выделяем знак (=)
+//
+// String conditionValue = selectFromMarkerToMarker(condition, " ", 2); //выделяем значение (1)
+//
+// boolean flag = false;
+//
+// String eventParam = jsonReadStr(configLiveJson, conditionParam); //получаем значение этого параметра события из json
+//
+// if (conditionSign == "=") {
+// flag = eventParam == conditionValue;
+// } else if (conditionSign == "!=") {
+// flag = eventParam != conditionValue;
+// } else if (conditionSign == "<") {
+// flag = eventParam.toInt() < conditionValue.toInt();
+// } else if (conditionSign == ">") {
+// flag = eventParam.toInt() > conditionValue.toInt();
+// } else if (conditionSign == ">=") {
+// flag = eventParam.toInt() >= conditionValue.toInt();
+// } else if (conditionSign == "<=") {
+// flag = eventParam.toInt() <= conditionValue.toInt();
+// }
+//
+// if (flag) {
+// scenBlok = deleteBeforeDelimiter(scenBlok, "\n"); // удаляем строку самого сценария оставляя только команды
+// SerialPrint("I","module","do: " + scenBlok);
+// spaceCmdExecute(scenBlok); // выполняем все команды
+// }
+// }
+// }
+// scenarioTmp = deleteBeforeDelimiter(scenarioTmp, "end\n"); //удаляем первый сценарий
+// }
+//
+// String eventBufTmp = eventBuf; //читаем файл событий
+// eventBufTmp = deleteBeforeDelimiter(eventBufTmp, ","); //удаляем выполненное событие
+// eventBuf = eventBufTmp; //записываем обновленный файл событий
+//}
void eventGen(String event_name, String number) {
if (!jsonReadBool(configSetupJson, "scen")) {
@@ -78,18 +78,18 @@ void eventGen(String event_name, String number) {
eventBuf = event_name + number + ",";
}
-String add_set(String str) {
- String num1 = str.substring(str.length() - 1);
- String num2 = str.substring(str.length() - 2, str.length() - 1);
- if (isDigitStr(num1) && isDigitStr(num2)) {
- str = str.substring(0, str.length() - 2) + "Set" + num2 + num1;
- } else {
- if (isDigitStr(num1)) {
- str = str.substring(0, str.length() - 1) + "Set" + num1;
- }
- }
- return str;
-}
+//String add_set(String str) {
+// String num1 = str.substring(str.length() - 1);
+// String num2 = str.substring(str.length() - 2, str.length() - 1);
+// if (isDigitStr(num1) && isDigitStr(num2)) {
+// str = str.substring(0, str.length() - 2) + "Set" + num2 + num1;
+// } else {
+// if (isDigitStr(num1)) {
+// str = str.substring(0, str.length() - 1) + "Set" + num1;
+// }
+// }
+// return str;
+//}
//button-out1 = 1
//button-out2 1
diff --git a/src/Utils/StringUtils.cpp b/src/Utils/StringUtils.cpp
index bf6af4b1..a158fa94 100644
--- a/src/Utils/StringUtils.cpp
+++ b/src/Utils/StringUtils.cpp
@@ -75,7 +75,7 @@ uint16_t hexStringToUint16(String hex) {
}
}
-size_t itemsCount(String str, const String &separator) {
+size_t itemsCount(String str, const String& separator) {
// если строки поиск нет сразу выход
if (str.indexOf(separator) == -1) {
return 0;
@@ -91,7 +91,7 @@ size_t itemsCount(String str, const String &separator) {
return cnt;
}
-boolean isDigitStr(const String &str) {
+boolean isDigitStr(const String& str) {
for (size_t i = 0; i < str.length(); i++) {
if (!isDigit(str.charAt(i))) {
return false;
@@ -111,3 +111,5 @@ String prettyBytes(size_t size) {
return String(size / 1024.0 / 1024.0 / 1024.0) + "GB";
}
+
+
diff --git a/src/Web.cpp b/src/Web.cpp
index e1485f23..9625950b 100644
--- a/src/Web.cpp
+++ b/src/Web.cpp
@@ -1,9 +1,10 @@
#include "Web.h"
-#include "items/LoggingClass.h"
+
#include "Class/NotAsync.h"
#include "Global.h"
#include "Init.h"
#include "ItemsList.h"
+#include "items/LoggingClass.h"
bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) {
if (request->hasArg("preset")) {
@@ -22,6 +23,12 @@ void web_init() {
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);
@@ -239,6 +246,8 @@ void web_init() {
msg = F("Cервер не найден. Попробуйте повторить позже...");
} else if (lastVersion == -2) {
msg = F("Устройство не подключено к роутеру!");
+ } else if (lastVersion < FIRMWARE_VERSION) {
+ msg = F("Ошибка версии. Попробуйте повторить позже...");
}
// else if (lastVersion == "") {
diff --git a/src/items/ImpulsOutClass.cpp b/src/items/ImpulsOutClass.cpp
new file mode 100644
index 00000000..99f860d4
--- /dev/null
+++ b/src/items/ImpulsOutClass.cpp
@@ -0,0 +1,70 @@
+#include "items/ImpulsOutClass.h"
+
+#include
+#include "BufferExecute.h"
+#include "Class/LineParsing.h"
+#include "Global.h"
+#include "ItemsCmd.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());
+ }
+ }
+}
diff --git a/src/items/LoggingClass.cpp b/src/items/LoggingClass.cpp
index de9cdee3..ca34a0ce 100644
--- a/src/items/LoggingClass.cpp
+++ b/src/items/LoggingClass.cpp
@@ -54,13 +54,13 @@ MyLoggingVector* myLogging = nullptr;
void logging() {
myLineParsing.update();
- String loggingValueKey = myLineParsing.gvalue();
+ String loggingValueKey = myLineParsing.gval();
String key = myLineParsing.gkey();
String interv = myLineParsing.gint();
- String maxcnt = myLineParsing.gmaxcnt();
+ String maxcnt = myLineParsing.gcnt();
myLineParsing.clear();
- logging_value_names_list += key + ",";
+ loggingKeyList += key + ",";
static bool firstTime = true;
if (firstTime) myLogging = new MyLoggingVector();
@@ -69,7 +69,7 @@ void logging() {
}
void choose_log_date_and_send() {
- String all_line = logging_value_names_list;
+ String all_line = loggingKeyList;
while (all_line.length() != 0) {
String tmp = selectToMarker(all_line, ",");
sendLogData("logs/" + tmp + ".txt", tmp);
diff --git a/src/items/SensorDallas.cpp b/src/items/SensorDallas.cpp
new file mode 100644
index 00000000..f861dc20
--- /dev/null
+++ b/src/items/SensorDallas.cpp
@@ -0,0 +1,54 @@
+#include "items/SensorDallas.h"
+#include "Class/LineParsing.h"
+#include "Global.h"
+#include "ItemsCmd.h"
+#include
+
+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);
+ eventGen(_key, "");
+ 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));
+}
+
diff --git a/src/items/SensorDallasClass.cpp b/src/items/SensorDallasClass.cpp
deleted file mode 100644
index f0fe6dba..00000000
--- a/src/items/SensorDallasClass.cpp
+++ /dev/null
@@ -1,20 +0,0 @@
-#include "ItemsCmd.h"
-#include "items/SensorDallasClass.h"
-//#ifdef SensorDallasEnabled
-//=========================================Модуль ультрозвукового дальномера==================================================================
-//dallas-temp;id;anydata;Сенсоры;Температура;order;pin;c[1]
-//=========================================================================================================================================
-SensorDallasClass mySensorDallas;
-void dallasTemp() {
- mySensorDallas.update();
- String key = mySensorDallas.gkey();
- sCmd.addCommand(key.c_str(), dallasReading);
- mySensorDallas.SensorDallasInit();
- mySensorDallas.clear();
-}
-
-void dallasReading() {
- String key = sCmd.order();
- mySensorDallas.SensorDallasRead(key);
-}
-//#endif
\ No newline at end of file
diff --git a/src/main.cpp b/src/main.cpp
index e94d744f..fc1f3dc7 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -16,6 +16,8 @@
#include "Utils/WebUtils.h"
#include "items/ButtonInClass.h"
#include "items/LoggingClass.h"
+#include "items/ImpulsOutClass.h"
+#include "items/SensorDallas.h"
void not_async_actions();
@@ -99,11 +101,9 @@ void setup() {
just_load = false;
initialized = true; //this second POST makes the data to be processed (you don't need to connect as "keep-alive" for that to work)
-
+
}
-
-
void loop() {
if (!initialized) {
return;
@@ -129,4 +129,16 @@ void loop() {
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();
+ }
+ }
}
\ No newline at end of file