From ac18805ff40282cc6c63ce0723659aa6d593b60b Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 1 Aug 2020 13:47:02 +0300 Subject: [PATCH] First commit --- ESP12SmallRoom/.gitignore | 5 + ESP12SmallRoom/.travis.yml | 67 +++ ESP12SmallRoom/.vscode/extensions.json | 7 + ESP12SmallRoom/include/README | 39 ++ ESP12SmallRoom/include/leds.h | 19 + ESP12SmallRoom/lib/README | 46 ++ ESP12SmallRoom/platformio.ini | 18 + ESP12SmallRoom/src/leds.cpp | 24 + ESP12SmallRoom/src/main.cpp | 175 ++++++ ESP12SmallRoom/test/README | 11 + ESP_BigRoom/.gitignore | 5 + ESP_BigRoom/.travis.yml | 67 +++ ESP_BigRoom/.vscode/extensions.json | 7 + ESP_BigRoom/include/README | 39 ++ ESP_BigRoom/include/amqtt.h | 30 + ESP_BigRoom/include/leds.h | 19 + ESP_BigRoom/include/main.h | 18 + ESP_BigRoom/lib/README | 46 ++ ESP_BigRoom/platformio.ini | 19 + ESP_BigRoom/src/amqtt.cpp | 72 +++ ESP_BigRoom/src/leds.cpp | 24 + ESP_BigRoom/src/main.cpp | 266 +++++++++ ESP_BigRoom/test/README | 11 + ESP_Electro/.gitignore | 5 + ESP_Electro/.travis.yml | 67 +++ ESP_Electro/.vscode/extensions.json | 7 + ESP_Electro/include/README | 39 ++ ESP_Electro/lib/README | 46 ++ ESP_Electro/platformio.ini | 18 + ESP_Electro/src/main.cpp | 208 +++++++ ESP_Electro/test/README | 11 + ESP_Kor/.gitignore | 5 + ESP_Kor/.travis.yml | 67 +++ ESP_Kor/.vscode/extensions.json | 7 + ESP_Kor/include/README | 39 ++ ESP_Kor/lib/README | 46 ++ ESP_Kor/platformio.ini | 17 + ESP_Kor/src/main.cpp | 194 ++++++ ESP_Kor/test/README | 11 + ESP_MidRoom/.gitignore | 5 + ESP_MidRoom/.travis.yml | 67 +++ ESP_MidRoom/.vscode/extensions.json | 7 + ESP_MidRoom/include/README | 39 ++ ESP_MidRoom/include/amqtt.h | 30 + ESP_MidRoom/include/leds.h | 19 + ESP_MidRoom/include/main.h | 19 + ESP_MidRoom/lib/README | 46 ++ ESP_MidRoom/platformio.ini | 19 + ESP_MidRoom/src/amqtt.cpp | 72 +++ ESP_MidRoom/src/leds.cpp | 32 + ESP_MidRoom/src/main.cpp | 337 +++++++++++ ESP_MidRoom/test/README | 11 + GateWay/.gitignore | 5 + GateWay/.travis.yml | 67 +++ GateWay/.vscode/extensions.json | 7 + GateWay/include/README | 39 ++ GateWay/include/mys.h | 5 + GateWay/lib/README | 46 ++ GateWay/platformio.ini | 17 + GateWay/src/main.cpp | 141 +++++ GateWay/test/README | 11 + I2C Scan/.gitignore | 5 + I2C Scan/.travis.yml | 67 +++ I2C Scan/.vscode/extensions.json | 7 + I2C Scan/include/README | 39 ++ I2C Scan/lib/README | 46 ++ I2C Scan/platformio.ini | 24 + I2C Scan/src/main.cpp | 54 ++ I2C Scan/test/README | 11 + KuhLight_ESP/.gitignore | 5 + KuhLight_ESP/.travis.yml | 67 +++ KuhLight_ESP/.vscode/extensions.json | 7 + KuhLight_ESP/include/README | 39 ++ KuhLight_ESP/lib/README | 46 ++ KuhLight_ESP/platformio.ini | 18 + KuhLight_ESP/src/main.cpp | 191 ++++++ KuhLight_ESP/test/README | 11 + MYS_Home.code-workspace | 70 +++ MainDoor/.gitignore | 5 + MainDoor/.travis.yml | 67 +++ MainDoor/.vscode/extensions.json | 7 + MainDoor/include/README | 39 ++ MainDoor/include/leds.h | 19 + MainDoor/lib/README | 46 ++ MainDoor/platformio.ini | 19 + MainDoor/src/leds.cpp | 24 + MainDoor/src/main.cpp | 342 +++++++++++ MainDoor/test/README | 11 + Sw_BigRoom/.gitignore | 5 + Sw_BigRoom/.travis.yml | 67 +++ Sw_BigRoom/.vscode/extensions.json | 7 + Sw_BigRoom/include/README | 39 ++ Sw_BigRoom/lib/README | 46 ++ Sw_BigRoom/platformio.ini | 17 + Sw_BigRoom/src/main.cpp | 395 +++++++++++++ Sw_BigRoom/test/README | 11 + Sw_Koridor/.gitignore | 5 + Sw_Koridor/.travis.yml | 67 +++ Sw_Koridor/.vscode/extensions.json | 7 + Sw_Koridor/include/README | 39 ++ Sw_Koridor/lib/README | 46 ++ Sw_Koridor/platformio.ini | 19 + Sw_Koridor/src/main.cpp | 208 +++++++ Sw_Koridor/test/README | 11 + Sw_MidlRoom/.gitignore | 5 + Sw_MidlRoom/.travis.yml | 67 +++ Sw_MidlRoom/.vscode/extensions.json | 7 + Sw_MidlRoom/include/README | 39 ++ Sw_MidlRoom/lib/README | 46 ++ Sw_MidlRoom/platformio.ini | 17 + Sw_MidlRoom/src/main.cpp | 393 +++++++++++++ Sw_MidlRoom/test/README | 11 + Sw_SmallRoom/.gitignore | 5 + Sw_SmallRoom/.travis.yml | 67 +++ Sw_SmallRoom/.vscode/extensions.json | 7 + Sw_SmallRoom/include/README | 39 ++ Sw_SmallRoom/lib/README | 46 ++ Sw_SmallRoom/platformio.ini | 19 + Sw_SmallRoom/src/main.cpp | 223 +++++++ Sw_SmallRoom/test/README | 11 + VT_ESP8266/.gitignore | 5 + VT_ESP8266/.travis.yml | 67 +++ VT_ESP8266/.vscode/extensions.json | 7 + VT_ESP8266/include/README | 39 ++ VT_ESP8266/include/leds.h | 21 + VT_ESP8266/include/main.h | 119 ++++ VT_ESP8266/include/pcf_butt.h | 18 + VT_ESP8266/lib/README | 46 ++ VT_ESP8266/platformio.ini | 17 + VT_ESP8266/src/leds.cpp | 27 + VT_ESP8266/src/main.cpp | 743 +++++++++++++++++++++++ VT_ESP8266/src/pcf_butt.cpp | 49 ++ VT_ESP8266/test/README | 11 + esp8266-KUH/.gitignore | 5 + esp8266-KUH/.travis.yml | 67 +++ esp8266-KUH/.vscode/extensions.json | 7 + esp8266-KUH/include/README | 39 ++ esp8266-KUH/include/main.h | 45 ++ esp8266-KUH/lib/README | 46 ++ esp8266-KUH/platformio.ini | 17 + esp8266-KUH/src/main.cpp | 780 +++++++++++++++++++++++++ esp8266-KUH/test/README | 11 + 142 files changed, 8325 insertions(+) create mode 100644 ESP12SmallRoom/.gitignore create mode 100644 ESP12SmallRoom/.travis.yml create mode 100644 ESP12SmallRoom/.vscode/extensions.json create mode 100644 ESP12SmallRoom/include/README create mode 100644 ESP12SmallRoom/include/leds.h create mode 100644 ESP12SmallRoom/lib/README create mode 100644 ESP12SmallRoom/platformio.ini create mode 100644 ESP12SmallRoom/src/leds.cpp create mode 100644 ESP12SmallRoom/src/main.cpp create mode 100644 ESP12SmallRoom/test/README create mode 100644 ESP_BigRoom/.gitignore create mode 100644 ESP_BigRoom/.travis.yml create mode 100644 ESP_BigRoom/.vscode/extensions.json create mode 100644 ESP_BigRoom/include/README create mode 100644 ESP_BigRoom/include/amqtt.h create mode 100644 ESP_BigRoom/include/leds.h create mode 100644 ESP_BigRoom/include/main.h create mode 100644 ESP_BigRoom/lib/README create mode 100644 ESP_BigRoom/platformio.ini create mode 100644 ESP_BigRoom/src/amqtt.cpp create mode 100644 ESP_BigRoom/src/leds.cpp create mode 100644 ESP_BigRoom/src/main.cpp create mode 100644 ESP_BigRoom/test/README create mode 100644 ESP_Electro/.gitignore create mode 100644 ESP_Electro/.travis.yml create mode 100644 ESP_Electro/.vscode/extensions.json create mode 100644 ESP_Electro/include/README create mode 100644 ESP_Electro/lib/README create mode 100644 ESP_Electro/platformio.ini create mode 100644 ESP_Electro/src/main.cpp create mode 100644 ESP_Electro/test/README create mode 100644 ESP_Kor/.gitignore create mode 100644 ESP_Kor/.travis.yml create mode 100644 ESP_Kor/.vscode/extensions.json create mode 100644 ESP_Kor/include/README create mode 100644 ESP_Kor/lib/README create mode 100644 ESP_Kor/platformio.ini create mode 100644 ESP_Kor/src/main.cpp create mode 100644 ESP_Kor/test/README create mode 100644 ESP_MidRoom/.gitignore create mode 100644 ESP_MidRoom/.travis.yml create mode 100644 ESP_MidRoom/.vscode/extensions.json create mode 100644 ESP_MidRoom/include/README create mode 100644 ESP_MidRoom/include/amqtt.h create mode 100644 ESP_MidRoom/include/leds.h create mode 100644 ESP_MidRoom/include/main.h create mode 100644 ESP_MidRoom/lib/README create mode 100644 ESP_MidRoom/platformio.ini create mode 100644 ESP_MidRoom/src/amqtt.cpp create mode 100644 ESP_MidRoom/src/leds.cpp create mode 100644 ESP_MidRoom/src/main.cpp create mode 100644 ESP_MidRoom/test/README create mode 100644 GateWay/.gitignore create mode 100644 GateWay/.travis.yml create mode 100644 GateWay/.vscode/extensions.json create mode 100644 GateWay/include/README create mode 100644 GateWay/include/mys.h create mode 100644 GateWay/lib/README create mode 100644 GateWay/platformio.ini create mode 100644 GateWay/src/main.cpp create mode 100644 GateWay/test/README create mode 100644 I2C Scan/.gitignore create mode 100644 I2C Scan/.travis.yml create mode 100644 I2C Scan/.vscode/extensions.json create mode 100644 I2C Scan/include/README create mode 100644 I2C Scan/lib/README create mode 100644 I2C Scan/platformio.ini create mode 100644 I2C Scan/src/main.cpp create mode 100644 I2C Scan/test/README create mode 100644 KuhLight_ESP/.gitignore create mode 100644 KuhLight_ESP/.travis.yml create mode 100644 KuhLight_ESP/.vscode/extensions.json create mode 100644 KuhLight_ESP/include/README create mode 100644 KuhLight_ESP/lib/README create mode 100644 KuhLight_ESP/platformio.ini create mode 100644 KuhLight_ESP/src/main.cpp create mode 100644 KuhLight_ESP/test/README create mode 100644 MYS_Home.code-workspace create mode 100644 MainDoor/.gitignore create mode 100644 MainDoor/.travis.yml create mode 100644 MainDoor/.vscode/extensions.json create mode 100644 MainDoor/include/README create mode 100644 MainDoor/include/leds.h create mode 100644 MainDoor/lib/README create mode 100644 MainDoor/platformio.ini create mode 100644 MainDoor/src/leds.cpp create mode 100644 MainDoor/src/main.cpp create mode 100644 MainDoor/test/README create mode 100644 Sw_BigRoom/.gitignore create mode 100644 Sw_BigRoom/.travis.yml create mode 100644 Sw_BigRoom/.vscode/extensions.json create mode 100644 Sw_BigRoom/include/README create mode 100644 Sw_BigRoom/lib/README create mode 100644 Sw_BigRoom/platformio.ini create mode 100644 Sw_BigRoom/src/main.cpp create mode 100644 Sw_BigRoom/test/README create mode 100644 Sw_Koridor/.gitignore create mode 100644 Sw_Koridor/.travis.yml create mode 100644 Sw_Koridor/.vscode/extensions.json create mode 100644 Sw_Koridor/include/README create mode 100644 Sw_Koridor/lib/README create mode 100644 Sw_Koridor/platformio.ini create mode 100644 Sw_Koridor/src/main.cpp create mode 100644 Sw_Koridor/test/README create mode 100644 Sw_MidlRoom/.gitignore create mode 100644 Sw_MidlRoom/.travis.yml create mode 100644 Sw_MidlRoom/.vscode/extensions.json create mode 100644 Sw_MidlRoom/include/README create mode 100644 Sw_MidlRoom/lib/README create mode 100644 Sw_MidlRoom/platformio.ini create mode 100644 Sw_MidlRoom/src/main.cpp create mode 100644 Sw_MidlRoom/test/README create mode 100644 Sw_SmallRoom/.gitignore create mode 100644 Sw_SmallRoom/.travis.yml create mode 100644 Sw_SmallRoom/.vscode/extensions.json create mode 100644 Sw_SmallRoom/include/README create mode 100644 Sw_SmallRoom/lib/README create mode 100644 Sw_SmallRoom/platformio.ini create mode 100644 Sw_SmallRoom/src/main.cpp create mode 100644 Sw_SmallRoom/test/README create mode 100644 VT_ESP8266/.gitignore create mode 100644 VT_ESP8266/.travis.yml create mode 100644 VT_ESP8266/.vscode/extensions.json create mode 100644 VT_ESP8266/include/README create mode 100644 VT_ESP8266/include/leds.h create mode 100644 VT_ESP8266/include/main.h create mode 100644 VT_ESP8266/include/pcf_butt.h create mode 100644 VT_ESP8266/lib/README create mode 100644 VT_ESP8266/platformio.ini create mode 100644 VT_ESP8266/src/leds.cpp create mode 100644 VT_ESP8266/src/main.cpp create mode 100644 VT_ESP8266/src/pcf_butt.cpp create mode 100644 VT_ESP8266/test/README create mode 100644 esp8266-KUH/.gitignore create mode 100644 esp8266-KUH/.travis.yml create mode 100644 esp8266-KUH/.vscode/extensions.json create mode 100644 esp8266-KUH/include/README create mode 100644 esp8266-KUH/include/main.h create mode 100644 esp8266-KUH/lib/README create mode 100644 esp8266-KUH/platformio.ini create mode 100644 esp8266-KUH/src/main.cpp create mode 100644 esp8266-KUH/test/README diff --git a/ESP12SmallRoom/.gitignore b/ESP12SmallRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP12SmallRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP12SmallRoom/.travis.yml b/ESP12SmallRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/ESP12SmallRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/ESP12SmallRoom/.vscode/extensions.json b/ESP12SmallRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/ESP12SmallRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/ESP12SmallRoom/include/README b/ESP12SmallRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/ESP12SmallRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/ESP12SmallRoom/include/leds.h b/ESP12SmallRoom/include/leds.h new file mode 100644 index 0000000..7981c48 --- /dev/null +++ b/ESP12SmallRoom/include/leds.h @@ -0,0 +1,19 @@ +#ifndef __LEDS_H__ +#define __LEDS_H__ +#include + +class leds +{ +private: + int ledPin; + bool inv, state; + int onMS; + unsigned long curMS; +public: + leds(int ledPin, int onms = 300, bool inverse = false); + //~leds(); + void start(); + void tick(); +}; + +#endif \ No newline at end of file diff --git a/ESP12SmallRoom/lib/README b/ESP12SmallRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/ESP12SmallRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP12SmallRoom/platformio.ini b/ESP12SmallRoom/platformio.ini new file mode 100644 index 0000000..851892e --- /dev/null +++ b/ESP12SmallRoom/platformio.ini @@ -0,0 +1,18 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp12e] +platform = espressif8266 +board = esp12e +framework = arduino +board_build.ldscript = eagle.flash.1m.ld +board_build.f_cpu = 26000000L +upload_protocol = espota +upload_port = 192.168.1.7 diff --git a/ESP12SmallRoom/src/leds.cpp b/ESP12SmallRoom/src/leds.cpp new file mode 100644 index 0000000..bb3739b --- /dev/null +++ b/ESP12SmallRoom/src/leds.cpp @@ -0,0 +1,24 @@ +#include + +leds::leds(int pinLED, int onms, bool inverse) +{ + ledPin = pinLED; + inv = inverse; + onMS = onms; + state = false; +} + +void leds::start() +{ + curMS = millis(); + state = true; + digitalWrite(ledPin, !inv); +} + +void leds::tick() +{ + if(state && ((curMS + onMS) < millis())){ + state = false; + digitalWrite(ledPin, inv); + } +} diff --git a/ESP12SmallRoom/src/main.cpp b/ESP12SmallRoom/src/main.cpp new file mode 100644 index 0000000..42987ea --- /dev/null +++ b/ESP12SmallRoom/src/main.cpp @@ -0,0 +1,175 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LED_BLUE D5 //GPIO14 +#define LED_GREEN D6 //GPIO12 +#define LED_RED D7 //GPIO13 +#define PWR_SENS D8 //GPIO13 + +Adafruit_HTU21DF htu = Adafruit_HTU21DF(); +WiFiClient espClient; +PubSubClient client(espClient); +leds lGreen(LED_GREEN, 200); +leds lRed(LED_RED, 200); +leds lBlue(LED_BLUE, 200); + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +float temp, rel_hum; +bool izm = false; +unsigned long cRun; +int minCnt = 0; +int measCnt = 1; + +void reconnect(); +void publishMin(); +void publishSec(); + +void setup() { + Serial.begin(9600); + pinMode(LED_BUILTIN, OUTPUT); + WiFi.mode(WIFI_STA); + WiFi.setOutputPower(20.5f); + WiFi.hostname("ESP-SmallRoom"); + WiFi.begin(ssid, password); + while (WiFi.waitForConnectResult() != WL_CONNECTED) { + //Serial.println("Connection Failed! Rebooting..."); + // "Соединиться не удалось! Перезагрузка..." + delay(5000); + ESP.restart(); + } + digitalWrite(LED_BUILTIN, !WiFi.isConnected()); + ArduinoOTA.onStart([]() { /*Serial.println("Start");*/}); // "Начало OTA-апдейта" + ArduinoOTA.onEnd([]() { /*Serial.println("\nEnd");*/}); // "Завершение OTA-апдейта" + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { /*Serial.printf("Progress: %u%%\r", (progress / (total / 100)));*/ }); + ArduinoOTA.onError([](ota_error_t error) { + /*Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial.println("End Failed"); // "Ошибка при завершении OTA-апдейта"*/ + }); + ArduinoOTA.begin(); + pinMode(LED_GREEN, OUTPUT); + pinMode(LED_BLUE, OUTPUT); + pinMode(LED_RED, OUTPUT); + pinMode(PWR_SENS, OUTPUT); + digitalWrite(LED_GREEN, LOW); + digitalWrite(LED_BLUE, LOW); + digitalWrite(LED_RED, LOW); + // Serial.begin(115200); + Serial.println("HTU21D-F"); + digitalWrite(PWR_SENS, HIGH); + delay(200); + if (!htu.begin()) { + Serial.println("Couldn't find sensor!"); + while (1); + } + temp = htu.readTemperature(); + rel_hum = htu.readHumidity(); + //digitalWrite(PWR_SENS, LOW); + client.setServer(mqtt_server, 1883); + cRun = millis(); +} + +void loop() { + ArduinoOTA.handle(); + lGreen.tick(); + lRed.tick(); + lBlue.tick(); + + if (!client.connected()) { + reconnect(); + } + client.loop(); + + if(cRun + 999 < millis()){ + cRun = millis(); + if(measCnt == 0){ + temp += (htu.readTemperature() - temp) / 6.0f; + rel_hum += (htu.readHumidity() - rel_hum) / 6.0f; + digitalWrite(PWR_SENS, LOW); + } + if(++measCnt == 9){ + digitalWrite(PWR_SENS, HIGH); + measCnt = 0; + } + //Serial.print("T: ");Serial.print(temp);Serial.print("\tH: ");Serial.println(rel_hum); + if(++minCnt == 59){ + publishMin(); + minCnt = 0; + } + if(minCnt % 10 == 0) publishSec(); + } +} + +void reconnect() { + lRed.start(); + //digitalWrite(LED_RED, HIGH); + //Serial.print("Attempting MQTT connection..."); + // "Попытка подключиться к MQTT-брокеру... " + // Пытаемся подключиться: + if (client.connect("ESPSmallRoom")) { + //Serial.println("connected"); // "подключен" + // подписываемся или переподписываемся на топик; + // можно подписаться не только на один, а на несколько топиков + } else { + //Serial.print("failed, rc="); // "подключение не удалось" + //Serial.print(client.state()); + //Serial.println(" try again in 5 seconds"); + } + //delay(100); + //digitalWrite(LED_RED, LOW); +} + +void publishMin() +{ + char strFVal[11]; + if (client.connected()) { + lGreen.start(); + //digitalWrite(LED_BLUE, HIGH); + if(!isnan(temp)){ + dtostrf(temp, 6, 1, strFVal); + client.publish("/home/smallroom/temp", strFVal); + } + if(!isnan(rel_hum)){ + dtostrf(rel_hum, 6, 1, strFVal); + client.publish("/home/smallroom/rel_hum", strFVal); + } + itoa(cRun, strFVal, 10); + client.publish("/home/smallroom/millis", strFVal); + //digitalWrite(LED_BLUE, LOW); + } +} + +void publishSec() +{ + char strFVal[11]; + if (client.connected()) { + lBlue.start(); + //digitalWrite(LED_GREEN, HIGH); + if(!isnan(temp)){ + dtostrf(temp, 7, 3, strFVal); + client.publish("/hometest/smallroom/temp", strFVal); + } + if(!isnan(rel_hum)){ + dtostrf(rel_hum, 7, 3, strFVal); + client.publish("/hometest/smallroom/rel_hum", strFVal); + } + itoa(WiFi.RSSI(), strFVal, 10); + client.publish("/hometest/smallroom/RSSI", strFVal); + itoa(cRun, strFVal, 10); + client.publish("/hometest/smallroom/millis", strFVal); + //digitalWrite(LED_GREEN, LOW); + } +} diff --git a/ESP12SmallRoom/test/README b/ESP12SmallRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/ESP12SmallRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/ESP_BigRoom/.gitignore b/ESP_BigRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP_BigRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP_BigRoom/.travis.yml b/ESP_BigRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/ESP_BigRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/ESP_BigRoom/.vscode/extensions.json b/ESP_BigRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/ESP_BigRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/ESP_BigRoom/include/README b/ESP_BigRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/ESP_BigRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/ESP_BigRoom/include/amqtt.h b/ESP_BigRoom/include/amqtt.h new file mode 100644 index 0000000..cb60798 --- /dev/null +++ b/ESP_BigRoom/include/amqtt.h @@ -0,0 +1,30 @@ +// #ifndef __AMQTT__ +// #define __AMQTT__ +// //#include +// #include +// #include +// #include +// #include + +// const char* ssid = "wf-home"; +// const char* password = "0ndthnrf"; +// const char* mqtt_server = "192.168.1.250"; + +// AsyncMqttClient mqttClient; +// Ticker mqttReconnectTimer; + +// WiFiEventHandler wifiConnectHandler; +// WiFiEventHandler wifiDisconnectHandler; +// Ticker wifiReconnectTimer; + +// void connectToWifi(); +// void connectToMqtt(); +// void onWifiConnect(const WiFiEventStationModeGotIP& event); +// void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +// void onMqttConnect(bool sessionPresent); +// void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +// void onMqttSubscribe(uint16_t packetId, uint8_t qos); +// void onMqttUnsubscribe(uint16_t packetId); +// void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +// void onMqttPublish(uint16_t packetId); +// #endif diff --git a/ESP_BigRoom/include/leds.h b/ESP_BigRoom/include/leds.h new file mode 100644 index 0000000..7981c48 --- /dev/null +++ b/ESP_BigRoom/include/leds.h @@ -0,0 +1,19 @@ +#ifndef __LEDS_H__ +#define __LEDS_H__ +#include + +class leds +{ +private: + int ledPin; + bool inv, state; + int onMS; + unsigned long curMS; +public: + leds(int ledPin, int onms = 300, bool inverse = false); + //~leds(); + void start(); + void tick(); +}; + +#endif \ No newline at end of file diff --git a/ESP_BigRoom/include/main.h b/ESP_BigRoom/include/main.h new file mode 100644 index 0000000..8c72b44 --- /dev/null +++ b/ESP_BigRoom/include/main.h @@ -0,0 +1,18 @@ +// #ifndef __MAIN__ +// #define __MAIN__ + +// #include +// #include +// #include +// #include +// #include "Adafruit_HTU21DF.h" + +// #define R_LED GPIO0 +// #define G_LED GPIO2 +// #define B_LED GPIO14 + +// bool meas = false; +// short minCnt; + + +// #endif // __MAIN__ diff --git a/ESP_BigRoom/lib/README b/ESP_BigRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/ESP_BigRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP_BigRoom/platformio.ini b/ESP_BigRoom/platformio.ini new file mode 100644 index 0000000..4b48d8e --- /dev/null +++ b/ESP_BigRoom/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = esp12e +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m.ld +;board_build.flash_mode = dout +upload_protocol = espota +upload_port = 192.168.1.131 \ No newline at end of file diff --git a/ESP_BigRoom/src/amqtt.cpp b/ESP_BigRoom/src/amqtt.cpp new file mode 100644 index 0000000..9218dad --- /dev/null +++ b/ESP_BigRoom/src/amqtt.cpp @@ -0,0 +1,72 @@ +// #include + +// void connectToWifi() { +// Serial.println("Connecting to Wi-Fi..."); +// WiFi.begin(ssid, password); +// } + +// void connectToMqtt() { +// Serial.println("Connecting to MQTT..."); +// //mqttClient.connect(); +// } + +// void onWifiConnect(const WiFiEventStationModeGotIP& event) { +// Serial.println("Connected to Wi-Fi."); +// Serial.print("IP: "); +// Serial.println(WiFi.localIP()); +// connectToMqtt(); +// } + +// void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { +// Serial.println("Disconnected from Wi-Fi."); +// mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi +// wifiReconnectTimer.once(2, connectToWifi); +// } + +// void onMqttConnect(bool sessionPresent) { +// Serial.println("Connected to MQTT."); +// Serial.print("Session present: "); +// Serial.println(sessionPresent); +// //uint16_t packetIdSub = +// // Serial.print("Subscribing Lamp1, packetId: "); +// // Serial.println(packetIdSub); +// //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); +// //Serial.print("Subscribing Lamp2, packetId: "); +// //Serial.println(packetIdSub); +// //Serial.println("Publishing at Lamp 1"); +// //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); +// //Serial.println("Publishing at Lamp 2"); +// } + +// void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { +// Serial.println("Disconnected from MQTT."); + +// if (WiFi.isConnected()) { +// mqttReconnectTimer.once(2, connectToMqtt); +// } +// } + +// void onMqttSubscribe(uint16_t packetId, uint8_t qos) { +// // Serial.println("Subscribe acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// // Serial.print(" qos: "); +// // Serial.println(qos); +// } + +// void onMqttUnsubscribe(uint16_t packetId) { +// // Serial.println("Unsubscribe acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// } + +// void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { +// if(strcmp(topic, "/home/kor/lamp1_set") == 0){ +// } +// } + +// void onMqttPublish(uint16_t packetId) { +// // Serial.println("Publish acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// } diff --git a/ESP_BigRoom/src/leds.cpp b/ESP_BigRoom/src/leds.cpp new file mode 100644 index 0000000..bb3739b --- /dev/null +++ b/ESP_BigRoom/src/leds.cpp @@ -0,0 +1,24 @@ +#include + +leds::leds(int pinLED, int onms, bool inverse) +{ + ledPin = pinLED; + inv = inverse; + onMS = onms; + state = false; +} + +void leds::start() +{ + curMS = millis(); + state = true; + digitalWrite(ledPin, !inv); +} + +void leds::tick() +{ + if(state && ((curMS + onMS) < millis())){ + state = false; + digitalWrite(ledPin, inv); + } +} diff --git a/ESP_BigRoom/src/main.cpp b/ESP_BigRoom/src/main.cpp new file mode 100644 index 0000000..e5efaf4 --- /dev/null +++ b/ESP_BigRoom/src/main.cpp @@ -0,0 +1,266 @@ +#include +#include +#include +#include +#include + +#include "Adafruit_HTU21DF.h" + +#define R_LED (0) +#define G_LED (2) +#define B_LED (14) +#define P_SENS (12) +#define MOV_SENS (13) + +bool meas = false; +short minCnt; +bool send_move = false; +int old_mov = 0; +int adc = 0; +int lastADC = 0; +Adafruit_HTU21DF htu = Adafruit_HTU21DF(); + +unsigned long cRun; +float temp, rel_hum; +// bool dir = true; +// int dc = 0; + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttSubscribe(uint16_t packetId, uint8_t qos); +void onMqttUnsubscribe(uint16_t packetId); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +void onMqttPublish(uint16_t packetId); + +leds b_led(B_LED); +leds g_led(G_LED); +leds r_led(R_LED); + +void setup() { + Serial.begin(9600); + Serial.println("Booting"); // "Загрузка" + WiFi.mode(WIFI_STA); + WiFi.hostname("BigRoom"); + ArduinoOTA.onStart([]() { + // Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + // Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // Serial.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + pinMode(MOV_SENS, INPUT_PULLUP); + pinMode(P_SENS, OUTPUT); + pinMode(R_LED, OUTPUT); + pinMode(G_LED, OUTPUT); + pinMode(B_LED, OUTPUT); + + digitalWrite(P_SENS, HIGH); + delay(200); + Serial.println("Begin HTU"); + if (!htu.begin()) { + while (1); + } + Serial.println("HTU Ok"); + temp = htu.readTemperature(); + rel_hum = htu.readHumidity(); + Serial.print("Temp: "); Serial.print(temp); Serial.print(" C"); + Serial.print("\t\t"); + Serial.print("Humidity: "); Serial.print(rel_hum); Serial.println(" \%"); + digitalWrite(R_LED, HIGH); + digitalWrite(P_SENS, LOW); + + connectToWifi(); + + cRun = millis(); +} + +void loop() { + char v[11]; + ArduinoOTA.handle(); + g_led.tick(); + if (digitalRead(MOV_SENS) != old_mov){ + old_mov = digitalRead(MOV_SENS); + Serial.println("Change mov detected"); + mqttClient.publish("/home/bigroom/move", 1, false, old_mov ? "1" : "0"); + } + + if(cRun + 999 < millis()){ + cRun = millis(); + //analogWrite(B_LED, dc); + /*if(dir){ + dc += 64; + if(dc >= 959) dir = !dir; + } + else{ + dc -= 64; + if(dc <= 64) dir = !dir; + }*/ + //Serial.println(dc); + adc = analogRead(A0); + if(abs(adc - lastADC) > 20){ + lastADC = adc; + itoa(adc, v, 10); + mqttClient.publish("/home/bigroom/light", 1, false, v); + } + if(meas){ + Serial.println(adc); + temp += (htu.readTemperature() - temp) / 60.0f; + rel_hum += (htu.readHumidity() - rel_hum) / 60.0f; + Serial.print(cRun); + Serial.print("\t"); + Serial.print(minCnt); + Serial.print("\t"); + Serial.print("Temp: "); Serial.print(temp); Serial.print(" C"); + Serial.print("\t\t"); + Serial.print("Humidity: "); Serial.print(rel_hum); Serial.println(" \%"); + digitalWrite(P_SENS, LOW); + meas = false; + } + else{ + if(minCnt % 5 == 0){ + digitalWrite(P_SENS, HIGH); + meas = true; + } + } + if(++minCnt == 60){ + minCnt = 0; + if(mqttClient.connected()){ + //char s[50]; + g_led.start(); + Serial.println("Begin Publish"); + dtostrf(temp, 5, 1,v); + mqttClient.publish("/home/bigroom/temp", 0, false, v); + Serial.println("Publish1"); + dtostrf(rel_hum, 5, 1,v); + mqttClient.publish("/home/bigroom/humid", 0, false, v); + Serial.println("Publish2"); + //sprintf(s, "{temperatura: %.1f, humidity: %.1f}", temp, rel_hum); + //Serial.println(s); + //mqttClient.publish("/home/bigroom/climat", 0, false, s); + } + } + else if(minCnt % 10 == 0){ + if(mqttClient.connected()) mqttClient.publish("/home/bigroom/millis", 0, false, itoa(millis(), v, 10)); + //b_led.start(); + } + } +} + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + digitalWrite(B_LED, LOW); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + digitalWrite(B_LED, HIGH); + digitalWrite(R_LED, LOW); + //uint16_t packetIdSub = + // Serial.print("Subscribing Lamp1, packetId: "); + // Serial.println(packetIdSub); + //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); + //Serial.print("Subscribing Lamp2, packetId: "); + //Serial.println(packetIdSub); + //Serial.println("Publishing at Lamp 1"); + //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); + //Serial.println("Publishing at Lamp 2"); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + Serial.println("Disconnected from MQTT."); + digitalWrite(B_LED, LOW); + digitalWrite(R_LED, HIGH); + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + // Serial.println("Subscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); + // Serial.print(" qos: "); + // Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + // Serial.println("Unsubscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/kor/lamp1_set") == 0){ + } +} + +void onMqttPublish(uint16_t packetId) { + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + g_led.start(); +} diff --git a/ESP_BigRoom/test/README b/ESP_BigRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/ESP_BigRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/ESP_Electro/.gitignore b/ESP_Electro/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP_Electro/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP_Electro/.travis.yml b/ESP_Electro/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/ESP_Electro/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/ESP_Electro/.vscode/extensions.json b/ESP_Electro/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/ESP_Electro/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/ESP_Electro/include/README b/ESP_Electro/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/ESP_Electro/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/ESP_Electro/lib/README b/ESP_Electro/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/ESP_Electro/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP_Electro/platformio.ini b/ESP_Electro/platformio.ini new file mode 100644 index 0000000..d29f8a8 --- /dev/null +++ b/ESP_Electro/platformio.ini @@ -0,0 +1,18 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp07] +platform = espressif8266 +;board = nodemcuv2 +board = esp07 +framework = arduino +board_build.ldscript = eagle.flash.1m.ld +upload_protocol = espota +upload_port = 192.168.1.136 diff --git a/ESP_Electro/src/main.cpp b/ESP_Electro/src/main.cpp new file mode 100644 index 0000000..1b02e72 --- /dev/null +++ b/ESP_Electro/src/main.cpp @@ -0,0 +1,208 @@ +#include +#include +#include +#include +#include + +#define LED_WF (14) +#define LED_MQ (12) +#define LED_WRK (13) + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; +unsigned long cRun = millis(); +double curr; +int nSec, nSampl; + +EnergyMonitor emon1; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); + digitalWrite(LED_WF, HIGH); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(LED_WF, LOW); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + digitalWrite(LED_MQ, HIGH); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(LED_MQ, LOW); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { +} + +void onMqttPublish(uint16_t packetId) { + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void setup(){ + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.hostname("Test"); + Serial.begin(9600); + + emon1.current(0, 30.0); + + ArduinoOTA.onStart([]() { + Serial1.println("Start Update"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + Serial1.println("\nEnd Update"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + //Serial1.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial1.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial1.println("Auth Failed"); + // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial1.println("Begin Failed"); + // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial1.println("Connect Failed"); + // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial1.println("Receive Failed"); + // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial1.println("End Failed"); + // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + pinMode(LED_WF, OUTPUT); + pinMode(LED_MQ, OUTPUT); + pinMode(LED_WRK, OUTPUT); + //pinMode(5, INPUT_PULLUP); + digitalWrite(LED_WF, LOW); + digitalWrite(LED_MQ, LOW); + digitalWrite(LED_WRK, LOW); + connectToWifi(); + nSec = 0; + curr = -1; + nSampl = 0; + #ifdef ESP8266 + Serial.println("ESP8266"); + delay(1000); + #endif +} + +void loop(){ + static bool led_wrk = false; + + ArduinoOTA.handle(); + yield(); + if(cRun + 999 < millis()){ + cRun = millis(); + double Irms = 0; + if(WiFi.isConnected()){ + Irms = emon1.calcIrms(1480) - 0.5; + if(curr < 0){ + curr = Irms; + } + else{ + //curr += (Irms - curr) / 60; + curr += (Irms); + } + // Serial.print("Sec: "); + // yield(); + // Serial.print(nSec); + // yield(); + // Serial.print("\t"); + // yield(); + // Serial.print(Irms); + // yield(); + // Serial.print("\t"); + // yield(); + // Serial.println(Irms * 233); + led_wrk = !led_wrk; + digitalWrite(LED_WRK, led_wrk); + nSampl++; + } + if(++nSec > 59){ + nSec = 0; + curr = curr / (double)nSampl; + // Serial.print("Millis: "); + // yield(); + // Serial.print(millis()); + // yield(); + // Serial.print("\t"); + // yield(); + // Serial.print(curr); + // yield(); + // Serial.print("\t"); + // yield(); + // Serial.println(curr * 233); + if(nSampl > 0){ + //Serial.println("Publish"); + char v[7]; + sprintf(v, "%.2f", curr); + mqttClient.publish("/home/kor/curr", 1, false, v); + } + nSampl = 0; + curr = -1; + } + } +} + + diff --git a/ESP_Electro/test/README b/ESP_Electro/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/ESP_Electro/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/ESP_Kor/.gitignore b/ESP_Kor/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP_Kor/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP_Kor/.travis.yml b/ESP_Kor/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/ESP_Kor/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/ESP_Kor/.vscode/extensions.json b/ESP_Kor/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/ESP_Kor/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/ESP_Kor/include/README b/ESP_Kor/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/ESP_Kor/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/ESP_Kor/lib/README b/ESP_Kor/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/ESP_Kor/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP_Kor/platformio.ini b/ESP_Kor/platformio.ini new file mode 100644 index 0000000..e23375f --- /dev/null +++ b/ESP_Kor/platformio.ini @@ -0,0 +1,17 @@ +;PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +monitor_speed = 9600 +upload_protocol = espota +upload_port = 192.168.1.6 diff --git a/ESP_Kor/src/main.cpp b/ESP_Kor/src/main.cpp new file mode 100644 index 0000000..5b8164f --- /dev/null +++ b/ESP_Kor/src/main.cpp @@ -0,0 +1,194 @@ +#include +#include +#include +#include +#include "SdsDustSensor.h" + +#define WIFI_SSID "wf-home" +#define WIFI_PASSWORD "0ndthnrf" +#define MQTT_SERV "192.168.1.250" + +#define HOSTNAME "ESP_Kor" + +#define LED_WF (D0) +#define LED_MQ (D3) +#define LED_WRK (D4) + +int rxPin = D1; +int txPin = D2; +SdsDustSensor sds(rxPin, txPin); + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttSubscribe(uint16_t packetId, uint8_t qos); +void onMqttUnsubscribe(uint16_t packetId); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +void onMqttPublish(uint16_t packetId); + +unsigned long cRun; +int cSec = 0; + +void setup() +{ + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.hostname(HOSTNAME); + ArduinoOTA.onStart([]() { + Serial.println("ArduinoOTA start"); + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nArduinoOTA end"); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("OTA Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) { + Serial.println("Auth Failed"); + } else if (error == OTA_BEGIN_ERROR) { + Serial.println("Begin Failed"); + } else if (error == OTA_CONNECT_ERROR) { + Serial.println("Connect Failed"); + } else if (error == OTA_RECEIVE_ERROR) { + Serial.println("Receive Failed"); + } else if (error == OTA_END_ERROR) { + Serial.println("End Failed"); + } + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(MQTT_SERV, 1883); + + sds.begin(); + + // Serial.println(sds.queryFirmwareVersion().toString()); // prints firmware version + // Serial.println(sds.setActiveReportingMode().toString()); // ensures sensor is in 'active' reporting mode + // Serial.println(sds.setCustomWorkingPeriod(3).toString()); // sensor sends data every 3 minutes + sds.setActiveReportingMode(); + sds.setCustomWorkingPeriod(1); + + pinMode(LED_WF, OUTPUT); + pinMode(LED_MQ, OUTPUT); + pinMode(LED_WRK, OUTPUT); + digitalWrite(LED_WF, HIGH); + digitalWrite(LED_MQ, HIGH); + + cRun = millis(); +} + +void loop() +{ + //static bool lwork = false; + static unsigned long stled = millis(); + ArduinoOTA.handle(); + if(cRun + 999 < millis()){ + cRun = millis(); + PmResult pm = sds.readPm(); + if((stled + 300) < millis()) digitalWrite(LED_WRK, LOW); + //lwork = !lwork; + cSec++; + if (pm.isOk()) { + if(mqttClient.connected()){ + digitalWrite(LED_WRK, HIGH); + stled = millis(); + char v[6]; + sprintf(v, "%.1f", pm.pm25); + mqttClient.publish("/home/kor/pm25", 1, false, v); + sprintf(v, "%.1f", pm.pm10); + mqttClient.publish("/home/kor/pm10", 1, false, v); + } + Serial.print(cRun); Serial.print("\t"); + Serial.print("PM2.5 = "); + Serial.print(pm.pm25); + Serial.print(", PM10 = "); + Serial.println(pm.pm10); + + cSec = 0; + } + } +} + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); + digitalWrite(LED_WF, LOW); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(LED_WF, HIGH); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + digitalWrite(LED_MQ, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(LED_MQ, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { +} + +void onMqttPublish(uint16_t packetId) { + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} diff --git a/ESP_Kor/test/README b/ESP_Kor/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/ESP_Kor/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/ESP_MidRoom/.gitignore b/ESP_MidRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP_MidRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/ESP_MidRoom/.travis.yml b/ESP_MidRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/ESP_MidRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/ESP_MidRoom/.vscode/extensions.json b/ESP_MidRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/ESP_MidRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/ESP_MidRoom/include/README b/ESP_MidRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/ESP_MidRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/ESP_MidRoom/include/amqtt.h b/ESP_MidRoom/include/amqtt.h new file mode 100644 index 0000000..cb60798 --- /dev/null +++ b/ESP_MidRoom/include/amqtt.h @@ -0,0 +1,30 @@ +// #ifndef __AMQTT__ +// #define __AMQTT__ +// //#include +// #include +// #include +// #include +// #include + +// const char* ssid = "wf-home"; +// const char* password = "0ndthnrf"; +// const char* mqtt_server = "192.168.1.250"; + +// AsyncMqttClient mqttClient; +// Ticker mqttReconnectTimer; + +// WiFiEventHandler wifiConnectHandler; +// WiFiEventHandler wifiDisconnectHandler; +// Ticker wifiReconnectTimer; + +// void connectToWifi(); +// void connectToMqtt(); +// void onWifiConnect(const WiFiEventStationModeGotIP& event); +// void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +// void onMqttConnect(bool sessionPresent); +// void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +// void onMqttSubscribe(uint16_t packetId, uint8_t qos); +// void onMqttUnsubscribe(uint16_t packetId); +// void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +// void onMqttPublish(uint16_t packetId); +// #endif diff --git a/ESP_MidRoom/include/leds.h b/ESP_MidRoom/include/leds.h new file mode 100644 index 0000000..7981c48 --- /dev/null +++ b/ESP_MidRoom/include/leds.h @@ -0,0 +1,19 @@ +#ifndef __LEDS_H__ +#define __LEDS_H__ +#include + +class leds +{ +private: + int ledPin; + bool inv, state; + int onMS; + unsigned long curMS; +public: + leds(int ledPin, int onms = 300, bool inverse = false); + //~leds(); + void start(); + void tick(); +}; + +#endif \ No newline at end of file diff --git a/ESP_MidRoom/include/main.h b/ESP_MidRoom/include/main.h new file mode 100644 index 0000000..dcd6dc4 --- /dev/null +++ b/ESP_MidRoom/include/main.h @@ -0,0 +1,19 @@ +#include +#include +#include +#include + +#include +#include + +//#define POWER_SENS (7) + +Adafruit_BME280 bme; +MHZ19 mhz19; + +unsigned long crun; +uint32_t co2; +bool firstRun; +float p, t, h; +//uint16_t cntSec; +int light, lightPrev; diff --git a/ESP_MidRoom/lib/README b/ESP_MidRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/ESP_MidRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/ESP_MidRoom/platformio.ini b/ESP_MidRoom/platformio.ini new file mode 100644 index 0000000..4ef80ac --- /dev/null +++ b/ESP_MidRoom/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = esp12e +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m.ld +;board_build.flash_mode = dout +upload_protocol = espota +upload_port = 192.168.1.132 \ No newline at end of file diff --git a/ESP_MidRoom/src/amqtt.cpp b/ESP_MidRoom/src/amqtt.cpp new file mode 100644 index 0000000..9218dad --- /dev/null +++ b/ESP_MidRoom/src/amqtt.cpp @@ -0,0 +1,72 @@ +// #include + +// void connectToWifi() { +// Serial.println("Connecting to Wi-Fi..."); +// WiFi.begin(ssid, password); +// } + +// void connectToMqtt() { +// Serial.println("Connecting to MQTT..."); +// //mqttClient.connect(); +// } + +// void onWifiConnect(const WiFiEventStationModeGotIP& event) { +// Serial.println("Connected to Wi-Fi."); +// Serial.print("IP: "); +// Serial.println(WiFi.localIP()); +// connectToMqtt(); +// } + +// void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { +// Serial.println("Disconnected from Wi-Fi."); +// mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi +// wifiReconnectTimer.once(2, connectToWifi); +// } + +// void onMqttConnect(bool sessionPresent) { +// Serial.println("Connected to MQTT."); +// Serial.print("Session present: "); +// Serial.println(sessionPresent); +// //uint16_t packetIdSub = +// // Serial.print("Subscribing Lamp1, packetId: "); +// // Serial.println(packetIdSub); +// //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); +// //Serial.print("Subscribing Lamp2, packetId: "); +// //Serial.println(packetIdSub); +// //Serial.println("Publishing at Lamp 1"); +// //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); +// //Serial.println("Publishing at Lamp 2"); +// } + +// void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { +// Serial.println("Disconnected from MQTT."); + +// if (WiFi.isConnected()) { +// mqttReconnectTimer.once(2, connectToMqtt); +// } +// } + +// void onMqttSubscribe(uint16_t packetId, uint8_t qos) { +// // Serial.println("Subscribe acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// // Serial.print(" qos: "); +// // Serial.println(qos); +// } + +// void onMqttUnsubscribe(uint16_t packetId) { +// // Serial.println("Unsubscribe acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// } + +// void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { +// if(strcmp(topic, "/home/kor/lamp1_set") == 0){ +// } +// } + +// void onMqttPublish(uint16_t packetId) { +// // Serial.println("Publish acknowledged."); +// // Serial.print(" packetId: "); +// // Serial.println(packetId); +// } diff --git a/ESP_MidRoom/src/leds.cpp b/ESP_MidRoom/src/leds.cpp new file mode 100644 index 0000000..03bf657 --- /dev/null +++ b/ESP_MidRoom/src/leds.cpp @@ -0,0 +1,32 @@ +#include + +leds::leds(int pinLED, int onms, bool inverse) +{ + ledPin = pinLED; + inv = inverse; + onMS = onms; + state = false; +} + +void leds::start() +{ + curMS = millis(); + state = true; + if(!inv) + analogWrite(ledPin, 100); + else + analogWrite(ledPin, 0); + //digitalWrite(ledPin, !inv); +} + +void leds::tick() +{ + if(state && ((curMS + onMS) < millis())){ + state = false; + if(inv) + analogWrite(ledPin, 1); + else + analogWrite(ledPin, 0); + //digitalWrite(ledPin, inv); + } +} diff --git a/ESP_MidRoom/src/main.cpp b/ESP_MidRoom/src/main.cpp new file mode 100644 index 0000000..b0bd4df --- /dev/null +++ b/ESP_MidRoom/src/main.cpp @@ -0,0 +1,337 @@ +#include +#include +#include +#include +#include + +#define R_LED (13) +#define G_LED (12) +#define B_LED (0) +#define MOV_SENS (16) +#define P_SENS (14) + +bool meas = false; +short minCnt; +bool send_move = false; +int old_mov = 0; +int adc = 0; +int lastADC = 0; + +unsigned long cRun; + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttSubscribe(uint16_t packetId, uint8_t qos); +void onMqttUnsubscribe(uint16_t packetId); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +void onMqttPublish(uint16_t packetId); + +//leds b_led(B_LED); +leds g_led(G_LED, 100); +//leds r_led(R_LED, 100); + +void setup() { + Serial.begin(9600, SERIAL_8N1); + Serial1.begin(9600); + Serial1.println("Booting"); // "Загрузка" + + WiFi.mode(WIFI_STA); + WiFi.hostname("MidRoom"); + ArduinoOTA.onStart([]() { + //Serial1.println("Start Update"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + //Serial1.println("\nEnd Update"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + ////Serial1.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // //Serial1.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) //Serial1.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) //Serial1.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) //Serial1.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) //Serial1.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) //Serial1.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + pinMode(MOV_SENS, INPUT_PULLUP); + pinMode(P_SENS, OUTPUT); + pinMode(R_LED, OUTPUT); + pinMode(G_LED, OUTPUT); + pinMode(B_LED, OUTPUT); + //analogWriteRange(100); + digitalWrite(P_SENS, HIGH); + digitalWrite(B_LED, HIGH); + digitalWrite(R_LED, HIGH); + Serial1.println(F("Begin MH-Z19")); + for(int i = 0; i < 5; i++){ + Serial1.print('.'); + delay(1000); + } + Serial1.println(); + mhz19.begin(Serial); + //char myVersion[4]; + //mhz19.getVersion(myVersion); + + // //Serial1.print("\nFirmware Version: "); + // for(byte i = 0; i < 4; i++) + // { + // //Serial1.print(myVersion[i]); + // if(i == 1) + // //Serial1.print("."); + // } + // //Serial1.println(""); + + // //Serial1.print("Range: "); + // //Serial1.println(mhz19.getRange()); + // //Serial1.print("Background CO2: "); + // //Serial1.println(mhz19.getBackgroundCO2()); + // //Serial1.print("Temperature Cal: "); + // //Serial1.println(mhz19.getTempAdjustment()); + // //Serial1.print("ABC Status: "); mhz19.getABC() ? //Serial1.println("ON") : //Serial1.println("OFF"); + //Serial1.println(F("End Begin MH-Z19")); + + Wire.begin(); + Serial1.println(F("Begin BME")); + bool status = bme.begin(BME280_ADDRESS_ALTERNATE); + + + if (!status) { + Serial1.println(F("Could not find a valid BME280 sensor, check wiring, address, sensor ID!")); + } + else{ + delay(100); + p = bme.readPressure(); + t = bme.readTemperature(); + h = bme.readHumidity(); + Serial1.print(F("T: ")); + Serial1.print(t); + Serial1.print(F("\tH: ")); + Serial1.print(h); + Serial1.print(F("\tP: ")); + Serial1.println(p); + } + + connectToWifi(); + + cRun = millis(); + Serial1.println(F("Start Loop")); + //(R_LED, HIGH); +} + +void loop() { + float pt, tt, ht; + char v[11]; + static int stDelay = 0; + ArduinoOTA.handle(); + g_led.tick(); + //r_led.tick(); + if (digitalRead(MOV_SENS) != old_mov){ + old_mov = digitalRead(MOV_SENS); + Serial1.println(F("Change mov detected")); + mqttClient.publish("/home/midroom/move", 1, false, old_mov ? "1" : "0"); + } + + if(cRun + 999 < millis()){ + cRun = millis(); + //if(mqttClient.connected()) digitalWrite(R_LED, LOW); else digitalWrite(R_LED, HIGH); + adc = analogRead(A0); + Serial1.print(F("ADC: "));Serial1.println(adc); + Serial1.print(F("MQTT: "));Serial1.println(mqttClient.connected()); + if(abs(adc - lastADC) > 50){ + lastADC = adc; + itoa(adc, v, 10); + mqttClient.publish("/home/midroom/light", 1, false, v); + } + if(meas){ + //Serial1.println(adc); + Serial1.println("Measure"); + + pt = bme.readPressure(); + tt = bme.readTemperature(); + ht = bme.readHumidity(); + Serial1.print(F("T: ")); + Serial1.print(tt); + Serial1.print(F("\tH: ")); + Serial1.print(ht); + Serial1.print(F("\tP: ")); + Serial1.println(pt); + if(!isnan(pt)) + p += (pt - p) / 60.0f ; + else + { + Serial1.println(F("Error BME")); + } + + if(!isnan(tt)) + t += (tt - t) / 30.0f ; + if(!isnan(ht)) + h += (ht - h) / 30.0f ; + digitalWrite(P_SENS, LOW); + meas = false; + } + else{ + if(minCnt % 5 == 0){ + co2 = mhz19.getCO2(); + Serial1.print("CO2: "); + Serial1.println(co2); + digitalWrite(P_SENS, HIGH); + bme.begin(BME280_ADDRESS_ALTERNATE); + meas = true; + } + } + if(++minCnt == 60){ + minCnt = 0; + if(mqttClient.connected()){ + g_led.start(); + //r_led.start(); + //Serial1.println("Begin Publish"); + dtostrf(t, 5, 1,v); + mqttClient.publish("/home/midroom/temp", 0, false, v); + //Serial1.println("Publish1"); + dtostrf(h, 5, 1,v); + mqttClient.publish("/home/midroom/humid", 0, false, v); + //Serial1.println("Publish2"); + if(firstRun){ + stDelay++; + if(stDelay > 3) firstRun = false; + } + if(!firstRun && (mhz19.errorCode == RESULT_OK)){ + itoa(co2, v, 10); + mqttClient.publish("/home/midroom/co2", 0, false, v); + //Serial1.println("Publish3"); + } + } + } + else if(minCnt % 10 == 0){ + itoa(millis(), v, 10); + if(mqttClient.connected()){ + mqttClient.publish("/home/midroom/millis", 0, false, v); + dtostrf(t, 5, 1,v); + mqttClient.publish("/home/midroom/temp", 0, false, v); + //Serial1.println("Publish1"); + dtostrf(h, 5, 1,v); + mqttClient.publish("/home/midroom/humid", 0, false, v); + g_led.start(); + } + } + } +} + +void connectToWifi() { + Serial1.println(F("Connecting to Wi-Fi...")); + //Serial1.flush(); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial1.println(F("Connecting to MQTT...")); + //Serial1.flush(); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial1.println(F("Connected to Wi-Fi.")); + Serial1.print(F("IP: ")); + //Serial1.flush(); + Serial1.println(WiFi.localIP()); + digitalWrite(R_LED, LOW); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial1.println(F("Disconnected from Wi-Fi.")); + //Serial1.flush(); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(R_LED, HIGH); +} + +void onMqttConnect(bool sessionPresent) { + Serial1.println(F("Connected to MQTT.")); + Serial1.print(F("Session present: ")); + //Serial1.flush(); + Serial1.println(sessionPresent); + //digitalWrite(B_LED, HIGH); + //digitalWrite(R_LED, LOW); + //uint16_t packetIdSub = + // //Serial1.print("Subscribing Lamp1, packetId: "); + // //Serial1.println(packetIdSub); + //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); + ////Serial1.print("Subscribing Lamp2, packetId: "); + ////Serial1.println(packetIdSub); + ////Serial1.println("Publishing at Lamp 1"); + //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); + ////Serial1.println("Publishing at Lamp 2"); + digitalWrite(B_LED, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + Serial1.println("Disconnected from MQTT."); + //digitalWrite(B_LED, LOW); + //digitalWrite(R_LED, HIGH); + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(B_LED, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + // //Serial1.println("Subscribe acknowledged."); + // //Serial1.print(" packetId: "); + // //Serial1.println(packetId); + // //Serial1.print(" qos: "); + // //Serial1.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + // //Serial1.println("Unsubscribe acknowledged."); + // //Serial1.print(" packetId: "); + // //Serial1.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/kor/lamp1_set") == 0){ + } +} + +void onMqttPublish(uint16_t packetId) { + //Serial1.println("Publish acknowledged."); + //Serial1.print(" packetId: "); + //Serial1.println(packetId); + //g_led.start(); +} + diff --git a/ESP_MidRoom/test/README b/ESP_MidRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/ESP_MidRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/GateWay/.gitignore b/GateWay/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/GateWay/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/GateWay/.travis.yml b/GateWay/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/GateWay/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/GateWay/.vscode/extensions.json b/GateWay/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/GateWay/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/GateWay/include/README b/GateWay/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/GateWay/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/GateWay/include/mys.h b/GateWay/include/mys.h new file mode 100644 index 0000000..80441f2 --- /dev/null +++ b/GateWay/include/mys.h @@ -0,0 +1,5 @@ +#define MY_DEBUG +#define MY_RADIO_RF24 +#define MY_RF24_PA_LEVEL (RF24_PA_MAX) +#define MY_RF24_CHANNEL (15) +#define MY_RF24_DATARATE (RF24_250KBPS) diff --git a/GateWay/lib/README b/GateWay/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/GateWay/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/GateWay/platformio.ini b/GateWay/platformio.ini new file mode 100644 index 0000000..e23375f --- /dev/null +++ b/GateWay/platformio.ini @@ -0,0 +1,17 @@ +;PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +monitor_speed = 9600 +upload_protocol = espota +upload_port = 192.168.1.6 diff --git a/GateWay/src/main.cpp b/GateWay/src/main.cpp new file mode 100644 index 0000000..86af863 --- /dev/null +++ b/GateWay/src/main.cpp @@ -0,0 +1,141 @@ +#include + +/* * LED purposes: + * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h + * - RX (green) - blink fast on radio message received. In inclusion mode will blink fast only on presentation received + * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly + * - ERR (red) - fast blink on error during transmission error or receive crc error + * + */ + +#define MY_DEBUG +#define MY_BAUD_RATE 9600 +#define MY_RADIO_RF24 +#define MY_GATEWAY_ESP8266 +// #define MY_DISABLED_SERIAL +// #define MY_SPLASH_SCREEN_DISABLED +#define MY_RF24_PA_LEVEL (RF24_PA_MAX) +#define MY_RF24_CHANNEL (15) +#define MY_RF24_DATARATE (RF24_250KBPS) + +#define MY_WIFI_SSID "wf-home" +#define MY_WIFI_PASSWORD "0ndthnrf" + +#define MY_HOSTNAME "ESP8266_GW" + +#define MY_PORT 5003 + +// How many clients should be able to connect to this gateway (default 1) +#define MY_GATEWAY_MAX_CLIENTS 12 + +// #define MY_DEFAULT_LED_BLINK_PERIOD 300 + +// Flash leds on rx/tx/err +#define MY_DEFAULT_ERR_LED_PIN D3 // Error led pin +#define MY_DEFAULT_RX_LED_PIN D4 // Receive led pin +//#define MY_DEFAULT_TX_LED_PIN 1 // the PCB, on board LED +#define MY_WITH_LEDS_BLINKING_INVERSE +#define MY_RF24_CE_PIN D0 + +#include +#include +#include "SdsDustSensor.h" + +int rxPin = D1; +int txPin = D2; +SdsDustSensor sds(rxPin, txPin); + +unsigned long cRun; +int cSec = 0; + +#define CHILD_ID_25 0 +#define CHILD_ID_10 1 + +MyMessage msg25(CHILD_ID_25, V_VAR1); +MyMessage msg10(CHILD_ID_10, V_VAR2); + +void setup() +{ + WiFi.begin(MY_WIFI_SSID, MY_WIFI_PASSWORD); + if(WiFi.waitForConnectResult() == WL_CONNECTED){ + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(MY_WIFI_SSID); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + ArduinoOTA.onStart([]() { + Serial.println("ArduinoOTA start"); + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nArduinoOTA end"); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("OTA Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) { + Serial.println("Auth Failed"); + } else if (error == OTA_BEGIN_ERROR) { + Serial.println("Begin Failed"); + } else if (error == OTA_CONNECT_ERROR) { + Serial.println("Connect Failed"); + } else if (error == OTA_RECEIVE_ERROR) { + Serial.println("Receive Failed"); + } else if (error == OTA_END_ERROR) { + Serial.println("End Failed"); + } + }); + ArduinoOTA.begin(); + sds.begin(); + + // Serial.println(sds.queryFirmwareVersion().toString()); // prints firmware version + // Serial.println(sds.setActiveReportingMode().toString()); // ensures sensor is in 'active' reporting mode + // Serial.println(sds.setCustomWorkingPeriod(3).toString()); // sensor sends data every 3 minutes + sds.setActiveReportingMode(); + sds.setCustomWorkingPeriod(1); + + cRun = millis(); +} + +void presentation() +{ + sendSketchInfo("GateWayDust", "2.0"); + present(CHILD_ID_25, S_AIR_QUALITY, "Dust 2.5"); + wait(50); + present(CHILD_ID_10, S_AIR_QUALITY, "Dust 10"); +} + +void loop() +{ + // Send locally attached sensors data here + ArduinoOTA.handle(); + if(cRun + 1000 < millis()){ + cRun = millis(); + PmResult pm = sds.readPm(); + cSec++; + if (pm.isOk()) { + // Serial.print(cSec); Serial.print("\t"); + // Serial.print("PM2.5 = "); + // Serial.print(pm.pm25); + // Serial.print(", PM10 = "); + // Serial.println(pm.pm10); + + // // if you want to just print the measured values, you can use toString() method as well + // Serial.println(pm.toString()); + send(msg25.set(pm.pm25, 1)); + wait(100); + send(msg10.set(pm.pm10, 1)); + cSec = 0; + //} else { + // // notice that loop delay is set to 5s (sensor sends data every 3 minutes) and some reads are not available + // Serial.print(cSec); Serial.print("\t"); + // Serial.print("Could not read values from sensor, reason: "); + // Serial.println(pm.statusToString()); + } + } +} diff --git a/GateWay/test/README b/GateWay/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/GateWay/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/I2C Scan/.gitignore b/I2C Scan/.gitignore new file mode 100644 index 0000000..5762142 --- /dev/null +++ b/I2C Scan/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/I2C Scan/.travis.yml b/I2C Scan/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/I2C Scan/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/I2C Scan/.vscode/extensions.json b/I2C Scan/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/I2C Scan/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/I2C Scan/include/README b/I2C Scan/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/I2C Scan/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/I2C Scan/lib/README b/I2C Scan/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/I2C Scan/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/I2C Scan/platformio.ini b/I2C Scan/platformio.ini new file mode 100644 index 0000000..8c784d4 --- /dev/null +++ b/I2C Scan/platformio.ini @@ -0,0 +1,24 @@ +;PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[platformio] +default_envs = nano +[env:uno] +platform = atmelavr +board = uno +framework = arduino +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +[env:nano] +platform = atmelavr +board = nanoatmega328 +framework = arduino diff --git a/I2C Scan/src/main.cpp b/I2C Scan/src/main.cpp new file mode 100644 index 0000000..6627c6b --- /dev/null +++ b/I2C Scan/src/main.cpp @@ -0,0 +1,54 @@ +#include + +// I2C Scanner +// Written by Nick Gammon +// Date: 20th April 2011 +/*#undef PIN_WIRE_SDA +#undef PIN_WIRE_SCL +#define PIN_WIRE_SCL D1 +#define PIN_WIRE_SDA D2*/ +#include + +void setup() { + Serial.begin (9600); + + // Leonardo: wait for serial port to connect + while (!Serial) + { + } + + Serial.println (); +//#undef SCL +//#undef SDA + Serial.print("SCL=");Serial.println (SCL); + Serial.print("SDA=");Serial.println (SDA); + Serial.print("PWSCL=");Serial.println (PIN_WIRE_SCL); + Serial.print("PWSDA=");Serial.println (PIN_WIRE_SDA); + Serial.println (); + Serial.println ("I2C scanner. Scanning ..."); + byte count = 0; + +/*#define SCL 5 +#define SDA 4*/ + Wire.begin(); + for (byte i = 8; i < 120; i++) + { + Wire.beginTransmission (i); + if (Wire.endTransmission () == 0) + { + Serial.print ("Found address: "); + Serial.print (i, DEC); + Serial.print (" (0x"); + Serial.print (i, HEX); + Serial.println (")"); + count++; + delay (1); // maybe unneeded? + } // end of good response + } // end of for loop + Serial.println ("Done."); + Serial.print ("Found "); + Serial.print (count, DEC); + Serial.println (" device(s)."); +} // end of setup + +void loop() {} diff --git a/I2C Scan/test/README b/I2C Scan/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/I2C Scan/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/KuhLight_ESP/.gitignore b/KuhLight_ESP/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/KuhLight_ESP/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/KuhLight_ESP/.travis.yml b/KuhLight_ESP/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/KuhLight_ESP/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/KuhLight_ESP/.vscode/extensions.json b/KuhLight_ESP/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/KuhLight_ESP/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/KuhLight_ESP/include/README b/KuhLight_ESP/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/KuhLight_ESP/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/KuhLight_ESP/lib/README b/KuhLight_ESP/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/KuhLight_ESP/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/KuhLight_ESP/platformio.ini b/KuhLight_ESP/platformio.ini new file mode 100644 index 0000000..5b21ffa --- /dev/null +++ b/KuhLight_ESP/platformio.ini @@ -0,0 +1,18 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:esp07] +platform = espressif8266 +board = esp07 +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m.ld +upload_protocol = espota +upload_port = 192.168.1.135 \ No newline at end of file diff --git a/KuhLight_ESP/src/main.cpp b/KuhLight_ESP/src/main.cpp new file mode 100644 index 0000000..8da1b4d --- /dev/null +++ b/KuhLight_ESP/src/main.cpp @@ -0,0 +1,191 @@ +#include +//#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +#define LED_WF (12) +#define LED_MQ (13) +#define LED_WRK (14) +#define SENS (4) +#define LAMP (5) + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +unsigned long cRun = 0; +unsigned long lastSense; +uint16_t nSec = 0; +uint8_t lamp, lampP; +uint8_t light; + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + connectToMqtt(); + digitalWrite(LED_WF, HIGH); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(LED_WF, LOW); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + mqttClient.subscribe("/home/kuh/lighttbl_set", 1); + mqttClient.publish("/home/kuh/lighttbl", 1, false, light ? "1" : "0"); + digitalWrite(LED_MQ, HIGH); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(LED_MQ, LOW); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/kuh/lighttbl_set") == 0){ + light = atoi(payload); + digitalWrite(LAMP, light); + mqttClient.publish("/home/kuh/lighttbl", 1, false, light ? "1" : "0"); + } +} + +void onMqttPublish(uint16_t packetId) { + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void setup() { + Serial.begin(9600); + Serial.println("Begin"); + WiFi.mode(WIFI_STA); + WiFi.hostname("KuhLight"); + ArduinoOTA.onStart([]() { + Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + // EEPROM.begin(16); + // EEPROM.get(0, lamp); + + pinMode(LAMP, OUTPUT); + pinMode(LED_WF, OUTPUT); + pinMode(LED_MQ, OUTPUT); + pinMode(LED_WRK, OUTPUT); + pinMode(SENS, INPUT); + + digitalWrite(LED_WF, LOW); + digitalWrite(LED_MQ, LOW); + digitalWrite(LED_WRK, LOW); + + Serial.println("Connect to WiFi"); + connectToWifi(); + lastSense = millis(); + light = false; + Serial.println("Loop"); +} + +void loop() { + static bool led_wrk = false; + ArduinoOTA.handle(); + + if(digitalRead(SENS) == 0){ + if(lastSense + 3000 < millis()){ + lastSense = millis(); + light = !light; + digitalWrite(LAMP, light); + mqttClient.publish("/home/kuh/lighttbl", 1, false, light ? "1" : "0"); + Serial.println("Change state"); + Serial.println(light); + } + } + if(cRun + 999 < millis()){ + cRun = millis(); + nSec++; + led_wrk = !led_wrk; + digitalWrite(LED_WRK, led_wrk); + if(nSec > 59){ + if(mqttClient.connected()){ + char v[11]; + itoa(millis(), v, 10); + mqttClient.publish("/home/kuh/ltblmillis", 1, false, v); + Serial.print("Millis: "); + Serial.println(millis()); + } + nSec = 0; + } + } +} diff --git a/KuhLight_ESP/test/README b/KuhLight_ESP/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/KuhLight_ESP/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/MYS_Home.code-workspace b/MYS_Home.code-workspace new file mode 100644 index 0000000..3beef69 --- /dev/null +++ b/MYS_Home.code-workspace @@ -0,0 +1,70 @@ +{ + "folders": [ + { + "path": "esp8266-KUH" + }, + { + "name": "I2C Scan", + "path": "I2C Scan" + }, + { + "name": "ESP12", + "path": "D:\\Projects\\Arduino\\ESP12" + }, + { + "name": "VT_ESP8266", + "path": "VT_ESP8266" + }, + { + "name": "MainDoor", + "path": "MainDoor" + }, + { + "path": "Sw_MidlRoom" + }, + { + "path": "Sw_BigRoom" + }, + { + "name": "ESP12SmallRoom", + "path": "ESP12SmallRoom" + }, + { + "path": "Sw_Koridor" + }, + { + "path": "Sw_SmallRoom" + }, + { + "path": "ESP_BigRoom" + }, + { + "path": "ESP_MidRoom" + }, + { + "name": "KuhLight_ESP", + "path": "KuhLight_ESP" + }, + { + "path": "ESP_Kor" + }, + { + "path": "ESP_Electro" + } + ], + "settings": { + "terminal.integrated.env.windows": { + "PATH": "C:\\Users\\Lexa\\.platformio\\penv\\Scripts;C:\\Users\\Lexa\\.platformio\\penv;C:\\Python37\\Scripts\\;C:\\Python37\\;C:\\Python27\\;C:\\Python27\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\AMD\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\ATI Technologies\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;C:\\Program Files\\Microsoft SQL Server\\130\\Tools\\Binn\\;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Microsoft\\Web Platform Installer\\;C:\\Program Files\\dotnet\\;C:\\Program Files\\PuTTY\\;C:\\Program Files\\Git\\cmd;C:\\Program Files\\TortoiseSVN\\bin;C:\\Users\\Lexa\\AppData\\Local\\Microsoft\\WindowsApps;;C:\\Python37\\Scripts\\;C:\\Python37\\;C:\\Python27\\;C:\\Python27\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Program Files (x86)\\AMD\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\ATI Technologies\\ATI.ACE\\Core-Static;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;C:\\Program Files\\Microsoft SQL Server\\130\\Tools\\Binn\\;C:\\Program Files\\Microsoft VS Code\\bin;C:\\Program Files\\Microsoft\\Web Platform Installer\\;C:\\Program Files\\dotnet\\;C:\\Program Files\\PuTTY\\;C:\\Program Files\\Git\\cmd;C:\\Program Files\\TortoiseSVN\\bin;C:\\Users\\Lexa\\AppData\\Local\\Microsoft\\WindowsApps;", + "PLATFORMIO_CALLER": "vscode" + }, + "files.associations": { + "*.tcc": "cpp", + "list": "cpp", + "string": "cpp", + "vector": "cpp", + "memory": "cpp", + "random": "cpp", + "initializer_list": "cpp" + } + } +} \ No newline at end of file diff --git a/MainDoor/.gitignore b/MainDoor/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/MainDoor/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/MainDoor/.travis.yml b/MainDoor/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/MainDoor/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/MainDoor/.vscode/extensions.json b/MainDoor/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/MainDoor/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/MainDoor/include/README b/MainDoor/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/MainDoor/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/MainDoor/include/leds.h b/MainDoor/include/leds.h new file mode 100644 index 0000000..7981c48 --- /dev/null +++ b/MainDoor/include/leds.h @@ -0,0 +1,19 @@ +#ifndef __LEDS_H__ +#define __LEDS_H__ +#include + +class leds +{ +private: + int ledPin; + bool inv, state; + int onMS; + unsigned long curMS; +public: + leds(int ledPin, int onms = 300, bool inverse = false); + //~leds(); + void start(); + void tick(); +}; + +#endif \ No newline at end of file diff --git a/MainDoor/lib/README b/MainDoor/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/MainDoor/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/MainDoor/platformio.ini b/MainDoor/platformio.ini new file mode 100644 index 0000000..1f698da --- /dev/null +++ b/MainDoor/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nano] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m.ld +;board_build.flash_mode = dout +upload_protocol = espota +upload_port = 192.168.1.133 diff --git a/MainDoor/src/leds.cpp b/MainDoor/src/leds.cpp new file mode 100644 index 0000000..bb3739b --- /dev/null +++ b/MainDoor/src/leds.cpp @@ -0,0 +1,24 @@ +#include + +leds::leds(int pinLED, int onms, bool inverse) +{ + ledPin = pinLED; + inv = inverse; + onMS = onms; + state = false; +} + +void leds::start() +{ + curMS = millis(); + state = true; + digitalWrite(ledPin, !inv); +} + +void leds::tick() +{ + if(state && ((curMS + onMS) < millis())){ + state = false; + digitalWrite(ledPin, inv); + } +} diff --git a/MainDoor/src/main.cpp b/MainDoor/src/main.cpp new file mode 100644 index 0000000..3045add --- /dev/null +++ b/MainDoor/src/main.cpp @@ -0,0 +1,342 @@ +#include +//#include +#include +#include +#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +#define L_TOP (2) +#define L_INT (3) +#define L_DOWN (0) +#define L_SMALL (1) +#define DOOR (4) +#define L_WIFI (2) //On board blue +#define L_WIFI2 (14) //Green +#define L_MQTT (13) //Blue +#define L_MSG (12) //Red + +unsigned long cRun = 0; +unsigned long l_run; +uint8_t tP, iP, dP, sP, door, doorP; +//uint16_t timeT, timeI, timeD, timeS; +//uint16_t timeTt, timeIt, timeDt, timeSt; +// uint16_t timeAlm, timeOpen; +// bool doorSent, lockSent; +uint16_t nSec = 0; +leds r_led(L_MSG); +uint8_t pcfreg, opcfreg; +PCF8574 pcf(0x3F); +bool l_m = false; + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + digitalWrite(L_WIFI, HIGH); + digitalWrite(L_WIFI2, LOW); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + digitalWrite(L_WIFI, LOW); + digitalWrite(L_WIFI2, HIGH); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println("Connected to MQTT."); + Serial.print("Session present: "); + Serial.println(sessionPresent); + //uint16_t packetIdSub = + //mqttClient.subscribe("/home/kor/doortimeout_set", 1); + mqttClient.publish("/home/kor/locker_top", 1, false, tP ? "0" : "1"); + mqttClient.publish("/home/kor/locker_int", 1, false, iP ? "0" : "1"); + mqttClient.publish("/home/kor/locker_down", 1, false, dP ? "0" : "1"); + mqttClient.publish("/home/kor/locker_small", 1, false, sP ? "0" : "1"); + mqttClient.publish("/home/kor/door", 1, false, doorP ? "0" : "1"); + //mqttClient.publish("/home/kor/doorlocker", 1, false, sP || dP || iP || tP ? "1" : "0"); + /*char v[7]; + itoa(timeAlm, v, 10); + mqttClient.publish("/home/kor/doortimeout", 1, false, v);*/ + //digitalWrite(L_WIFI2, LOW); + digitalWrite(L_MQTT, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(L_MQTT, HIGH); + //if(WiFi.isConnected()) + // digitalWrite(L_WIFI2, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + Serial.println("Subscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); + Serial.print(" qos: "); + Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + Serial.println("Unsubscribe acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { +/* if(strcmp(topic, "/home/kor/doortimeout_set") == 0){ + char v[7]; + timeAlm = atoi(payload); + EEPROM.put(0, timeAlm); + EEPROM.commit(); + itoa(timeAlm, v, 10); + mqttClient.publish("/home/kor/doortimeout", 0, false, v); + Serial.print("New Timeout: "); + Serial.println(timeAlm); + }*/ +} + +void onMqttPublish(uint16_t packetId) { + Serial.println("Publish acknowledged."); + Serial.print(" packetId: "); + Serial.println(packetId); +} + +void setup() { + Serial.begin(9600); + Serial.println("Begin"); + WiFi.mode(WIFI_STA); + WiFi.hostname("Door-Koridor"); + ArduinoOTA.onStart([]() { + Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + Wire.begin(); + // Serial.println("Begin Scan"); + // for (byte i = 8; i < 120; i++) + // { + // Wire.beginTransmission (i); + // if (Wire.endTransmission () == 0) + // { + // Serial.print ("Found address: "); + // Serial.print (i, DEC); + // Serial.print (" (0x"); + // Serial.print (i, HEX); + // Serial.println (")"); + // delay (1); // maybe unneeded? + // } // end of good response + // } // end of for loop + // Serial.println("End Scan"); + Wire.beginTransmission(0x3F); + if(Wire.endTransmission() == 0) Serial.println("PCF Found"); + else Serial.println("PCF Not Found"); + pcf.begin(); + + // pinMode(L_TOP, INPUT_PULLUP); + // pinMode(L_INT, INPUT_PULLUP); + // pinMode(L_DOWN, INPUT_PULLUP); + // pinMode(L_SMALL, INPUT_PULLUP); + // pinMode(DOOR, INPUT_PULLUP); + pinMode(L_WIFI, OUTPUT); + pinMode(L_WIFI2, OUTPUT); + pinMode(L_MQTT, OUTPUT); + pinMode(L_MSG, OUTPUT); + + digitalWrite(L_MQTT, HIGH); + digitalWrite(L_WIFI, HIGH); + + uint8_t pcfreg = pcf.read8(); + tP = pcfreg & 0x1; + iP = (pcfreg >> L_INT) & 0x1; + dP = (pcfreg >> L_DOWN) & 0x1; + sP = (pcfreg >> L_SMALL) & 0x1; + doorP = (pcfreg >> DOOR) & 0x1;// tP = digitalRead(L_TOP); + // iP = digitalRead(L_INT); + // dP = digitalRead(L_DOWN); + // sP = digitalRead(L_SMALL); + // EEPROM.begin(16); + // EEPROM.get(0, timeAlm); + // timeOpen = 0; + // doorSent = lockSent = false; + Serial.println("Connect to WiFi"); + connectToWifi(); + Serial.println("Loop"); +} + +void loop() { + // uint8_t tC = digitalRead(L_TOP); + // uint8_t iC = digitalRead(L_INT); + // uint8_t dC = digitalRead(L_DOWN); + // uint8_t sC = digitalRead(L_SMALL); + uint8_t tC, iC, dC, sC; + char v[10]; + //door = digitalRead(DOOR); + if(l_m && (l_run + 100) < millis()){ + analogWrite(L_MSG, 0); + l_m = false; + } + //r_led.tick(); + + ArduinoOTA.handle(); + + if(cRun + 99 < millis()){ + cRun = millis(); + pcfreg = pcf.read8(); + tC = (pcfreg >> L_TOP) & 0x1; + iC = (pcfreg >> L_INT) & 0x1; + dC = (pcfreg >> L_DOWN) & 0x1; + sC = (pcfreg >> L_SMALL) & 0x1; + door = (pcfreg >> DOOR) & 0x1; + if(opcfreg != pcfreg){ + itoa(pcfreg, v, 2); + mqttClient.publish("/home/kor/pcf", 1, false, v); + opcfreg = pcfreg; + } + + if(tC != tP){ + Serial.println("Top Changed"); + if(mqttClient.connected()){ + mqttClient.publish("/home/kor/locker_top", 1, false, tC ? "0" : "1"); + } + tP = tC; + } + if(iC != iP){ + if(mqttClient.connected()){ + mqttClient.publish("/home/kor/locker_int", 1, false, iC ? "0" : "1"); + } + iP = iC; + } + if(dC != dP){ + if(mqttClient.connected()){ + mqttClient.publish("/home/kor/locker_down", 1, false, dC ? "0" : "1"); + } + dP = dC; + } + if(sC != sP){ + if(mqttClient.connected()){ + mqttClient.publish("/home/kor/locker_small", 1, false, sC ? "0" : "1"); + } + sP = sC; + } + if(door != doorP){ + if(mqttClient.connected()){ + mqttClient.publish("/home/kor/door", 1, false, door ? "0" : "1"); + } + doorP = door; + } + + nSec++; + // if(nSec % 10 == 0){ + // char v[11]; + // itoa(pcfreg, v, 2); + // if(mqttClient.connected()) + // mqttClient.publish("/home/test/pcfreg", 0, false, v); + // } + if(nSec > 99){ + if(mqttClient.connected()){ + char v[11]; + itoa(millis(), v, 10); + analogWrite(L_MSG, 1); + l_run = millis(); + l_m = true; + //r_led.start(); + mqttClient.publish("/home/kor/doormillis", 1, false, v); + Serial.print("Millis: "); + Serial.println(millis()); + } + nSec = 0; + } +/* if((((tC == 0) && (iC == 0) && (dC == 0) && (sC == 0)) || (door == 0)) && ((timeOpen / 10) < timeAlm)){ + timeOpen++; + if((timeOpen / 10) >= timeAlm){ + if(mqttClient.connected()){ + if (door == 0){ //Door to long time open + r_led.start(); + mqttClient.publish("/home/kor/doorlong", 1, false, "1"); + doorSent = true; + } + else{ //Not closed locker + r_led.start(); + mqttClient.publish("/home/kor/doorlocker", 1, false, "0"); + lockSent = true; + } + } + } + } + else{ + timeOpen = 0; + if(doorSent == true){ + doorSent = false; + if(mqttClient.connected()) + r_led.start(); + mqttClient.publish("/home/kor/doorlong", 1, false, "0"); + } + if(lockSent == true){ + lockSent = false; + if(mqttClient.connected()) + r_led.start(); + mqttClient.publish("/home/kor/doorlocker", 1, false, "1"); + } + }*/ + } +} diff --git a/MainDoor/test/README b/MainDoor/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/MainDoor/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/Sw_BigRoom/.gitignore b/Sw_BigRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Sw_BigRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Sw_BigRoom/.travis.yml b/Sw_BigRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Sw_BigRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/Sw_BigRoom/.vscode/extensions.json b/Sw_BigRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Sw_BigRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/Sw_BigRoom/include/README b/Sw_BigRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Sw_BigRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Sw_BigRoom/lib/README b/Sw_BigRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Sw_BigRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Sw_BigRoom/platformio.ini b/Sw_BigRoom/platformio.ini new file mode 100644 index 0000000..d291a6e --- /dev/null +++ b/Sw_BigRoom/platformio.ini @@ -0,0 +1,17 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +board_build.ldscript = eagle.flash.2m.ld +upload_protocol = espota +upload_port = 192.168.1.129 \ No newline at end of file diff --git a/Sw_BigRoom/src/main.cpp b/Sw_BigRoom/src/main.cpp new file mode 100644 index 0000000..cdf60eb --- /dev/null +++ b/Sw_BigRoom/src/main.cpp @@ -0,0 +1,395 @@ +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include + +// // замените значения в этих константах на те, +// // что соответствуют вашей сети: +// const char* ssid = "wf-home"; +// const char* password = "0ndthnrf"; +// const char* mqtt_server = "192.168.1.250"; +// //unsigned long int cRun; +// bool lStat1; +// bool lStat2; +// #define B_LED 16 +// //bool led = false; + +// Bounce l1 = Bounce(); +// Bounce l2 = Bounce(); + +// WiFiClient espClient; +// PubSubClient client(espClient); + +// void callback(char* topic, byte* payload, unsigned int length) { +// Serial.print("Message arrived ["); +// Serial.print(topic); +// Serial.print("] "); +// for (unsigned int i = 0; i < length; i++) { +// Serial.print((char)payload[i]); +// } +// Serial.println(); +// if(strcmp(topic, "/home/bigroom/lamp1_set") == 0){ +// if ((char)payload[0] == '1') lStat1 = true; +// else lStat1 = false; +// EEPROM.put(0, lStat1); +// EEPROM.commit(); +// Serial.print("Lamp 1: "); +// Serial.println(lStat1); +// if (client.connected()) +// client.publish("/home/bigroom/lamp1", lStat1 ? "1" : "0"); +// //setLamp(0); +// } +// if(strcmp(topic, "/home/bigroom/lamp2_set") == 0){ +// if ((char)payload[0] == '1') lStat2 = true; +// else lStat2 = false; +// //setLamp(1); +// EEPROM.put(1, lStat2); +// EEPROM.commit(); +// Serial.print("Lamp 2: "); +// Serial.println(lStat2); +// if (client.connected()) +// client.publish("/home/bigroom/lamp2", lStat2 ? "1" : "0"); +// } + +// // Switch on the LED if an 1 was received as first character +// //if ((char)payload[0] == '1') { +// //digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level +// // but actually the LED is on; this is because +// // it is active low on the ESP-01) +// //} else { +// //digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH +// //} +// } + +// void reconnect() { +// // Loop until we're reconnected +// int cntConn = 0; +// int cntConnW = 0; +// while (!client.connected() && cntConn < 5) { +// if(!WiFi.isConnected()){ +// WiFi.disconnect(); +// WiFi.begin(ssid, password); +// while ((WiFi.waitForConnectResult() != WL_CONNECTED) && cntConn < 5) { +// Serial.println("Connection Failed! Rebooting..."); +// // "Соединиться не удалось! Перезагрузка..." +// delay(1000); +// cntConn++; +// } +// } +// Serial.print("Attempting MQTT connection..."); +// // Create a random client ID +// String clientId = "SwitchBigRoom"; +// //clientId += String(random(0xffff), HEX); +// // Attempt to connect +// if (client.connect(clientId.c_str())) { +// Serial.println("connected"); +// // Once connected, publish an announcement... +// //client.publish("outTopic", "hello world"); +// // ... and resubscribe +// client.subscribe("/home/bigroom/lamp1_set"); +// client.subscribe("/home/bigroom/lamp2_set"); +// digitalWrite(B_LED, LOW); +// } else { +// Serial.print("failed, rc="); +// Serial.print(client.state()); +// Serial.println(" try again in 5 seconds"); +// digitalWrite(B_LED, HIGH); +// // Wait 5 seconds before retrying +// //delay(5000); +// } +// cntConn++; +// } +// } + +// void setup() { +// Serial.begin(9600); +// Serial.println("Booting"); // "Загрузка" +// WiFi.mode(WIFI_STA); +// WiFi.hostname("SW-BigRoom"); +// WiFi.begin(ssid, password); +// int cntConn = 0; +// while ((WiFi.waitForConnectResult() != WL_CONNECTED) && cntConn < 5) { +// Serial.println("Connection Failed! Rebooting..."); +// // "Соединиться не удалось! Перезагрузка..." +// delay(1000); +// cntConn++; +// ESP.restart(); +// } + +// // строчка для номера порта по умолчанию +// // можно вписать «8266»: +// // ArduinoOTA.setPort(8266); + +// // строчка для названия хоста по умолчанию; +// // можно вписать «esp8266-[ID чипа]»: +// // ArduinoOTA.setHostname("myesp8266"); + +// // строчка для аутентификации +// // (по умолчанию никакой аутентификации не будет): +// // ArduinoOTA.setPassword((const char *)"123"); + +// ArduinoOTA.onStart([]() { +// Serial.println("Start"); // "Начало OTA-апдейта" + +// }); +// ArduinoOTA.onEnd([]() { +// Serial.println("\nEnd"); // "Завершение OTA-апдейта" +// }); +// ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { +// Serial.printf("Progress: %u%%\r", (progress / (total / 100))); +// }); +// ArduinoOTA.onError([](ota_error_t error) { +// Serial.printf("Error[%u]: ", error); +// if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); +// // "Ошибка при аутентификации" +// else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); +// // "Ошибка при начале OTA-апдейта" +// else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); +// // "Ошибка при подключении" +// else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); +// // "Ошибка при получении данных" +// else if (error == OTA_END_ERROR) Serial.println("End Failed"); +// // "Ошибка при завершении OTA-апдейта" +// }); +// ArduinoOTA.begin(); +// Serial.println("Ready"); // "Готово" +// Serial.print("IP address: "); // "IP-адрес: " +// Serial.println(WiFi.localIP()); +// //pinMode(0, INPUT_PULLUP); +// //l1.attach(0); +// pinMode(B_LED, OUTPUT); +// pinMode(4, OUTPUT); +// pinMode(13, OUTPUT); +// pinMode(14, INPUT); +// l1.attach(14); +// pinMode(12, INPUT); +// l2.attach(12); +// lStat1 = false; +// lStat2 = false; +// client.setServer(mqtt_server, 1883); +// client.setCallback(callback); +// EEPROM.begin(16); +// EEPROM.get(0, lStat1); +// EEPROM.get(1, lStat2); + +// //cRun = millis(); +// } + +// void loop() { +// ArduinoOTA.handle(); + +// digitalWrite(4, lStat1); +// digitalWrite(13, lStat2); +// if (!client.connected()) { +// reconnect(); +// } +// client.loop(); + +// l1.update(); +// l2.update(); +// if(l1.fell()){ +// lStat1 = !lStat1; +// //digitalWrite(4, lStat1); +// EEPROM.put(0, lStat1); +// EEPROM.commit(); +// Serial.print("Lamp 1: "); +// Serial.println(lStat1); +// if (client.connected()) +// client.publish("/home/bigroom/lamp1", String(lStat1).c_str()); +// } +// if(l2.fell()){ +// lStat2 = !lStat2; +// //digitalWrite(13, lStat2); +// EEPROM.put(1, lStat2); +// EEPROM.commit(); +// Serial.print("Lamp 2: "); +// Serial.println(lStat2); +// if (client.connected()) +// client.publish("/home/bigroom/lamp2", String(lStat2).c_str()); +// } +// // if(cRun + 500 < millis()){ +// // digitalWrite(B_LED, led); +// // led = !led; +// // cRun = millis(); +// // } +// } + + +#include +#include +#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +bool lStat1, oldLStat1; +bool lStat2, oldLStat2; +unsigned long cRun; +#define B_LED (16) +#define R_LED1 (4) +#define R_LED2 (13) +#define BUTT1 (14) +#define BUTT2 (12) +bool led = false; + +Bounce l1 = Bounce(); +Bounce l2 = Bounce(); + +void connectToWifi() { + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + mqttClient.subscribe("/home/bigroom/lamp1_set", 1); + mqttClient.subscribe("/home/bigroom/lamp2_set", 1); + mqttClient.publish("/home/bigroom/lamp1", 1, false, lStat1 ? "1" : "0"); + mqttClient.publish("/home/bigroom/lamp2", 1, false, lStat2 ? "1" : "0"); + digitalWrite(B_LED, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(B_LED, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { +} + +void onMqttUnsubscribe(uint16_t packetId) { +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/bigroom/lamp1_set") == 0){ + if ((char)payload[0] == '1') lStat1 = true; + else lStat1 = false; + } + if(strcmp(topic, "/home/bigroom/lamp2_set") == 0){ + if ((char)payload[0] == '1') lStat2 = true; + else lStat2 = false; + } +} + +void onMqttPublish(uint16_t packetId) { +} + +void setup() { + WiFi.mode(WIFI_STA); + WiFi.hostname("SW-BigRoom"); + ArduinoOTA.onStart([]() { + }); + ArduinoOTA.onEnd([]() { + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // Serial.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + //pinMode(B_LED, FUNCTION_3); + pinMode(B_LED, OUTPUT); + digitalWrite(B_LED, HIGH); + pinMode(R_LED1, OUTPUT); + pinMode(BUTT1, INPUT_PULLUP); + pinMode(R_LED2, OUTPUT); + pinMode(BUTT2, FUNCTION_3); + pinMode(BUTT2, INPUT_PULLUP); + l1.attach(BUTT1); + l2.attach(BUTT2); + + + EEPROM.begin(16); + EEPROM.get(0, lStat1); + EEPROM.get(1, lStat2); + oldLStat1 = lStat1; + oldLStat2 = lStat2; + // Serial.print("Lamp1: "); + // Serial.println(lStat1); + digitalWrite(R_LED1, lStat1); + digitalWrite(R_LED2, lStat2); + //oldLStat2 = lStat2; + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + connectToWifi(); + + cRun = millis(); +} + +void loop() { + ArduinoOTA.handle(); + l1.update(); + l2.update(); + if(l1.fell()){ + lStat1 = !lStat1; + } + if(l2.fell()){ + lStat2 = !lStat2; + } + if(lStat1 != oldLStat1){ + digitalWrite(R_LED1, lStat1); + oldLStat1 = lStat1; + mqttClient.publish("/home/bigroom/lamp1", 1, false, lStat1 ? "1" : "0"); + EEPROM.put(0, lStat1); + EEPROM.commit(); + } + if(lStat2 != oldLStat2){ + digitalWrite(R_LED2, lStat2); + oldLStat2 = lStat2; + mqttClient.publish("/home/bigroom/lamp2", 1, false, lStat2 ? "1" : "0"); + EEPROM.put(1, lStat2); + EEPROM.commit(); + } +} + + diff --git a/Sw_BigRoom/test/README b/Sw_BigRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Sw_BigRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/Sw_Koridor/.gitignore b/Sw_Koridor/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Sw_Koridor/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Sw_Koridor/.travis.yml b/Sw_Koridor/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Sw_Koridor/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/Sw_Koridor/.vscode/extensions.json b/Sw_Koridor/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Sw_Koridor/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/Sw_Koridor/include/README b/Sw_Koridor/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Sw_Koridor/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Sw_Koridor/lib/README b/Sw_Koridor/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Sw_Koridor/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Sw_Koridor/platformio.ini b/Sw_Koridor/platformio.ini new file mode 100644 index 0000000..00975ba --- /dev/null +++ b/Sw_Koridor/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = esp12e +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m128.ld +board_build.flash_mode = dout +upload_protocol = espota +upload_port = 192.168.1.130 \ No newline at end of file diff --git a/Sw_Koridor/src/main.cpp b/Sw_Koridor/src/main.cpp new file mode 100644 index 0000000..9946888 --- /dev/null +++ b/Sw_Koridor/src/main.cpp @@ -0,0 +1,208 @@ +/********* + Руи Сантос (Rui Santos) + Более подробно о проекте на: http://randomnerdtutorials.com + Пример в IDE Arduino: File > Examples > Arduino OTA > BasicOTA.ino + (Файл > Примеры > Arduino OTA > BasicOTA.ino) +*********/ +#include +#include +#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +bool lStat1, oldLStat1; +bool lStat2, oldLStat2; +unsigned long cRun; +#define B_LED (1) +#define R_LED (12) +#define BUTT (5) +bool led = false; + +OneButton button(BUTT); + +void connectToWifi() { + //Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + //Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + //Serial.println("Connected to Wi-Fi."); + //Serial.print("IP: "); + //Serial.println(WiFi.localIP()); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + //Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + // Serial.println("Connected to MQTT."); + // Serial.print("Session present: "); + // Serial.println(sessionPresent); + //uint16_t packetIdSub = + mqttClient.subscribe("/home/kor/lamp1_set", 1); + // Serial.print("Subscribing Lamp1, packetId: "); + // Serial.println(packetIdSub); + //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); + //Serial.print("Subscribing Lamp2, packetId: "); + //Serial.println(packetIdSub); + mqttClient.publish("/home/kor/lamp1", 1, false, lStat1 ? "1" : "0"); + //Serial.println("Publishing at Lamp 1"); + //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); + //Serial.println("Publishing at Lamp 2"); + digitalWrite(B_LED, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(B_LED, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + // Serial.println("Subscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); + // Serial.print(" qos: "); + // Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + // Serial.println("Unsubscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/kor/lamp1_set") == 0){ + if ((char)payload[0] == '1') lStat1 = true; + else lStat1 = false; + } +} + +void onMqttPublish(uint16_t packetId) { + // Serial.println("Publish acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); +} + +// void ICACHE_RAM_ATTR sw_func() +// { +// lStat1 = !lStat1; +// } + +void oneClick() +{ + lStat1 = !lStat1; +} + +void longPress() +{ + lStat1 = false; + mqttClient.publish("/home/bigroom/lamp1_set", 1, false, "0"); + mqttClient.publish("/home/bigroom/lamp2_set", 1, false, "0"); + mqttClient.publish("/home/midroom/lamp1_set", 1, false, "0"); + mqttClient.publish("/home/midroom/lamp2_set", 1, false, "0"); + mqttClient.publish("/home/smallroom/lamp1_set", 1, false, "0"); + mqttClient.publish("/home/smallroom/lamp2_set", 1, false, "0"); +} + +void setup() { + // Serial.begin(9600); + // Serial.println("Booting"); // "Загрузка" + WiFi.mode(WIFI_STA); + WiFi.hostname("SW-Koridor"); + ArduinoOTA.onStart([]() { + // Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + // Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // Serial.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + pinMode(B_LED, FUNCTION_3); + pinMode(B_LED, OUTPUT); + digitalWrite(B_LED, HIGH); + pinMode(R_LED, OUTPUT); + pinMode(BUTT, INPUT_PULLUP); + EEPROM.begin(16); + EEPROM.get(0, lStat1); + oldLStat1 = lStat1; + // Serial.print("Lamp1: "); + // Serial.println(lStat1); + digitalWrite(R_LED, lStat1); + //oldLStat2 = lStat2; + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + button.attachClick(oneClick); + button.attachLongPressStart(longPress); + button.setPressTicks(2000); + + //attachInterrupt(digitalPinToInterrupt(BUTT), sw_func, RISING); + + connectToWifi(); + + cRun = millis(); +} + +void loop() { + ArduinoOTA.handle(); + button.tick(); + if(lStat1 != oldLStat1){ + digitalWrite(R_LED, lStat1); + oldLStat1 = lStat1; + mqttClient.publish("/home/kor/lamp1", 1, false, lStat1 ? "1" : "0"); + EEPROM.put(0, lStat1); + EEPROM.commit(); + } +} + diff --git a/Sw_Koridor/test/README b/Sw_Koridor/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Sw_Koridor/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/Sw_MidlRoom/.gitignore b/Sw_MidlRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Sw_MidlRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Sw_MidlRoom/.travis.yml b/Sw_MidlRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Sw_MidlRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/Sw_MidlRoom/.vscode/extensions.json b/Sw_MidlRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Sw_MidlRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/Sw_MidlRoom/include/README b/Sw_MidlRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Sw_MidlRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Sw_MidlRoom/lib/README b/Sw_MidlRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Sw_MidlRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Sw_MidlRoom/platformio.ini b/Sw_MidlRoom/platformio.ini new file mode 100644 index 0000000..fd27b9f --- /dev/null +++ b/Sw_MidlRoom/platformio.ini @@ -0,0 +1,17 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +board_build.ldscript = eagle.flash.2m.ld +upload_protocol = espota +upload_port = 192.168.1.9 \ No newline at end of file diff --git a/Sw_MidlRoom/src/main.cpp b/Sw_MidlRoom/src/main.cpp new file mode 100644 index 0000000..9b4f697 --- /dev/null +++ b/Sw_MidlRoom/src/main.cpp @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +bool lStat1, oldLStat1; +bool lStat2, oldLStat2; +unsigned long cRun; +#define B_LED (16) +#define R_LED1 (4) +#define R_LED2 (13) +#define BUTT1 (14) +#define BUTT2 (12) +bool led = false; + +Bounce l1 = Bounce(); +Bounce l2 = Bounce(); + +void connectToWifi() { + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + mqttClient.subscribe("/home/midroom/lamp1_set", 1); + mqttClient.subscribe("/home/midroom/lamp2_set", 1); + mqttClient.publish("/home/midroom/lamp1", 1, false, lStat1 ? "1" : "0"); + mqttClient.publish("/home/midroom/lamp2", 1, false, lStat2 ? "1" : "0"); + digitalWrite(B_LED, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(B_LED, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { +} + +void onMqttUnsubscribe(uint16_t packetId) { +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/midroom/lamp1_set") == 0){ + if ((char)payload[0] == '1') lStat1 = true; + else lStat1 = false; + } + if(strcmp(topic, "/home/midroom/lamp2_set") == 0){ + if ((char)payload[0] == '1') lStat2 = true; + else lStat2 = false; + } +} + +void onMqttPublish(uint16_t packetId) { +} + +void setup() { + WiFi.mode(WIFI_STA); + WiFi.hostname("SW-MidRoom"); + ArduinoOTA.onStart([]() { + }); + ArduinoOTA.onEnd([]() { + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // Serial.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + //pinMode(B_LED, FUNCTION_3); + pinMode(B_LED, OUTPUT); + digitalWrite(B_LED, HIGH); + pinMode(R_LED1, OUTPUT); + pinMode(BUTT1, INPUT_PULLUP); + pinMode(R_LED2, OUTPUT); + pinMode(BUTT2, FUNCTION_3); + pinMode(BUTT2, INPUT_PULLUP); + l1.attach(BUTT1); + l2.attach(BUTT2); + + + EEPROM.begin(16); + EEPROM.get(0, lStat1); + EEPROM.get(1, lStat2); + oldLStat1 = lStat1; + oldLStat2 = lStat2; + // Serial.print("Lamp1: "); + // Serial.println(lStat1); + digitalWrite(R_LED1, lStat1); + digitalWrite(R_LED2, lStat2); + //oldLStat2 = lStat2; + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + connectToWifi(); + + cRun = millis(); +} + +void loop() { + ArduinoOTA.handle(); + l1.update(); + l2.update(); + if(l1.fell()){ + lStat1 = !lStat1; + } + if(l2.fell()){ + lStat2 = !lStat2; + } + if(lStat1 != oldLStat1){ + digitalWrite(R_LED1, lStat1); + oldLStat1 = lStat1; + mqttClient.publish("/home/midroom/lamp1", 1, false, lStat1 ? "1" : "0"); + EEPROM.put(0, lStat1); + EEPROM.commit(); + } + if(lStat2 != oldLStat2){ + digitalWrite(R_LED2, lStat2); + oldLStat2 = lStat2; + mqttClient.publish("/home/midroom/lamp2", 1, false, lStat2 ? "1" : "0"); + EEPROM.put(1, lStat2); + EEPROM.commit(); + } +} + + + + +///////////////////////////////////////////////////// + + +// /********* +// Руи Сантос (Rui Santos) +// Более подробно о проекте на: http://randomnerdtutorials.com +// Пример в IDE Arduino: File > Examples > Arduino OTA > BasicOTA.ino +// (Файл > Примеры > Arduino OTA > BasicOTA.ino) +// *********/ +// #include +// #include +// #include +// #include +// #include +// #include +// #include +// #include + +// // замените значения в этих константах на те, +// // что соответствуют вашей сети: +// const char* ssid = "wf-home"; +// const char* password = "0ndthnrf"; +// const char* mqtt_server = "192.168.1.250"; +// //unsigned long int cRun; +// bool lStat1; +// bool lStat2; +// #define B_LED 16 +// //bool led = false; + +// Bounce l1 = Bounce(); +// Bounce l2 = Bounce(); + +// WiFiClient espClient; +// PubSubClient client(espClient); + +// void callback(char* topic, byte* payload, unsigned int length) { +// Serial.print("Message arrived ["); +// Serial.print(topic); +// Serial.print("] "); +// for (unsigned int i = 0; i < length; i++) { +// Serial.print((char)payload[i]); +// } +// Serial.println(); +// if(strcmp(topic, "/home/midroom/lamp1_set") == 0){ +// if ((char)payload[0] == '1') lStat1 = true; +// else lStat1 = false; +// EEPROM.put(0, lStat1); +// EEPROM.commit(); +// Serial.print("Lamp 1: "); +// Serial.println(lStat1); +// if (client.connected()) +// client.publish("/home/midroom/lamp1", lStat1 ? "1" : "0"); +// //setLamp(0); +// } +// if(strcmp(topic, "/home/midroom/lamp2_set") == 0){ +// if ((char)payload[0] == '1') lStat2 = true; +// else lStat2 = false; +// //setLamp(1); +// EEPROM.put(1, lStat2); +// EEPROM.commit(); +// Serial.print("Lamp 2: "); +// Serial.println(lStat2); +// if (client.connected()) +// client.publish("/home/midroom/lamp2", lStat2 ? "1" : "0"); +// } + +// // Switch on the LED if an 1 was received as first character +// //if ((char)payload[0] == '1') { +// //digitalWrite(LED_BUILTIN, LOW); // Turn the LED on (Note that LOW is the voltage level +// // but actually the LED is on; this is because +// // it is active low on the ESP-01) +// //} else { +// //digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off by making the voltage HIGH +// //} +// } + +// void reconnect() { +// // Loop until we're reconnected +// int cntConn = 0; +// while (!client.connected() && cntConn < 5) { +// Serial.print("Attempting MQTT connection..."); +// // Create a random client ID +// String clientId = "SwitchMidRoom"; +// //clientId += String(random(0xffff), HEX); +// // Attempt to connect +// if (client.connect(clientId.c_str())) { +// Serial.println("connected"); +// // Once connected, publish an announcement... +// //client.publish("outTopic", "hello world"); +// // ... and resubscribe +// client.subscribe("/home/midroom/lamp1_set"); +// client.subscribe("/home/midroom/lamp2_set"); +// digitalWrite(B_LED, LOW); +// } else { +// Serial.print("failed, rc="); +// Serial.print(client.state()); +// Serial.println(" try again in 5 seconds"); +// digitalWrite(B_LED, HIGH); +// // Wait 5 seconds before retrying +// //delay(5000); +// } +// cntConn++; +// } +// } + +// void setup() { +// Serial.begin(9600); +// Serial.println("Booting"); // "Загрузка" +// WiFi.mode(WIFI_STA); +// WiFi.hostname("SW-MidRoom"); +// WiFi.begin(ssid, password); +// int cntConn = 0; +// while ((WiFi.waitForConnectResult() != WL_CONNECTED) && cntConn < 5) { +// Serial.println("Connection Failed! Rebooting..."); +// // "Соединиться не удалось! Перезагрузка..." +// delay(1000); +// cntConn++; +// ESP.restart(); +// } + +// // строчка для номера порта по умолчанию +// // можно вписать «8266»: +// // ArduinoOTA.setPort(8266); + +// // строчка для названия хоста по умолчанию; +// // можно вписать «esp8266-[ID чипа]»: +// // ArduinoOTA.setHostname("myesp8266"); + +// // строчка для аутентификации +// // (по умолчанию никакой аутентификации не будет): +// // ArduinoOTA.setPassword((const char *)"123"); + +// ArduinoOTA.onStart([]() { +// Serial.println("Start"); // "Начало OTA-апдейта" + +// }); +// ArduinoOTA.onEnd([]() { +// Serial.println("\nEnd"); // "Завершение OTA-апдейта" +// }); +// ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { +// Serial.printf("Progress: %u%%\r", (progress / (total / 100))); +// }); +// ArduinoOTA.onError([](ota_error_t error) { +// Serial.printf("Error[%u]: ", error); +// if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); +// // "Ошибка при аутентификации" +// else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); +// // "Ошибка при начале OTA-апдейта" +// else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); +// // "Ошибка при подключении" +// else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); +// // "Ошибка при получении данных" +// else if (error == OTA_END_ERROR) Serial.println("End Failed"); +// // "Ошибка при завершении OTA-апдейта" +// }); +// ArduinoOTA.begin(); +// Serial.println("Ready"); // "Готово" +// Serial.print("IP address: "); // "IP-адрес: " +// Serial.println(WiFi.localIP()); +// //pinMode(0, INPUT_PULLUP); +// //l1.attach(0); +// pinMode(B_LED, OUTPUT); +// pinMode(4, OUTPUT); +// pinMode(13, OUTPUT); +// pinMode(14, INPUT); +// l1.attach(14); +// pinMode(12, INPUT); +// l2.attach(12); +// lStat1 = false; +// lStat2 = false; +// client.setServer(mqtt_server, 1883); +// client.setCallback(callback); +// EEPROM.begin(16); +// EEPROM.get(0, lStat1); +// EEPROM.get(1, lStat2); + +// //cRun = millis(); +// } + +// void loop() { +// ArduinoOTA.handle(); + +// digitalWrite(4, lStat1); +// digitalWrite(13, lStat2); +// if (!client.connected()) { +// reconnect(); +// } +// client.loop(); + +// l1.update(); +// l2.update(); +// if(l1.fell()){ +// lStat1 = !lStat1; +// //digitalWrite(4, lStat1); +// EEPROM.put(0, lStat1); +// EEPROM.commit(); +// Serial.print("Lamp 1: "); +// Serial.println(lStat1); +// if (client.connected()) +// client.publish("/home/midroom/lamp1", String(lStat1).c_str()); +// } +// if(l2.fell()){ +// lStat2 = !lStat2; +// //digitalWrite(13, lStat2); +// EEPROM.put(1, lStat2); +// EEPROM.commit(); +// Serial.print("Lamp 2: "); +// Serial.println(lStat2); +// if (client.connected()) +// client.publish("/home/midroom/lamp2", String(lStat2).c_str()); +// } +// // if(cRun + 500 < millis()){ +// // digitalWrite(B_LED, led); +// // led = !led; +// // cRun = millis(); +// // } +// } diff --git a/Sw_MidlRoom/test/README b/Sw_MidlRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Sw_MidlRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/Sw_SmallRoom/.gitignore b/Sw_SmallRoom/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Sw_SmallRoom/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Sw_SmallRoom/.travis.yml b/Sw_SmallRoom/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/Sw_SmallRoom/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/Sw_SmallRoom/.vscode/extensions.json b/Sw_SmallRoom/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/Sw_SmallRoom/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/Sw_SmallRoom/include/README b/Sw_SmallRoom/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/Sw_SmallRoom/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/Sw_SmallRoom/lib/README b/Sw_SmallRoom/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/Sw_SmallRoom/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/Sw_SmallRoom/platformio.ini b/Sw_SmallRoom/platformio.ini new file mode 100644 index 0000000..3c927db --- /dev/null +++ b/Sw_SmallRoom/platformio.ini @@ -0,0 +1,19 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = esp12e +framework = arduino +board_build.f_cpu = 26000000L +board_build.ldscript = eagle.flash.1m128.ld +board_build.flash_mode = dout +upload_protocol = espota +upload_port = 192.168.1.150 \ No newline at end of file diff --git a/Sw_SmallRoom/src/main.cpp b/Sw_SmallRoom/src/main.cpp new file mode 100644 index 0000000..ed5c953 --- /dev/null +++ b/Sw_SmallRoom/src/main.cpp @@ -0,0 +1,223 @@ +/********* + Руи Сантос (Rui Santos) + Более подробно о проекте на: http://randomnerdtutorials.com + Пример в IDE Arduino: File > Examples > Arduino OTA > BasicOTA.ino + (Файл > Примеры > Arduino OTA > BasicOTA.ino) +*********/ +#include +#include +#include +#include +#include +#include + +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; +const char* mqtt_server = "192.168.1.250"; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; + +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +bool lStat1, oldLStat1; +bool lStat2, oldLStat2; +unsigned long cRun; +#define B_LED (1) +#define R_LED1 (14) +#define R_LED2 (13) +#define BUTT1 (4) +#define BUTT2 (3) +bool led = false; + +Bounce l1 = Bounce(); +Bounce l2 = Bounce(); + +void connectToWifi() { + //Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(ssid, password); +} + +void connectToMqtt() { + //Serial.println("Connecting to MQTT..."); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + //Serial.println("Connected to Wi-Fi."); + //Serial.print("IP: "); + //Serial.println(WiFi.localIP()); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + //Serial.println("Disconnected from Wi-Fi."); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); +} + +void onMqttConnect(bool sessionPresent) { + // Serial.println("Connected to MQTT."); + // Serial.print("Session present: "); + // Serial.println(sessionPresent); + //uint16_t packetIdSub = + mqttClient.subscribe("/home/smallroom/lamp1_set", 1); + mqttClient.subscribe("/home/smallroom/lamp2_set", 1); + // Serial.print("Subscribing Lamp1, packetId: "); + // Serial.println(packetIdSub); + //packetIdSub = mqttClient.subscribe("/home/kor/lamp2_set", 1); + //Serial.print("Subscribing Lamp2, packetId: "); + //Serial.println(packetIdSub); + mqttClient.publish("/home/smallroom/lamp1", 1, false, lStat1 ? "1" : "0"); + mqttClient.publish("/home/smallroom/lamp2", 1, false, lStat2 ? "1" : "0"); + //Serial.println("Publishing at Lamp 1"); + //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); + //Serial.println("Publishing at Lamp 2"); + digitalWrite(B_LED, LOW); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + //Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(B_LED, HIGH); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + // Serial.println("Subscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); + // Serial.print(" qos: "); + // Serial.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + // Serial.println("Unsubscribe acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/smallroom/lamp1_set") == 0){ + if ((char)payload[0] == '1') lStat1 = true; + else lStat1 = false; + } + if(strcmp(topic, "/home/smallroom/lamp2_set") == 0){ + if ((char)payload[0] == '1') lStat2 = true; + else lStat2 = false; + } +} + +void onMqttPublish(uint16_t packetId) { + // Serial.println("Publish acknowledged."); + // Serial.print(" packetId: "); + // Serial.println(packetId); +} + +void setup() { + //Serial.begin(9600); + //Serial.println("Booting"); // "Загрузка" + WiFi.mode(WIFI_STA); + WiFi.hostname("SW-SmallRoom1"); + ArduinoOTA.onStart([]() { + // Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + // Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + // Serial.printf("Error[%u]: ", error); + // if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // // "Ошибка при аутентификации" + // else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // // "Ошибка при начале OTA-апдейта" + // else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // // "Ошибка при подключении" + // else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // // "Ошибка при получении данных" + // else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); + + + + + pinMode(B_LED, FUNCTION_3); + pinMode(B_LED, OUTPUT); + digitalWrite(B_LED, HIGH); + pinMode(R_LED1, OUTPUT); + pinMode(BUTT1, INPUT_PULLUP); + pinMode(R_LED2, OUTPUT); + pinMode(BUTT2, FUNCTION_3); + pinMode(BUTT2, INPUT_PULLUP); + l1.attach(BUTT1); + l2.attach(BUTT2); + + + EEPROM.begin(16); + EEPROM.get(0, lStat1); + EEPROM.get(1, lStat2); + oldLStat1 = lStat1; + oldLStat2 = lStat2; + // Serial.print("Lamp1: "); + // Serial.println(lStat1); + digitalWrite(R_LED1, lStat1); + digitalWrite(R_LED2, lStat2); + //oldLStat2 = lStat2; + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + connectToWifi(); + + cRun = millis(); +} + +void loop() { + ArduinoOTA.handle(); + l1.update(); + l2.update(); + if(l1.fell()){ + lStat1 = !lStat1; + } + if(l2.fell()){ + lStat2 = !lStat2; + } + if(lStat1 != oldLStat1){ + digitalWrite(R_LED1, lStat1); + oldLStat1 = lStat1; + mqttClient.publish("/home/smallroom/lamp1", 1, false, lStat1 ? "1" : "0"); + // Serial.println("Publishing at Lamp 1"); + EEPROM.put(0, lStat1); + EEPROM.commit(); + // Serial.print("Lamp 1: "); + // Serial.println(lStat1); + } + if(lStat2 != oldLStat2){ + digitalWrite(R_LED2, lStat2); + oldLStat2 = lStat2; + mqttClient.publish("/home/smallroom/lamp2", 1, false, lStat2 ? "1" : "0"); + // Serial.println("Publishing at Lamp 1"); + EEPROM.put(1, lStat2); + EEPROM.commit(); + // Serial.print("Lamp 1: "); + // Serial.println(lStat1); + } +} + diff --git a/Sw_SmallRoom/test/README b/Sw_SmallRoom/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/Sw_SmallRoom/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/VT_ESP8266/.gitignore b/VT_ESP8266/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/VT_ESP8266/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/VT_ESP8266/.travis.yml b/VT_ESP8266/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/VT_ESP8266/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/VT_ESP8266/.vscode/extensions.json b/VT_ESP8266/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/VT_ESP8266/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/VT_ESP8266/include/README b/VT_ESP8266/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/VT_ESP8266/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/VT_ESP8266/include/leds.h b/VT_ESP8266/include/leds.h new file mode 100644 index 0000000..239cfe4 --- /dev/null +++ b/VT_ESP8266/include/leds.h @@ -0,0 +1,21 @@ +#ifndef __LEDS_H__ +#define __LEDS_H__ +#include +#include + +class leds +{ +private: + int ledPin; + bool inv, state; + int onMS; + unsigned long curMS; + PCF8574 *_pcf; +public: + leds(PCF8574 *pcf, int ledPin, int onms = 300, bool inverse = false); + //~leds(); + void start(); + void tick(); +}; + +#endif \ No newline at end of file diff --git a/VT_ESP8266/include/main.h b/VT_ESP8266/include/main.h new file mode 100644 index 0000000..18901fb --- /dev/null +++ b/VT_ESP8266/include/main.h @@ -0,0 +1,119 @@ +#include +#include +#include +#include "ClosedCube_HDC1080.h" +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include + +#define DEBUG +#define WIFI_SSID "wf-home" +#define WIFI_PASSWORD "0ndthnrf" +#define MY_HOSTNAME "ESP8266_GW" +#define MQTT_SERV "192.168.1.250" + +#define MAX_PAGE (4) +#define MAX_HSP (99) +#define MAX_HDB (99) +#define MAX_TWORK (99) +#define MAX_TPAUSE (99) +#define MAX_LCDPAUSE (99) + +//#define LIGHT_SENS D0 +#define VENT_VANNA (D0) +#define ASDA (D1) +#define ASCL (D2) +#define ENC_A (D3) +#define ENC_B (D4) +#define ONE_WIRE (D5) +#define VENT_TUAL (D6) +#define BUTT_ENC (D7) + +#define LIGHT_SENS (0) +#define LED_RED (4) +#define LED_BLUE (5) +#define LED_GREEN (6) +#define LED_YELLOW (7) +#define FLOOD (1) +#define Q_C (3) +#define Q_H (2) + +ClosedCube_HDC1080 hdc1080; + +unsigned long cRun; +int8_t page; +float hum, temp; +float cTemp, hTemp; +uint8_t pcf_w; +uint8_t LCDtimeout, LCDsec; +bool modeEdit; +uint8_t itemEdit; +uint16_t adc; +float mws; +long curPos; +bool vvannaSent1, vvannaSent0; + +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; +const char* mqtt_server = "192.168.1.250"; +char v[12]; + +struct contacts +{ + bool QC; + bool QH; + bool Flood; +} wconts; + +struct wCnt +{ + float QC; + float QH; +} wCounter, oldwCounter; + +struct wUst{ + uint8_t hSP; + uint8_t hDB; +} wUstavki, oldwUstavki; + +struct stTualVent +{ + uint8_t tWork; + uint8_t tPause; +} ventUst, oldventUst; + +void printSerialNumber(); +void buttClick(); +void chkCount(); +// void callback(char* topic, byte* payload, unsigned int length); +// void reconnect(); +void showLCD(uint8_t page, bool chgd); +void chkEnc(); +void getTemps(); +void buttLongClick(); +void chkLight(); +void connectToWifi(); +void connectToMqtt(); + +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void onMqttConnect(bool sessionPresent); +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason); +void onMqttSubscribe(uint16_t packetId, uint8_t qos); +void onMqttUnsubscribe(uint16_t packetId); +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total); +void onMqttPublish(uint16_t packetId); + +void sendData(); diff --git a/VT_ESP8266/include/pcf_butt.h b/VT_ESP8266/include/pcf_butt.h new file mode 100644 index 0000000..b79fdc4 --- /dev/null +++ b/VT_ESP8266/include/pcf_butt.h @@ -0,0 +1,18 @@ +#ifndef __PCF_BUTT__ +#define __PCF_BUTT__ + +class pcf_butt +{ +private: + bool lastState; + bool curState; +public: + pcf_butt(); + pcf_butt(bool state); + void update(bool state); + bool chngUp(bool state); + bool chngDown(bool state); + ~pcf_butt(); +}; + +#endif diff --git a/VT_ESP8266/lib/README b/VT_ESP8266/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/VT_ESP8266/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/VT_ESP8266/platformio.ini b/VT_ESP8266/platformio.ini new file mode 100644 index 0000000..a822239 --- /dev/null +++ b/VT_ESP8266/platformio.ini @@ -0,0 +1,17 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +monitor_speed = 115200 +upload_protocol = espota +upload_port = 192.168.1.134 \ No newline at end of file diff --git a/VT_ESP8266/src/leds.cpp b/VT_ESP8266/src/leds.cpp new file mode 100644 index 0000000..9899a66 --- /dev/null +++ b/VT_ESP8266/src/leds.cpp @@ -0,0 +1,27 @@ +#include + +leds::leds(PCF8574 *pcf, int pinLED, int onms, bool inverse) +{ + _pcf = pcf; + ledPin = pinLED; + inv = inverse; + onMS = onms; + state = false; +} + +void leds::start() +{ + curMS = millis(); + state = true; + _pcf->write(ledPin, !inv); + //digitalWrite(ledPin, !inv); +} + +void leds::tick() +{ + if(state && ((curMS + onMS) < millis())){ + state = false; + _pcf->write(ledPin, inv); + //digitalWrite(ledPin, inv); + } +} diff --git a/VT_ESP8266/src/main.cpp b/VT_ESP8266/src/main.cpp new file mode 100644 index 0000000..d209859 --- /dev/null +++ b/VT_ESP8266/src/main.cpp @@ -0,0 +1,743 @@ +#include + +RotaryEncoder encoder(ENC_B, ENC_A); +OneButton button(BUTT_ENC, true); + +LiquidCrystal_PCF8574 lcd(0x27); +PCF8574 pcf(0x38); +I2C_eeprom ee(0x50, 0x1000); + +OneWire oneWire(ONE_WIRE); +DallasTemperature sensors(&oneWire); + +WiFiClient espClient; +//PubSubClient client(espClient); + +pcf_butt c_qc; +pcf_butt c_qh; +pcf_butt c_flood; + +//leds ledRed(&pcf, LED_RED, 300, true); +leds ledGreen(&pcf, LED_GREEN, 300, true); +//leds ledBlue(&pcf, LED_BLUE, 100, true); +//leds ledYellow(&pcf, LED_YELLOW, 100, true); +//leds pin0(&pcf, 0, 100, true); + +bool led = false; +uint16_t cnt = 0; + +void setup() +{ + Serial.begin(115200); + lcd.begin(16, 2); + lcd.setBacklight(255); + lcd.setCursor(0, 0); + lcd.print(F("Booting")); + + WiFi.hostname("VT_ESP"); + // WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + // if(WiFi.waitForConnectResult() == WL_CONNECTED){ + // delay(500); + // Serial.print("."); + // } + // Serial.println(""); + // lcd.clear(); + // lcd.setCursor(0, 0); + // lcd.print(F("Conn.to wf-home")); + // lcd.setCursor(0, 1); + // //lcd.print("IP address: "); + // lcd.println(WiFi.localIP()); + // Serial.println(WiFi.localIP()); + + ArduinoOTA.onStart([]() { + Serial.println(F("ArduinoOTA start")); + }); + ArduinoOTA.onEnd([]() { + Serial.println(F("\nArduinoOTA end")); + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("OTA Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) { + Serial.println(F("Auth Failed")); + } else if (error == OTA_BEGIN_ERROR) { + Serial.println(F("Begin Failed")); + } else if (error == OTA_CONNECT_ERROR) { + Serial.println(F("Connect Failed")); + } else if (error == OTA_RECEIVE_ERROR) { + Serial.println(F("Receive Failed")); + } else if (error == OTA_END_ERROR) { + Serial.println(F("End Failed")); + } + }); + ArduinoOTA.begin(); + + wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect); + wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect); + + mqttClient.onConnect(onMqttConnect); + mqttClient.onDisconnect(onMqttDisconnect); + mqttClient.onSubscribe(onMqttSubscribe); + mqttClient.onUnsubscribe(onMqttUnsubscribe); + mqttClient.onMessage(onMqttMessage); + mqttClient.onPublish(onMqttPublish); + mqttClient.setServer(mqtt_server, 1883); + + Serial.println("WF"); + connectToWifi(); + + pcf.begin(); + hdc1080.begin(0x40); + ee.begin(); + + button.attachClick(buttClick); + button.attachLongPressStart(buttLongClick); + + ee.readBlock(0, (uint8_t *)&wCounter, sizeof(wCounter)); + ee.readBlock(8, (uint8_t *)&wUstavki, sizeof(wUstavki)); + ee.readBlock(16, (uint8_t *)&ventUst, sizeof(ventUst)); + LCDtimeout = ee.readByte(20); + Serial.printf("QCold=%f, QHot=%f\n", wCounter.QC, wCounter.QH); + Serial.printf("H_SP=%d, H_DB=%d\n", wUstavki.hSP, wUstavki.hDB); + Serial.printf("TWork=%d, TPause=%d\n", ventUst.tWork, ventUst.tPause); + Serial.println(LCDtimeout); + //c_qc.update(b & 0x01); + //c_qh.update((b >> 1) & 0x01); + //c_flood.update((b >> 2) & 0x01); + // client.setServer(MQTT_SERV, 1883); + // client.setCallback(callback); + + sensors.begin(); + sensors.requestTemperatures(); + sensors.setResolution(11); + cTemp = sensors.getTempCByIndex(0); + hTemp = sensors.getTempCByIndex(1); + sensors.setWaitForConversion(false); + pinMode(VENT_TUAL, OUTPUT); + pinMode(VENT_VANNA, OUTPUT); + digitalWrite(VENT_TUAL, 1); + digitalWrite(VENT_VANNA, 1); + pcf.write(LED_RED, 1); + pcf.write(LED_GREEN, 1); + lcd.clear(); + lcd.setCursor(0, 0); + lcd.print(F("Init completed")); + cRun = 0; + page = 0; + LCDsec = 0; + vvannaSent0 = vvannaSent1 = false; + modeEdit = 0; +} // setup() + + +// Read the current position of the encoder and print out when changed. +void loop() +{ + ArduinoOTA.handle(); +// client.loop(); + button.tick(); + chkEnc(); + //ledBlue.tick(); + ledGreen.tick(); + //ledRed.tick(); + //ledYellow.tick(); + + if(cRun + 99 < millis()){ + cRun = millis(); + //ledGreen.start(); + chkCount(); + if(cnt % 10 == 0){ + ledGreen.start(); + chkLight(); + adc = analogRead(A0); + mws = (adc - 186) / 7.303396f; + temp = hdc1080.readTemperature(); + hum = hdc1080.readHumidity(); + // Serial.print(F("cnt:")); + // Serial.print(cnt); + // Serial.print(F("\t")); + // Serial.print(cRun); + // Serial.print(F("\tT=")); + // Serial.print(temp); + // Serial.print(F("C, RH=")); + // Serial.print(hum); + // Serial.print("% adc: "); + // Serial.println(adc); + getTemps(); + if(++LCDsec >= LCDtimeout){ + LCDsec = LCDtimeout; + lcd.setBacklight(0); + modeEdit = 0; + } + showLCD(page, false); + } + if(++cnt == 600){ + cnt = 0; + sendData(); + } + } + + if(hum >= wUstavki.hSP + wUstavki.hDB){ + digitalWrite(VENT_VANNA, 0); + if (!vvannaSent1){ + vvannaSent1 = true; + vvannaSent0 = false; + mqttClient.publish("/home/vt/vvanna", 1, false, "1"); + } + } + else if(hum <= wUstavki.hSP){ + digitalWrite(VENT_VANNA, 1); + if (!vvannaSent0){ + vvannaSent0 = true; + vvannaSent1 = false; + mqttClient.publish("/home/vt/vvanna", 1, false, "0"); + } + } +} // loop () + +void buttClick() +{ + Serial.println("Button Click"); + LCDsec = 0; + lcd.setBacklight(255); + if(modeEdit == 1){ + if (++itemEdit == 2) itemEdit = 0; + switch(page){ + case 0: + if(itemEdit == 0) encoder.setPosition(wUstavki.hSP); + else encoder.setPosition(wUstavki.hDB); + break; + case 1: + if(itemEdit == 0) encoder.setPosition(ventUst.tWork); + else encoder.setPosition(ventUst.tPause); + break; + case 2: + if(itemEdit == 0) encoder.setPosition((int)(wCounter.QC*100)); + else encoder.setPosition((int)(wCounter.QH*100)); + break; + } + } +} + +void buttLongClick() +{ + Serial.println("Button LongClick"); + LCDsec = 0; + lcd.setBacklight(255); + if (page == 3) return; + if (modeEdit == 0){ + modeEdit = 1; + itemEdit = 0; + switch(page){ + case 0: + encoder.setPosition(wUstavki.hSP); + break; + case 1: + encoder.setPosition(ventUst.tWork); + break; + case 2: + encoder.setPosition((int)(wCounter.QC*100)); + break; + } + } + else{ + modeEdit = 0; + switch(page){ + case 0: + ee.writeBlock(8, (uint8_t *)&wUstavki, sizeof(wUstavki)); + break; + case 1: + ee.writeBlock(16, (uint8_t *)&ventUst, sizeof(ventUst)); + break; + case 2: + ee.writeBlock(0, (uint8_t *)&wCounter, sizeof(wCounter)); + break; + } + encoder.setPosition(page); + } + curPos = encoder.getPosition(); +} + +void chkCount() +{ + byte b = pcf.read8(); + if(c_qc.chngDown((b >> Q_C) & 0x01)){ + wCounter.QC += 0.01f; + ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); + sprintf(v, "%.2f", wCounter.QC); + mqttClient.publish("/home/vt/qcold", 1, false, v); + Serial.printf("QCold=%f\n", wCounter.QC); + //pcf.write(7, led); + //led = !led; + } + if(c_qh.chngDown((b >> Q_H) & 0x01)){ + wCounter.QH += 0.01f; + ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); + sprintf(v, "%.2f", wCounter.QH); + mqttClient.publish("/home/vt/qhot", 1, false, v); + Serial.printf("QHot=%f\n", wCounter.QH); + //pcf.write(7, led); + //led = !led; + } + if(c_flood.chngDown((b >> FLOOD) & 0x01)){ + mqttClient.publish("/home/vt/flood", 1, false, "1"); + pcf.write(LED_RED, 0); + //Send MQTT Flood + Serial.printf("Flood\n"); + //pcf.write(7, led); + //led = !led; + } +} + +// void callback(char* topic, byte* payload, unsigned int length) { +// Serial.print("Message arrived ["); +// Serial.print(topic); +// Serial.print("] "); +// for (unsigned int i = 0; i < length; i++) { +// Serial.print((char)payload[i]); +// } +// Serial.println(); +// if (strcmp(topic, "/home/vt/h_sp_set") == 0){ +// wUstavki.hSP = atoi((char*)payload); +// ee.writeBlock(8, (uint8_t*)&wUstavki, sizeof(wUstavki)); +// return; +// } +// if (strcmp(topic, "/home/vt/h_db_set") == 0){ +// wUstavki.hDB = atoi((char*)payload); +// ee.writeBlock(8, (uint8_t*)&wUstavki, sizeof(wUstavki)); +// return; +// } +// if (strcmp(topic, "/home/vt/v_work_set") == 0){ +// ventUst.tWork = atoi((char*)payload); +// ee.writeBlock(16, (uint8_t*)&ventUst, sizeof(ventUst)); +// return; +// } +// if (strcmp(topic, "/home/vt/v_pause_set") == 0){ +// ventUst.tPause = atoi((char*)payload); +// ee.writeBlock(16, (uint8_t*)&ventUst, sizeof(ventUst)); +// return; +// } +// if (strcmp(topic, "/home/vt/QC_set") == 0){ +// wCounter.QC = atof((char*)payload); +// ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); +// return; +// } +// if (strcmp(topic, "/home/vt/QH_set") == 0){ +// wCounter.QH = atof((char*)payload); +// ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); +// return; +// } +// if (strcmp(topic, "/home/vt/LCDto_set") == 0){ +// LCDtimeout = atoi((char*)payload); +// ee.writeByte(20, LCDtimeout); +// } +// } + +// void reconnect() { +// uint8_t cnt = 0; +// // Loop until we're reconnected +// ledRed.start(); +// while (!client.connected() && (cnt < 5)) { +// Serial.print(F("Attempting MQTT connection...")); +// // Create a random client ID +// String clientId = "ESP_VT"; +// // Attempt to connect +// if (client.connect(clientId.c_str())) { +// Serial.println(F("connected")); +// client.subscribe("/home/vt/h_sp_set"); +// client.subscribe("/home/vt/h_db_set"); +// client.subscribe("/home/vt/v_work_set"); +// client.subscribe("/home/vt/v_pause_set"); +// client.subscribe("/home/vt/LCDto_set"); +// client.subscribe("/home/vt/QC_set"); +// client.subscribe("/home/vt/QH_set"); +// } else { +// Serial.print(F("failed, rc=")); +// Serial.print(client.state()); +// } +// cnt++; +// } +// } + +void showLCD(uint8_t page, bool chgd) +{ + char c = ' '; + if(chgd) c = '*'; + switch (page) + { + case 0: + lcd.setCursor(0, 0); + lcd.printf("V H%4.1f%% T%4.1fC%c", hum, temp, c); + lcd.setCursor(0, 1); + lcd.printf("SP:%2d DB:%2d ", wUstavki.hSP, wUstavki.hDB); + if (modeEdit == 1){ + lcd.cursor(); + lcd.blink(); + if(itemEdit == 0) + lcd.setCursor(4, 1); + else + lcd.setCursor(10, 1); + } + else{ + lcd.noCursor(); + lcd.noBlink(); + } + break; + case 1: + lcd.setCursor(0, 0); + lcd.printf("TW:%2ds TP:%2ds %c", ventUst.tWork, ventUst.tPause, c); + lcd.setCursor(0, 1); + lcd.printf("TC:%4.1fcTH:%4.1fc", cTemp, hTemp); + if (modeEdit == 1){ + lcd.cursor(); + lcd.blink(); + if(itemEdit == 0) + lcd.setCursor(4, 0); + else + lcd.setCursor(11, 0); + } + else{ + lcd.noCursor(); + lcd.noBlink(); + } + break; + case 2: + lcd.setCursor(0, 0); + lcd.printf("QC: %7.2f m3 %c", wCounter.QC, c); + lcd.setCursor(0, 1); + lcd.printf("QH: %7.2f m3 ", wCounter.QH); + if (modeEdit == 1){ + lcd.cursor(); + lcd.blink(); + if(itemEdit == 0) + lcd.setCursor(10, 0); + else + lcd.setCursor(10, 1); + } + else{ + lcd.noCursor(); + lcd.noBlink(); + } + break; + case 3: + lcd.setCursor(0, 0); + lcd.printf("ADC: %4d %c", adc, c); + lcd.setCursor(0, 1); + lcd.printf("P: %5.2f mws ", mws); + break; + default: + break; + } + //Serial.println(F("ShLCD")); +} + +void chkEnc() +{ + encoder.tick(); + int newPos = encoder.getPosition(); + if (curPos != newPos) { + LCDsec = 0; + lcd.setBacklight(255); + // if((newPos < 0) || (newPos > 3)){ + // encoder.setPosition(curPos); + // return; + // } + // Serial.println(); + curPos = newPos; + //Serial.print(curPos); + if(modeEdit == 1){ + if (newPos < 0) encoder.setPosition(0); + else switch(page){ + case 0: + if(itemEdit == 0){ + if(curPos > MAX_HSP){ + encoder.setPosition(MAX_HSP); + curPos = MAX_HSP; + } + else + wUstavki.hSP = curPos; + } + else{ + if(curPos > MAX_HDB){ + encoder.setPosition(MAX_HDB); + curPos = MAX_HDB; + } + else + wUstavki.hDB = curPos; + } + break; + case 1: + if(itemEdit == 0){ + if(curPos > MAX_TWORK){ + encoder.setPosition(MAX_TWORK); + curPos = MAX_TWORK; + } + else + ventUst.tWork = curPos; + } + else{ + if(curPos > MAX_TPAUSE){ + encoder.setPosition(MAX_TPAUSE); + curPos = MAX_TPAUSE; + } + else + ventUst.tPause = curPos; + } + break; + case 2: + if(itemEdit == 0){ + if(curPos > 999999){ + encoder.setPosition(999999); + curPos = 999999; + } + else + wCounter.QC = curPos / 100.0f; + } + else{ + if(curPos > 999999){ + encoder.setPosition(999999); + curPos = 999999; + } + else + wCounter.QH = curPos / 100.0f; + } + break; + } + } + else{ + page = curPos; + if(page > MAX_PAGE - 1) page = curPos = 0; + if(page < 0) page = curPos = MAX_PAGE - 1; + } + encoder.setPosition(curPos); + showLCD(page, false); + // Serial.print(page); + // Serial.println(); + } // if +} + +void getTemps() +{ + static uint8_t cnt = 0; + switch (cnt) + { + case 0: + sensors.requestTemperatures(); + break; + case 1: + cTemp = sensors.getTempCByIndex(0); + break; + case 2: + hTemp = sensors.getTempCByIndex(1); + break; + } + if(++cnt > 2){ + cnt = 0; + } +} + +void chkLight() +{ + static int sec = 0; + static unsigned long currun = millis(); + static bool lOn = false; + //Lamp is on + if(!pcf.read(LIGHT_SENS)){ + if((currun + 999 < millis()) && !lOn){ + sec++; + currun = millis(); +#ifdef DEBUG + Serial.print("Sec On: ");Serial.println(sec); + Serial.print("Lamp State: ");Serial.println(lOn); +#endif + } + if((sec >= ventUst.tPause) && !lOn){ + //lamp on +#ifdef DEBUG + Serial.print("Lamp On: ");Serial.println(sec); +#endif + lOn = true; + digitalWrite(VENT_TUAL, LOW); + mqttClient.publish("/home/vt/vtual", 1, false, "1"); + //sec = 0; + } + if(lOn) sec = 0; + } + else{ + if(lOn == true){ + if(currun + 999 < millis()){ + sec++; + currun = millis(); +#ifdef DEBUG + Serial.print("Sec Off: ");Serial.println(sec); + Serial.print("Lamp State: ");Serial.println(lOn); +#endif + } + if(sec >= ventUst.tWork){ +#ifdef DEBUG + Serial.print("Lamp Off: ");Serial.println(sec); +#endif + lOn = false; + digitalWrite(VENT_TUAL, HIGH); + mqttClient.publish("/home/vt/vtual", 1, false, "0"); + sec = 0; + } + } + else{ + sec = 0; + } + } +} + +void connectToWifi() { + Serial.println(F("Connecting to Wi-Fi...")); + //Serial1.flush(); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); +} + +void connectToMqtt() { + Serial.println(F("Connecting to MQTT...")); + //Serial1.flush(); + mqttClient.connect(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println(F("Connected to Wi-Fi.")); + Serial.print(F("IP: ")); + //Serial1.flush(); + Serial.println(WiFi.localIP()); + pcf.write(LED_YELLOW, 0); + connectToMqtt(); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println(F("Disconnected from Wi-Fi.")); + //Serial1.flush(); + mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi + wifiReconnectTimer.once(2, connectToWifi); + pcf.write(LED_YELLOW, 1); +} + +void onMqttConnect(bool sessionPresent) { + Serial.println(F("Connected to MQTT.")); + Serial.print(F("Session present: ")); + //Serial1.flush(); + Serial.println(sessionPresent); + //digitalWrite(B_LED, HIGH); + //digitalWrite(R_LED, LOW); + //uint16_t packetIdSub = + // //Serial1.print("Subscribing Lamp1, packetId: "); + // //Serial1.println(packetIdSub); + //packetIdSub = + mqttClient.subscribe("/home/vt/qhot_set", 1); + mqttClient.subscribe("/home/vt/qcold_set", 1); + mqttClient.subscribe("/home/vt/tpause_set", 1); + mqttClient.subscribe("/home/vt/twork_set", 1); + mqttClient.subscribe("/home/vt/hsp_set", 1); + mqttClient.subscribe("/home/vt/hdb_set", 1); + sprintf(v, "%.2f", wCounter.QH); + mqttClient.publish("/home/vt/qhot", 1, false, v); + sprintf(v, "%.2f", wCounter.QC); + mqttClient.publish("/home/vt/qcold", 1, false, v); + itoa(wUstavki.hDB, v, 10); + mqttClient.publish("/home/vt/hdb", 1, false, v); + itoa(wUstavki.hSP, v, 10); + mqttClient.publish("/home/vt/hsp", 1, false, v); + itoa(ventUst.tWork, v, 10); + mqttClient.publish("/home/vt/twork", 1, false, v); + itoa(ventUst.tPause, v, 10); + mqttClient.publish("/home/vt/tpause", 1, false, v); + ////Serial1.print("Subscribing Lamp2, packetId: "); + ////Serial1.println(packetIdSub); + ////Serial1.println("Publishing at Lamp 1"); + //mqttClient.publish("/home/kor/lamp2", 1, false, lStat2 ? "1" : "0"); + ////Serial1.println("Publishing at Lamp 2"); + + pcf.write(LED_BLUE, 0); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + Serial.println("Disconnected from MQTT."); + //digitalWrite(B_LED, LOW); + //digitalWrite(R_LED, HIGH); + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + pcf.write(LED_BLUE, 0); +} + +void onMqttSubscribe(uint16_t packetId, uint8_t qos) { + // //Serial1.println("Subscribe acknowledged."); + // //Serial1.print(" packetId: "); + // //Serial1.println(packetId); + // //Serial1.print(" qos: "); + // //Serial1.println(qos); +} + +void onMqttUnsubscribe(uint16_t packetId) { + // //Serial1.println("Unsubscribe acknowledged."); + // //Serial1.print(" packetId: "); + // //Serial1.println(packetId); +} + +void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) { + if(strcmp(topic, "/home/vt/qhot_set") == 0){ + wCounter.QH = atof(payload); + ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); + sprintf(v, "%.2f", wCounter.QH); + mqttClient.publish("/home/vt/qhot", 1, false, v); + } else + if(strcmp(topic, "/home/vt/qcold_set") == 0){ + wCounter.QC = atof(payload); + ee.writeBlock(0, (uint8_t*)&wCounter, sizeof(wCounter)); + sprintf(v, "%.2f", wCounter.QC); + mqttClient.publish("/home/vt/qcold", 1, false, v); + } else + if(strcmp(topic, "/home/vt/tpause_set") == 0){ + ventUst.tPause = atoi(payload); + ee.writeBlock(16, (uint8_t*)&ventUst, sizeof(wCounter)); + itoa(ventUst.tPause, v, 10); + mqttClient.publish("/home/vt/tpause", 1, false, v); + } else + if(strcmp(topic, "/home/vt/twork_set") == 0){ + ventUst.tWork = atoi(payload); + ee.writeBlock(16, (uint8_t*)&ventUst, sizeof(wCounter)); + itoa(ventUst.tWork, v, 10); + mqttClient.publish("/home/vt/twork", 1, false, v); + } else + if(strcmp(topic, "/home/vt/hsp_set") == 0){ + wUstavki.hSP = atoi(payload); + ee.writeBlock(8, (uint8_t*)&wUstavki, sizeof(wCounter)); + itoa(wUstavki.hSP, v, 10); + mqttClient.publish("/home/vt/hsp", 1, false, v); + } else + if(strcmp(topic, "/home/vt/hdb_set") == 0){ + wUstavki.hDB = atoi(payload); + ee.writeBlock(8, (uint8_t*)&wUstavki, sizeof(wCounter)); + itoa(wUstavki.hDB, v, 10); + mqttClient.publish("/home/vt/hdb", 1, false, v); + } +} +void onMqttPublish(uint16_t packetId) { + //Serial1.println("Publish acknowledged."); + //Serial1.print(" packetId: "); + //Serial1.println(packetId); + //g_led.start(); +} + +void sendData(){ + sprintf(v, "%.2f", temp); + mqttClient.publish("/home/vt/vtemp", 1, false, v); + sprintf(v, "%.2f", hum); + mqttClient.publish("/home/vt/vhum", 1, false, v); + sprintf(v, "%.2f", cTemp); + mqttClient.publish("/home/vt/tcold", 1, false, v); + sprintf(v, "%.2f", hTemp); + mqttClient.publish("/home/vt/thot", 1, false, v); + sprintf(v, "%.2f", mws); + mqttClient.publish("/home/vt/wpress", 1, false, v); + Serial.print("millis: "); Serial.print(millis()); + Serial.println(" Sent data"); +} diff --git a/VT_ESP8266/src/pcf_butt.cpp b/VT_ESP8266/src/pcf_butt.cpp new file mode 100644 index 0000000..9e5707f --- /dev/null +++ b/VT_ESP8266/src/pcf_butt.cpp @@ -0,0 +1,49 @@ +#include +#include "pcf_butt.h" + +pcf_butt::pcf_butt() +{ + curState = false; +} + +pcf_butt::pcf_butt(bool state) +{ + curState = state; +} + +bool pcf_butt::chngUp(bool state) +{ + curState = state; + if((lastState != curState) && curState == true){ + Serial.println("Down"); + lastState = curState; + return true; + } + else { + lastState = curState; + return false; + } +} + +bool pcf_butt::chngDown(bool state) +{ + curState = state; + if((lastState != curState) && curState == false){ + Serial.println("Down"); + lastState = curState; + return true; + } + else { + lastState = curState; + return false; + } +} + +void pcf_butt::update(bool state) +{ + curState = state; +} + +pcf_butt::~pcf_butt() +{ +} diff --git a/VT_ESP8266/test/README b/VT_ESP8266/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/VT_ESP8266/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/esp8266-KUH/.gitignore b/esp8266-KUH/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/esp8266-KUH/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/esp8266-KUH/.travis.yml b/esp8266-KUH/.travis.yml new file mode 100644 index 0000000..a8bbc57 --- /dev/null +++ b/esp8266-KUH/.travis.yml @@ -0,0 +1,67 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to be used as a library with examples. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# - platformio update +# +# script: +# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/esp8266-KUH/.vscode/extensions.json b/esp8266-KUH/.vscode/extensions.json new file mode 100644 index 0000000..0f0d740 --- /dev/null +++ b/esp8266-KUH/.vscode/extensions.json @@ -0,0 +1,7 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ] +} diff --git a/esp8266-KUH/include/README b/esp8266-KUH/include/README new file mode 100644 index 0000000..45496b1 --- /dev/null +++ b/esp8266-KUH/include/README @@ -0,0 +1,39 @@ + +This directory is intended for project header files. + +A header file is a file containing C declarations and macro definitions +to be shared between several project source files. You request the use of a +header file in your project source file (C, C++, etc) located in `src` folder +by including it, with the C preprocessing directive `#include'. + +```src/main.c + +#include "header.h" + +int main (void) +{ + ... +} +``` + +Including a header file produces the same results as copying the header file +into each source file that needs it. Such copying would be time-consuming +and error-prone. With a header file, the related declarations appear +in only one place. If they need to be changed, they can be changed in one +place, and programs that include the header file will automatically use the +new version when next recompiled. The header file eliminates the labor of +finding and changing all the copies as well as the risk that a failure to +find one copy will result in inconsistencies within a program. + +In C, the usual convention is to give header files names that end with `.h'. +It is most portable to use only letters, digits, dashes, and underscores in +header file names, and at most one dot. + +Read more about using header files in official GCC documentation: + +* Include Syntax +* Include Operation +* Once-Only Headers +* Computed Includes + +https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/esp8266-KUH/include/main.h b/esp8266-KUH/include/main.h new file mode 100644 index 0000000..761298c --- /dev/null +++ b/esp8266-KUH/include/main.h @@ -0,0 +1,45 @@ +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +//#include + +#include + +#include +#include +#include + +#include + +#include + +#define ONE_WIRE_BUS D4 + +union uFloat { + byte b[4]; + float f; + int i; +} wcH, wcC, ls, ld; + +void wCycle(); +void showLCD(); +void getTemp(); +void initLCD(); +void initWiFi(); +void initTemp(); +//void readEEPROM(); +void readDI(); +void movSens(); +void callback(String topic, byte* message, unsigned int length); +void reconnect(); +void handleData(); +//void writeEEPROM(const char tip[2], uFloat val); +void publishSec(); +void publishMin(); diff --git a/esp8266-KUH/lib/README b/esp8266-KUH/lib/README new file mode 100644 index 0000000..8c9c29c --- /dev/null +++ b/esp8266-KUH/lib/README @@ -0,0 +1,46 @@ + +This directory is intended for project specific (private) libraries. +PlatformIO will compile them to static libraries and link into executable file. + +The source code of each library should be placed in a an own separate directory +("lib/your_library_name/[here are source files]"). + +For example, see a structure of the following two libraries `Foo` and `Bar`: + +|--lib +| | +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html +| | +| |--Foo +| | |- Foo.c +| | |- Foo.h +| | +| |- README --> THIS FILE +| +|- platformio.ini +|--src + |- main.c + +and a contents of `src/main.c`: +``` +#include +#include + +int main (void) +{ + ... +} + +``` + +PlatformIO Library Dependency Finder will find automatically dependent +libraries scanning project source files. + +More information about PlatformIO Library Dependency Finder +- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/esp8266-KUH/platformio.ini b/esp8266-KUH/platformio.ini new file mode 100644 index 0000000..8d3bd7d --- /dev/null +++ b/esp8266-KUH/platformio.ini @@ -0,0 +1,17 @@ +;PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html + +[env:nodemcuv2] +platform = espressif8266 +board = nodemcuv2 +framework = arduino +upload_protocol = espota +upload_port = 192.168.1.6 + diff --git a/esp8266-KUH/src/main.cpp b/esp8266-KUH/src/main.cpp new file mode 100644 index 0000000..c41a135 --- /dev/null +++ b/esp8266-KUH/src/main.cpp @@ -0,0 +1,780 @@ +#include "main.h" + +const char* host = "esp8266"; +const char* ssid = "wf-home"; +const char* password = "0ndthnrf"; + +const char* mqtt_server = "192.168.1.250"; + +//ESP8266WebServer server(80); + +// инициализируем espClient: +WiFiClient espClient; +PubSubClient client(espClient); + +LiquidCrystal_PCF8574 lcd(0x27); // set the LCD address to 0x27 for a 16 chars and 2 line display + +int nDevs; +DeviceAddress da[4] = { + {0x28, 0xFF, 0x75, 0x3f, 0x93, 0x16, 0x04, 0xce}, + {0x28, 0x85, 0xcd, 0x1b, 0x05, 0x00, 0x00, 0x48}, + {0x28, 0xff, 0x79, 0x41, 0x88, 0x16, 0x03, 0x5a}, + {0x28, 0x20, 0xbe, 0x1b, 0x05, 0x00, 0x00, 0xdc} +}; + +// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) +OneWire oneWire(ONE_WIRE_BUS); + +// Pass our oneWire reference to Dallas Temperature. +DallasTemperature sensors(&oneWire); + +float temp1, tHolTop, tHolDown, tMoroz; +//float hum; +float hic; +//float temp2; +//float pres, bmpTemp; + +int old_wcC, old_wcH; +int adc; +float temp[4]; + + +const int led = LED_BUILTIN; +const int HOT_SENS = D5; +const int COLD_SENS = D6; +const int LED_STRIPE = D7; +const int LCD_MODE = D8; +const int RSET_FLOOD = D4; + +unsigned long oldRun = millis(); + +bool Flood = false; + +TwoWire testWire; +PCF857x pcf8574(0x38, &testWire); + +/*const int MB_LED = 0; +const int VLZEM_LED = 1; +const int BOX_LED = 2; +const int FLOOD_LED = 3; */ + + +//Bounce modeLCD_dbnc = Bounce(); +//Bounce hot_dbnc = Bounce(); +//Bounce cold_dbnc = Bounce(); +//Bounce rset_dbnc = Bounce(); + +bool bMLCD; +short sLCDPage; + +BME280I2C::Settings settings( + BME280::OSR_X1, + BME280::OSR_X2, + BME280::OSR_X16, + BME280::Mode_Normal, + BME280::StandbyTime_1000ms, + BME280::Filter_16, + BME280::SpiEnable_False, + BME280I2C::I2CAddr_0x76 // I2C address. I2C specific. +); +BME280I2C bme(settings); // Default : forced mode, standby time = 1000 ms +// Oversampling = pressure ×1, temperature ×1, humidity ×1, filter off, +float temp2(NAN), hum(NAN), pres(NAN); + +bool movSensor = 0; +bool MS = 0; + +void setup() +{ + Serial.begin(115200); + Serial.println("Init LCD"); + initLCD(); + delay(500); + Serial.println("Init BME280"); + int nt = 0; + while (!bme.begin()) { + Serial.println("Could not find a valid BMe280 sensor, check wiring!"); + delay(1000); + nt++; + if (nt > 10) break; + } + delay(500); + Serial.println("Init Temperature"); + initTemp(); + bme.read(pres, temp2, hum, BME280::TempUnit_Celsius, BME280::PresUnit_torr); + + pinMode(led, OUTPUT); + digitalWrite(led, 1); + pinMode(HOT_SENS, INPUT_PULLUP); + pinMode(COLD_SENS, INPUT_PULLUP); + pinMode(LED_STRIPE, OUTPUT); + pinMode(LCD_MODE, INPUT_PULLUP); + pinMode(D4, INPUT_PULLUP); + + //hot_dbnc.attach(HOT_SENS); + //hot_dbnc.interval(5); // interval in ms + //cold_dbnc.attach(COLD_SENS); + //cold_dbnc.interval(5); // interval in ms + /*modeLCD_dbnc.attach(LCD_MODE); + modeLCD_dbnc.interval(5); // interval in ms + rset_dbnc.attach(RSET_FLOOD); + rset_dbnc.interval(5); // interval in ms*/ + + + EEPROM.begin(16); + //readEEPROM(); + //Serial.print("Hot water: "); + //Serial.print(float(wcH.i) / 100.0); + //Serial.print("Cold water: "); + //Serial.println(float(wcC.i) / 100.0); + //Serial.print("LS Set: "); + //Serial.println(ls.i); + //Serial.print("LS DB: "); + //Serial.println(ld.i); + ls.i = 250; + ld.i = 50; + //old_wcC = wcC.i; + //old_wcH = wcH.i; + + testWire.begin();//5, 4); + testWire.setClock(100000L); + pcf8574.begin(); + bMLCD = false; + readDI(); + sLCDPage = 0; + initWiFi(); + client.setServer(mqtt_server, 1883); + client.setCallback(callback); + + ArduinoOTA.onStart([]() { + Serial.println("Start"); // "Начало OTA-апдейта" + }); + ArduinoOTA.onEnd([]() { + Serial.println("\nEnd"); // "Завершение OTA-апдейта" + }); + ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + }); + ArduinoOTA.onError([](ota_error_t error) { + Serial.printf("Error[%u]: ", error); + if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); + // "Ошибка при аутентификации" + else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); + // "Ошибка при начале OTA-апдейта" + else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); + // "Ошибка при подключении" + else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); + // "Ошибка при получении данных" + else if (error == OTA_END_ERROR) Serial.println("End Failed"); + // "Ошибка при завершении OTA-апдейта" + }); + ArduinoOTA.begin(); +} // setup() + +void loop() +{ + unsigned long curTime = millis(); + if ((curTime - oldRun) >= 10){ + wCycle(); + oldRun = curTime; + } + //server.handleClient(); + ArduinoOTA.handle(); + //movSens(); +} + +char strFVal[10]; + +void wCycle() +{ + static int sec = 0; + static short stp = 100; + if(stp == 100){ + stp = 0; + sec++; + if (sec == 59){ + sec = 0; + publishMin(); + } + getTemp(); + publishSec(); + } + if((stp % 20) == 0){ + showLCD(); + } + if((stp) == 60){ + float p, t, h; + bme.read(p, t, h, BME280::TempUnit_Celsius, BME280::PresUnit_torr); + //if (isnan(pres)) + pres = p; + //else pres += (p - pres) * 0.05; + //if (isnan(temp2)) + temp2 = t; + //else temp2 += (t - temp2) * 0.05; + //if (isnan(hum)) + hum = h; + //else hum += (h - hum) * 0.05; + } + readDI(); + movSens(); +/* if (Flood == true) + pcf8574.write(2, LOW); + else + pcf8574.write(2, HIGH);*/ + stp++; +} // loop() + + +void movSens() +{ + adc = analogRead(A0); + if (MS != pcf8574.read(4)){ + MS = pcf8574.read(4); + client.publish("/esp8266/move", String(MS).c_str()); + } + //Dark + if ((adc < (ls.i - ld.i)) && MS){ + pcf8574.write(5, LOW); //digitalWrite(LED_STRIPE, LOW); + } + //Light + if ((adc > (ls.i + ld.i)) || !MS){ + pcf8574.write(5, HIGH); //digitalWrite(LED_STRIPE, HIGH); + } + if (MS == true) + lcd.setBacklight(255); + else + lcd.setBacklight(0); +} + + +void getTemp() +{ + static bool readTemp = false; + static byte nSens = 0; + if (readTemp){ + sensors.setWaitForConversion(false); + sensors.requestTemperatures(); + readTemp = !readTemp; + } + else{ + //float t = sensors.getTempC(outTemp); + float t = sensors.getTempC(da[nSens]);//ByIndex(nSens); + Serial.print(nSens); + Serial.print(" Temp readed="); + Serial.println(t); + //to[0] = t; + if ((t > -127) && (t < 85)){ + switch(nSens){ + case 0: + temp1 += (t - temp1) * 0.05; + break; + case 1: + tHolTop += (t - tHolTop) * 0.05; + break; + case 2: + tHolDown += (t - tHolDown) * 0.05; + break; + case 3: + tMoroz += (t - tMoroz) * 0.05; + break; + } + } + if (++nSens > 3){ + nSens = 0; + readTemp = !readTemp; + } + } + //n++; +} + +void showLCD() +{ + char outS[16]; + String s1, s2; + //lcd.clear(); + switch (sLCDPage){ + case 0: + s1 = String(temp1, 1); + s2 = String(temp2, 1); + snprintf(outS, 17, "O:%5sC I:%4sC ", s1.c_str(), s2.c_str()); + lcd.setCursor(0, 0); + lcd.print(outS); + lcd.setCursor(0, 1); + s1 = String(hum, 1); + s2 = String(pres, 0); + snprintf(outS, 17, "H:%4s%% Pr:%2smm", s1.c_str(), s2.c_str()); + lcd.print(outS); + break; + case 1: + snprintf(outS, 17, "L:%04d SP:%03d %d ", adc, ls.i, ld.i); + lcd.setCursor(0, 0); + lcd.print(outS); + lcd.setCursor(0, 1); + s1 = String(hum, 1); + s2 = String(hic, 1); + snprintf(outS, 17, "H:%4s%% HI:%4sC ", s1.c_str(), s2.c_str()); + lcd.print(outS); + break; + case 2: + snprintf(outS, 17, "L:%04d SP:%03d %d", adc, ls.i, ld.i); + lcd.setCursor(0, 0); + lcd.print(outS); + lcd.setCursor(0, 1); + snprintf(outS, 17, "C:%03.2fH:%03.2f", float(wcC.i) / 100.0, float(wcH.i) / 100.0); + lcd.print(outS); + break; + case 3: + s1 = String(temp1, 1); + s2 = String(tMoroz, 1); + snprintf(outS, 17, "O:%4sC M:%4sC ", s1.c_str(), s2.c_str()); + lcd.setCursor(0, 0); + lcd.print(outS); + lcd.setCursor(0, 1); + s1 = String(tHolTop, 1); + s2 = String(tHolDown, 1); + snprintf(outS, 17, "H:%4sC HM:%4sC", s1.c_str(), s2.c_str()); + lcd.print(outS); + break; + } +} + +void initLCD(){ + int error; + Serial.println("LCD..."); + Serial.println("Dose: check for LCD"); + + // See http://playground.arduino.cc/Main/I2cScanner + Wire.begin(); + Wire.beginTransmission(0x38); + error = Wire.endTransmission(); + Serial.print("Error: "); + Serial.print(error); + + if (error == 0) { + Serial.println(": LCD found."); + + } else { + Serial.println(": LCD not found."); + } // if + lcd.begin(16, 2); // initialize the lcd + lcd.setBacklight(255); + lcd.clear(); +} + +/*void handleRoot() { + digitalWrite ( led, 0 ); + char temp[400]; + int sec = millis() / 1000; + int min = sec / 60; + int hr = min / 60; + + snprintf ( temp, 400, + + "\ + \ + \ + ESP8266 Demo\ + \ + \ + \ +

