diff --git a/data_svelte/config.json b/data_svelte/config.json index 583d056b..c1d69e0c 100644 --- a/data_svelte/config.json +++ b/data_svelte/config.json @@ -9,7 +9,60 @@ "map": "1,1024,1,1024", "plus": 0, "multiply": 1, + "round": 1, "pin": 0, "int": 15 + }, + { + "type": "Reading", + "subtype": "Ds18b20", + "id": "tmp", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "Температура", + "int": 15, + "pin": 0, + "index": 0, + "addr": "" + }, + { + "type": "Reading", + "subtype": "Sht20t", + "id": "tmp2", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "Температура", + "int": 15 + }, + { + "type": "Reading", + "subtype": "Sht20h", + "id": "Hum2", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "Влажность", + "int": 15 + }, + { + "type": "Reading", + "subtype": "Dht1122t", + "id": "tmp3", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "Температура", + "int": 15, + "pin": 0, + "senstype": "dht11" + }, + { + "type": "Reading", + "subtype": "Dht1122h", + "id": "Hum3", + "widget": "anydataTmp", + "page": "Сенсоры", + "descr": "Влажность", + "int": 15, + "pin": 0, + "senstype": "dht11" } ] \ No newline at end of file diff --git a/include/classes/IoTSensor.h b/include/classes/IoTSensor.h index 40807f75..f58dd40c 100644 --- a/include/classes/IoTSensor.h +++ b/include/classes/IoTSensor.h @@ -10,6 +10,7 @@ class IoTSensor { void loop(); virtual void doByInterval(); void regEvent(String value, String consoleInfo); + void regEvent(float value, String consoleInfo); String getSubtype(); String getID(); @@ -22,4 +23,12 @@ class IoTSensor { String _subtype; String _id; unsigned long _interval; + + float _multiply; // умножаем на значение + float _plus; // увеличиваем на значение + int _map1; + int _map2; + int _map3; + int _map4; + int _round; // 1, 10, 100, 1000, 10000 }; diff --git a/include/utils/JsonUtils.h b/include/utils/JsonUtils.h index 9053ab41..c7ab1c61 100644 --- a/include/utils/JsonUtils.h +++ b/include/utils/JsonUtils.h @@ -10,6 +10,8 @@ extern String jsonWriteInt(String& json, String name, int value); extern String jsonWriteFloat(String& json, String name, float value); extern String jsonWriteBool(String& json, String name, boolean value); +extern bool jsonRead(String& json, String key, unsigned long& value); +extern bool jsonRead(String& json, String key, float& value); extern bool jsonRead(String& json, String key, String& value); extern bool jsonRead(String& json, String key, bool& value); extern bool jsonRead(String& json, String key, int& value); diff --git a/platformio.ini b/platformio.ini index c0e5c915..1cdb8748 100644 --- a/platformio.ini +++ b/platformio.ini @@ -28,6 +28,8 @@ platform = espressif8266 @2.6.3 lib_deps = ${common_env_data.lib_deps_external} milesburton/DallasTemperature@^3.9.1 + robtillaart/SHT2x@^0.1.1 + beegee-tokyo/DHT sensor library for ESPx monitor_filters = esp8266_exception_decoder upload_speed = 921600 monitor_speed = 115200 @@ -41,6 +43,8 @@ platform = espressif32 @3.3.0 lib_deps = ${common_env_data.lib_deps_external} milesburton/DallasTemperature@^3.9.1 + robtillaart/SHT2x@^0.1.1 + beegee-tokyo/DHT sensor library for ESPx monitor_filters = esp32_exception_decoder upload_speed = 921600 monitor_speed = 115200 diff --git a/src/classes/IoTSensor.cpp b/src/classes/IoTSensor.cpp index fa253b5c..3781d4ec 100644 --- a/src/classes/IoTSensor.cpp +++ b/src/classes/IoTSensor.cpp @@ -5,9 +5,22 @@ IoTSensor::IoTSensor(String parameters) { - _interval = jsonReadInt(parameters, "int") * 1000; - _subtype = jsonReadStr(parameters, "subtype"); - _id = jsonReadStr(parameters, "id"); + jsonRead(parameters, "int", _interval); + _interval = _interval * 1000; + jsonRead(parameters, "subtype", _subtype); + jsonRead(parameters, "id", _id); + jsonRead(parameters, "multiply", _multiply); + jsonRead(parameters, "plus", _plus); + jsonRead(parameters, "round", _round); + + String map; + jsonRead(parameters, "map", map); + if (map != "") { + _map1 = selectFromMarkerToMarker(map, ",", 0).toInt(); + _map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); + _map3 = selectFromMarkerToMarker(map, ",", 2).toInt(); + _map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); + } } IoTSensor::~IoTSensor() {} @@ -29,10 +42,22 @@ void IoTSensor::loop() { } void IoTSensor::regEvent(String value, String consoleInfo = "") { - eventGen2(_id, String(value)); - jsonWriteStr(paramsFlashJson, _id, String(value)); - publishStatus(_id, String(value)); - SerialPrint("I", "Sensor " + consoleInfo, "'" + _id + "' data: " + String(value) + "'"); + eventGen2(_id, value); + jsonWriteStr(paramsFlashJson, _id, value); + publishStatus(_id, value); + SerialPrint("I", "Sensor " + consoleInfo, "'" + _id + "' data: " + value + "'"); +} + +void IoTSensor::regEvent(float value, String consoleInfo = "") { + if (_multiply) value = value * _multiply; + if (_plus) value = value + _multiply; + if (_round != 0) { + if (value > 0) value = (int)(value * _round + 0.5) / _round; + if (value < 0) value = (int)(value * _round - 0.5) / _round; + } + if (_map1 != _map2) value = map(value, _map1, _map2, _map3, _map4); + + regEvent((String)value, consoleInfo); } void IoTSensor::doByInterval() {} diff --git a/src/modules/API.cpp b/src/modules/API.cpp index 0812e534..7df50ce9 100644 --- a/src/modules/API.cpp +++ b/src/modules/API.cpp @@ -3,7 +3,9 @@ //============================================================================================ //здесь скопируйте строку и вставьте ниже, заменив имя AnalogAdc на название вашего сенсора void* getAPI_AnalogAdc(String subtype, String params); -void* getAPI_ds18b20(String subtype, String params); +void* getAPI_Ds18b20(String subtype, String params); +void* getAPI_Sht20(String subtype, String params); +void* getAPI_Dht1122(String subtype, String params); //============================================================================================ void* getAPI(String subtype, String params) { @@ -11,7 +13,9 @@ void* getAPI(String subtype, String params) { //=============================================================================================================== //здесь нужно скопировать строку еще раз и вставить ее ниже, переименовав AnalogAdc на название вашего сенсора if ((tmpAPI = getAPI_AnalogAdc(subtype, params)) != nullptr) return tmpAPI; - if ((tmpAPI = getAPI_ds18b20(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Ds18b20(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Sht20(subtype, params)) != nullptr) return tmpAPI; + if ((tmpAPI = getAPI_Dht1122(subtype, params)) != nullptr) return tmpAPI; //================================================================================================================ return nullptr; diff --git a/src/modules/AnalogAdc.cpp b/src/modules/AnalogAdc.cpp index ae298f1d..2f3ecac7 100644 --- a/src/modules/AnalogAdc.cpp +++ b/src/modules/AnalogAdc.cpp @@ -34,7 +34,7 @@ class AnalogAdc : public IoTSensor { void doByInterval() { float value = analogRead(_pin); - regEvent((String)value, "AnalogAdc"); //обязательный вызов хотяб один + regEvent(value, "AnalogAdc"); //обязательный вызов хотяб один } //======================================================================================================= diff --git a/src/modules/Dht1122.cpp b/src/modules/Dht1122.cpp new file mode 100644 index 00000000..788e7da4 --- /dev/null +++ b/src/modules/Dht1122.cpp @@ -0,0 +1,80 @@ +/****************************************************************** + Used DHT Temperature & Humidity Sensor library for Arduino & ESP32. + Support for DHT11 and DHT22/AM2302/RHT03 + https://github.com/beegee-tokyo/arduino-DHTesp + ******************************************************************/ + + +#include "Global.h" +#include "Classes/IoTSensor.h" + +#include "DHTesp.h" +#include + + +std::map dhts; + +class Dht1122t : public IoTSensor { + private: + int _pin; + + public: + Dht1122t(String parameters): IoTSensor(parameters) { + jsonRead(parameters, "pin", _pin); + } + + void doByInterval() { + float value = dhts[_pin]->getTemperature(); + if (String(value) != "nan") regEvent(value, "Dht1122t"); + else SerialPrint("E", "Sensor DHTt", "Error"); + } + + ~Dht1122t(); +}; + + +class Dht1122h : public IoTSensor { + private: + int _pin; + + public: + Dht1122h(String parameters): IoTSensor(parameters) { + jsonRead(parameters, "pin", _pin); + } + + void doByInterval() { + float value = dhts[_pin]->getHumidity(); + if (String(value) != "nan") regEvent(value, "Dht1122h"); + else SerialPrint("E", "Sensor DHTh", "Error"); + } + + ~Dht1122h(); +}; + + +void* getAPI_Dht1122(String subtype, String param) { + int pin; + String senstype; + jsonRead(param, "pin", pin); + jsonRead(param, "senstype", senstype); + + if (dhts.find(pin) == dhts.end()) { + DHTesp* dht = new DHTesp(); + + if (senstype == "dht11") { + dht->setup(pin, DHTesp::DHT11); + } else if (senstype == "dht22") { + dht->setup(pin, DHTesp::DHT22); + } + + dhts[pin] = dht; + } + + if (subtype == F("Dht1122t")) { + return new Dht1122t(param); + } else if (subtype == F("Dht1122h")) { + return new Dht1122h(param); + } else { + return nullptr; + } +} diff --git a/src/modules/Sht20.cpp b/src/modules/Sht20.cpp new file mode 100644 index 00000000..6f30f78d --- /dev/null +++ b/src/modules/Sht20.cpp @@ -0,0 +1,52 @@ +#include "Global.h" +#include "Classes/IoTSensor.h" + +#include "Wire.h" +#include "SHT2x.h" + + +SHT2x* sht = nullptr; + +class Sht20t : public IoTSensor { + public: + Sht20t(String parameters): IoTSensor(parameters) { } + + void doByInterval() { + sht->read(); + float value = sht->getTemperature(); + if (value > -46.85F) regEvent(value, "Sht20t"); + else SerialPrint("E", "Sensor Sht20t", "Error"); + } + + ~Sht20t(); +}; + +class Sht20h : public IoTSensor { + public: + Sht20h(String parameters): IoTSensor(parameters) { } + + void doByInterval() { + sht->read(); + float value = sht->getHumidity(); + if (value != -6) regEvent(value, "Sht20h"); + else SerialPrint("E", "Sensor Sht20h", "Error"); + } + + ~Sht20h(); +}; + + +void* getAPI_Sht20(String subtype, String param) { + if (!sht) { + sht = new SHT2x; + if (sht) sht->begin(); + } + + if (subtype == F("Sht20t")) { + return new Sht20t(param); + } else if (subtype == F("Sht20h")) { + return new Sht20h(param); + } else { + return nullptr; + } +} diff --git a/src/modules/ds18b20.cpp b/src/modules/ds18b20.cpp index c227dc2c..9cbd6109 100644 --- a/src/modules/ds18b20.cpp +++ b/src/modules/ds18b20.cpp @@ -9,7 +9,7 @@ std::map oneWireTemperatureArray; std::map sensorsTemperatureArray; -class ds18b20 : public IoTSensor { +class Ds18b20 : public IoTSensor { private: //для работы библиотеки с несколькими линиями необходимо обеспечить каждый экземпляр класса ссылками на объекты настроенные на эти линии OneWire* oneWire; @@ -17,8 +17,8 @@ class ds18b20 : public IoTSensor { //описание параметров передаваемых из настроек датчика из веба String _addr; - unsigned int _pin; - unsigned int _index; + int _pin; + int _index; public: //======================================================================================================= @@ -27,11 +27,10 @@ class ds18b20 : public IoTSensor { //Такие как ...begin и подставлять в них параметры полученные из web интерфейса. //Все параметры хранятся в перемененной parameters, вы можете прочитать любой параметр используя jsonRead функции: // jsonReadStr, jsonReadBool, jsonReadInt - ds18b20(String parameters): IoTSensor(parameters) { - - _pin = jsonReadInt(parameters, "pin"); - _index = jsonReadInt(parameters, "index"); - _addr = jsonReadStr(parameters, "addr"); + Ds18b20(String parameters): IoTSensor(parameters) { + jsonRead(parameters, "pin", _pin); + jsonRead(parameters, "index", _index); + jsonRead(parameters, "addr", _addr); //учитываем, что библиотека может работать с несколькими линиями на разных пинах, поэтому инициируем библиотеку, если линия ранее не использовалась if (oneWireTemperatureArray.find(_pin) == oneWireTemperatureArray.end()) { @@ -75,19 +74,20 @@ class ds18b20 : public IoTSensor { char addrStr[20] = ""; hex2string(deviceAddress, 8, addrStr); - regEvent((String)value, "addr: " + String(addrStr)); //обязательный вызов для отправки результата работы + if (value != -127) regEvent(value, "addr: " + String(addrStr)); //обязательный вызов для отправки результата работы + else SerialPrint("E", "Sensor Ds18b20", "Error"); } //======================================================================================================= - ~ds18b20(){}; + ~Ds18b20(){}; }; //после замены названия сенсора, на функцию можно не обращать внимания //если сенсор предполагает использование общего объекта библиотеки для нескольких экземпляров сенсора, то в данной функции необходимо предусмотреть -//создание и контроль соответствующих глобальных переменных (см. пример реализации сенсора ds18b20) -void* getAPI_ds18b20(String subtype, String param) { - if (subtype == F("ds18b20")) { - return new ds18b20(param); +//создание и контроль соответствующих глобальных переменных +void* getAPI_Ds18b20(String subtype, String param) { + if (subtype == F("Ds18b20")) { + return new Ds18b20(param); } else { return nullptr; } diff --git a/src/utils/JsonUtils.cpp b/src/utils/JsonUtils.cpp index 7c42034a..a02df298 100644 --- a/src/utils/JsonUtils.cpp +++ b/src/utils/JsonUtils.cpp @@ -12,6 +12,36 @@ void jsonWriteStrDoc(DynamicJsonDocument& doc, String name, String value) { } // new============================================================================== +bool jsonRead(String& json, String key, unsigned long& value) { + bool ret = true; + DynamicJsonDocument doc(JSON_BUFFER_SIZE); + DeserializationError error = deserializeJson(doc, json); + if (error) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + ret = false; + } else if (!doc.containsKey(key)) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + ret = false; + } + value = doc[key].as(); + return ret; +} + +bool jsonRead(String& json, String key, float& value) { + bool ret = true; + DynamicJsonDocument doc(JSON_BUFFER_SIZE); + DeserializationError error = deserializeJson(doc, json); + if (error) { + SerialPrint("EE", F("jsonRead"), error.f_str()); + ret = false; + } else if (!doc.containsKey(key)) { + SerialPrint("EE", F("jsonRead"), key + " missing"); + ret = false; + } + value = doc[key].as(); + return ret; +} + bool jsonRead(String& json, String key, String& value) { bool ret = true; DynamicJsonDocument doc(JSON_BUFFER_SIZE);