Hello from ESP8266!

\ +

Uptime: %02d:%02d:%02d

\ + \ + ", + + hr, min % 60, sec % 60 + ); + server.send ( 200, "text/html", temp ); + //digitalWrite ( led, 1 ); +}*/ + +/*void handleNotFound() { +// digitalWrite ( led, 0 ); + String message = "File Not Found\n\n"; + message += "URI: "; + message += server.uri(); + message += "\nMethod: "; + message += ( server.method() == HTTP_GET ) ? "GET" : "POST"; + message += "\nArguments: "; + message += server.args(); + message += "\n"; + // message += test().c_str(); + + for ( uint8_t i = 0; i < server.args(); i++ ) { + message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n"; + } + + server.send ( 404, "text/plain", message ); + //digitalWrite ( led, 1 ); +}*/ + +/*void handleJSON() +{ + //digitalWrite ( led, 0 ); + pcf8574.write(7, LOW); + + // Allocate JsonBuffer + // Use arduinojson.org/assistant to compute the capacity. + + StaticJsonBuffer<500> jsonBuffer; + + // Create the root object + JsonObject& root = jsonBuffer.createObject(); + + root.set("temp1", temp1); + root.set("temp2", temp2); + root.set("press", pres); + root.set("hum", hum); + root.set("vlzem", 0.0); + root.set("qc", float(wcC.i) / 100.0); + root.set("qh", float(wcH.i) / 100.0); + root.set("sp", ls.i); + root.set("db", ld.i); + root.set("vlsp", adc); + root.set("flood", Flood); + // Create the "analog" array + + String s; + root.printTo(s); + server.send(200, "application/json", s); + pcf8574.write(7, HIGH); + //digitalWrite ( led, 0 ); +}*/ + +/*void handleData() +{ + //String inArgs = ""; + char temp[100]; + char tm[3]; + String html; + + pcf8574.write(7, LOW); + int sec = millis() / 1000; + int min = sec / 60; + int hr = min / 60; + + if (server.args() > 0){ + for (int i = 0; i < server.args(); i++) { + if (server.argName(i).equals("wcc")){ + wcC.i = int(server.arg(i).toFloat() * 100.0f); + writeEEPROM("cc", wcC); + //inArgs += "

Write to wcc value: " + server.arg(i) + "

"; + } + if (server.argName(i).equals("wch")){ + wcH.i = int(server.arg(i).toFloat() * 100.0f) ; + writeEEPROM("ch", wcH); + //inArgs += "

Write to wcc value: " + server.arg(i) + "

"; + } + if (server.argName(i).equals("ls_set")){ + ls.i = server.arg(i).toInt(); + writeEEPROM("ls", ls); + } + if (server.argName(i).equals("ls_db")){ + ld.i = server.arg(i).toInt(); + writeEEPROM("ld", ld); + } + } + } + + html = ""; + html += ""; + html += ""; + html += "ESP8266 Demo"; + html += ""; + html += ""; + html += ""; + html += "

Hello from ESP8266!

"; + snprintf(tm, 3, "%02d", hr); + html += "

Uptime: " + String(tm); + snprintf(tm, 3, "%02d", min % 60); + html += ":" + String(tm); + snprintf(tm, 3, "%02d", sec % 60); + html += ":" + String(tm) + String("

"); + sprintf(temp, "

Cold Water: %6.2f m3

Hot Water: %6.2f m3

Temp: %3.3fC

LSet: %d, LDB: %d

", float(wcC.i) / 100.0, float(wcH.i) / 100.0, temp1, ls.i, ld.i); + html += String(temp); + html += ""; + + server.send ( 200, "text/html", html ); + pcf8574.write(7, HIGH); +}*/ + + +void initWiFi() +{ + //WiFi.mode(WIFI_STA); + WiFi.begin(ssid, password); + if(WiFi.waitForConnectResult() == WL_CONNECTED){ + delay(500); + Serial.print("."); + } + Serial.println(""); + Serial.print("Connected to "); + Serial.println(ssid); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + if (MDNS.begin(host)) { + Serial.println("MDNS responder started"); + } + + /*server.on ("/", handleData); + server.on("/data", handleData); + server.on("/json", handleJSON); + server.on ("/inline", []() { + server.send ( 200, "text/plain", "this works as well" ); + } ); + server.onNotFound ( handleNotFound ); + server.begin(); + Serial.println ( "HTTP server started" );*/ + + Serial.println("Ready"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); +} + +void initTemp() +{ + //DeviceAddress da[4]; + sensors.begin(); + Serial.println("InitTemp"); + //oneWire.reset_search(); + for (int i = 0; i < 4; i++){ + //sensors.getAddress(da[i], i); + sensors.setResolution(da[i], 12); + //printAddress(da[i]); + } + //sensors.getAddress(outTemp, 0); + //sensors.setResolution(outTemp, 12); + sensors.setWaitForConversion(true); + sensors.requestTemperatures(); + Serial.println("Request Temp"); + /*printAddress(outTemp); + printAddress(holTop); + printAddress(holDown); + printAddress(moroz);*/ + temp1 = sensors.getTempC(da[0]); + Serial.println(temp1); + tHolTop = sensors.getTempC(da[1]); + Serial.println(tHolTop); + tHolDown = sensors.getTempC(da[2]); + Serial.println(tHolDown); + tMoroz = sensors.getTempC(da[3]); + Serial.println(tMoroz); + /*delay(100); + tHolTop = sensors.getTempCByIndex(1); + delay(100); + tHolDown = sensors.getTempCByIndex(2); + delay(100); + tMoroz = sensors.getTempCByIndex(0);*/ +} + +/*void readEEPROM() +{ + wcC.b[0] = EEPROM.read(0); + wcC.b[1] = EEPROM.read(1); + wcC.b[2] = EEPROM.read(2); + wcC.b[3] = EEPROM.read(3); + + wcH.b[0] = EEPROM.read(4); + wcH.b[1] = EEPROM.read(5); + wcH.b[2] = EEPROM.read(6); + wcH.b[3] = EEPROM.read(7); + + ls.b[0] = EEPROM.read(8); + ls.b[1] = EEPROM.read(9); + ls.b[2] = EEPROM.read(10); + ls.b[3] = EEPROM.read(11); + + ld.b[0] = EEPROM.read(12); + ld.b[1] = EEPROM.read(13); + ld.b[2] = EEPROM.read(14); + ld.b[3] = EEPROM.read(15); +}*/ + +/*void writeEEPROM(const char tip[2], uFloat val) +{ + short shft = -1; + if (strcmp(tip, "cc") == 0) { + shft = 0; + //Serial.print("Write cold counter: "); + //Serial.println(val.f); + } + if (strcmp(tip, "ch") == 0) { + shft = 4; + //Serial.print("Write Hot counter: "); + //Serial.println(val.f); + } + if (strcmp(tip, "ls") == 0) { + shft = 8; + //Serial.print("Light Sensor Set: "); + //Serial.println(val.i); + } + if (strcmp(tip, "ld") == 0) { + shft = 12; + //Serial.print("Light Sensor DB: "); + //Serial.println(val.i); + } + if (shft == -1) return; + + EEPROM.write(shft, val.b[0]); + EEPROM.write(shft + 1, val.b[1]); + EEPROM.write(shft + 2, val.b[2]); + EEPROM.write(shft + 3, val.b[3]); + EEPROM.commit(); +}*/ + +void readDI() +{ + /*if (hot_dbnc.update()){ + if (hot_dbnc.read() == 1){ + wcH.i += 1; + //wcH.f += 0.01; + if (fabs(old_wcH - wcH.i) >= 5){ + writeEEPROM("ch", wcH); + old_wcH = wcH.i; + } + } + } + if (cold_dbnc.update()){ + if (cold_dbnc.read() == 1) + wcC.i += 1; + if (fabs(old_wcC - wcC.i) >= 5){ + writeEEPROM("cc", wcC); + old_wcC = wcC.i; + } + } + if (!pcf8574.read(6)) + Flood = true; + if (!pcf8574.read(0)) Flood = false;*/ + if (pcf8574.read(1) != bMLCD){ + if (bMLCD == false){ + sLCDPage++; + if (sLCDPage > 3) sLCDPage = 0; + } + bMLCD = !bMLCD; + } +} + +void callback(String topic, byte* message, unsigned int length) { + Serial.print("Message arrived on topic: "); + // "Сообщение прибыло в топик: " + Serial.print(topic); + Serial.print(". Message: "); // ". Сообщение: " + String messageTemp; + + for (unsigned int i = 0; i < length; i++) { + Serial.print((char)message[i]); + messageTemp += (char)message[i]; + } + Serial.println(); +} + +void reconnect() { + // заново запускаем цикл, пока не подключимся: + //while (!client.connected()) { + Serial.print("Attempting MQTT connection..."); + // "Попытка подключиться к MQTT-брокеру... " + + // Пытаемся подключиться: + if (client.connect("ESP8266Client")) { + Serial.println("connected"); // "подключен" + // подписываемся или переподписываемся на топик; + // можно подписаться не только на один, а на несколько топиков + // (что касается конкретно этого примера, то это позволит + // управлять большим количеством светодиодов): + //client.subscribe("esp8266/qc"); + //client.subscribe("esp8266/qh"); + } else { + Serial.print("failed, rc="); // "подключение не удалось" + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // "5 секунд до следующей попытки" + // ждем 5 секунд перед тем, как попробовать снова: + //delay(5000); + } + //} +} + +void printAddress(DeviceAddress deviceAddress) +{ + for (uint8_t i = 0; i < 8; i++) + { + // zero pad the address if necessary + if (deviceAddress[i] < 16) Serial.print("0"); + Serial.print(deviceAddress[i], HEX); + } + Serial.println(); +} + +void publishSec() +{ + if (!client.connected()) { + reconnect(); + } + if(!client.loop()) + client.connect("ESP8266Client"); + if (client.connected()) { + pcf8574.write(3, LOW); + dtostrf(temp1, 6, 2, strFVal); + client.publish("/esp8266/temp_out", strFVal); + dtostrf(temp2, 6, 2, strFVal); + client.publish("/esp8266/temp_in", strFVal); + dtostrf(hum, 6, 2, strFVal); + client.publish("/esp8266/humidity", strFVal); + dtostrf(pres, 6, 2, strFVal); + client.publish("/esp8266/pressure", strFVal); + dtostrf(float(wcC.i) / 100.0, 6, 2, strFVal); + /*client.publish("/esp8266/qCold", strFVal); + dtostrf(float(wcH.i) / 100.0, 6, 2, strFVal); + client.publish("/esp8266/qHot", strFVal); + itoa(ls.i, strFVal, 10);*/ + client.publish("/esp8266/light_sp", strFVal); + itoa(ld.i, strFVal, 10); + client.publish("/esp8266/light_db", strFVal); + itoa(adc, strFVal, 10); + client.publish("/esp8266/light_cur", strFVal); + //client.publish("/esp8266/flood", String(Flood).c_str()); + dtostrf(tHolTop, 6, 2, strFVal); + client.publish("/esp8266/hol_top", strFVal); + dtostrf(tHolDown, 6, 2, strFVal); + client.publish("/esp8266/hol_down", strFVal); + dtostrf(tMoroz, 6, 2, strFVal); + client.publish("/esp8266/moroz", strFVal); + pcf8574.write(3, HIGH); + } +} + +void publishMin() +{ + if (!client.connected()) { + reconnect(); + } + if(!client.loop()) + client.connect("ESP8266Client"); + if (client.connected()) { + pcf8574.write(7, LOW); + dtostrf(temp1, 6, 1, strFVal); + client.publish("/home/kuh/temp_out", strFVal); + dtostrf(temp2, 6, 1, strFVal); + client.publish("/home/kuh/temp_in", strFVal); + dtostrf(hum, 6, 1, strFVal); + client.publish("/home/kuh/humidity", strFVal); + dtostrf(pres, 6, 1, strFVal); + client.publish("/home/kuh/pressure", strFVal); + itoa(ls.i, strFVal, 10); + client.publish("/home/kuh/light_sp", strFVal); + itoa(ld.i, strFVal, 10); + client.publish("/home/kuh/light_db", strFVal); + itoa(adc, strFVal, 10); + client.publish("/home/kuh/light_cur", strFVal); + dtostrf(tHolTop, 6, 1, strFVal); + client.publish("/home/kuh/hol_top", strFVal); + dtostrf(tHolDown, 6, 1, strFVal); + client.publish("/home/kuh/hol_down", strFVal); + dtostrf(tMoroz, 6, 1, strFVal); + client.publish("/home/kuh/moroz", strFVal); + pcf8574.write(7, HIGH); + } +} diff --git a/esp8266-KUH/test/README b/esp8266-KUH/test/README new file mode 100644 index 0000000..c3b0ed6 --- /dev/null +++ b/esp8266-KUH/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PIO Unit Testing and project tests. + +Unit Testing is a software testing method by which individual units of +source code, sets of one or more MCU program modules together with associated +control data, usage procedures, and operating procedures, are tested to +determine whether they are fit for use. Unit testing finds problems early +in the development cycle. + +More information about PIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html