diff --git a/ESP12SmallRoom/platformio.ini b/ESP12SmallRoom/platformio.ini index 9c5c927..51d2c9f 100644 --- a/ESP12SmallRoom/platformio.ini +++ b/ESP12SmallRoom/platformio.ini @@ -17,6 +17,7 @@ board_build.f_cpu = 26000000L upload_protocol = espota upload_port = 192.168.1.148 lib_deps = - Adafruit HTU21DF Library @ ^1.1.0 + ;Adafruit HTU21DF Library @ ^1.1.0 PubSubClient @ ^2.8 jwrw/ESP_EEPROM @ ^2.0.0 + marvinroger/AsyncMqttClient @ ^0.9.0 diff --git a/ESP12SmallRoom/src/main.cpp b/ESP12SmallRoom/src/main.cpp index 328dd04..61bc7fd 100644 --- a/ESP12SmallRoom/src/main.cpp +++ b/ESP12SmallRoom/src/main.cpp @@ -5,9 +5,11 @@ #include #include #include -#include +//#include #include #include +#include +#include #define LED_BLUE D5 //GPIO14 #define LED_GREEN D6 //GPIO12 @@ -17,7 +19,9 @@ Adafruit_HTU21DF htu = Adafruit_HTU21DF(); WiFiClient espClient; -PubSubClient client(espClient); +//PubSubClient client(espClient); +AsyncMqttClient mqttClient; +Ticker mqttReconnectTimer; leds lGreen(LED_GREEN, 200); leds lRed(LED_RED, 200); leds lBlue(LED_BLUE, 200); @@ -39,20 +43,34 @@ void reconnect(); void publishMin(); void publishSec(); void callback(char* topic, byte* payload, unsigned int length); +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); void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); WiFi.mode(WIFI_STA); - WiFi.setOutputPower(20.5f); + //WiFi.setOutputPower(20.5f); WiFi.hostname("ESP-SmallRoom"); - WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { + //WiFi.begin(ssid, password); + //while (WiFi.waitForConnectResult() != WL_CONNECTED) { //Serial.println("Connection Failed! Rebooting..."); // "Соединиться не удалось! Перезагрузка..." - delay(5000); - ESP.restart(); - } +// delay(5000); +// ESP.restart(); +// } digitalWrite(LED_BUILTIN, !WiFi.isConnected()); ArduinoOTA.onStart([]() { /*Serial.println("Start");*/}); // "Начало OTA-апдейта" ArduinoOTA.onEnd([]() { /*Serial.println("\nEnd");*/}); // "Завершение OTA-апдейта" @@ -65,15 +83,29 @@ void setup() { else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); // "Ошибка при получении данных" else if (error == OTA_END_ERROR) Serial.println("End Failed"); // "Ошибка при завершении OTA-апдейта"*/ }); + 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); + mqttClient.setClientId("ESPSmallRoom"); + + connectToWifi(); + ArduinoOTA.begin(); pinMode(LED_GREEN, OUTPUT); pinMode(LED_BLUE, OUTPUT); pinMode(LED_RED, OUTPUT); pinMode(PWR_SENS, OUTPUT); pinMode(MOVE_SENS, INPUT); - digitalWrite(LED_GREEN, LOW); + digitalWrite(LED_GREEN, HIGH); digitalWrite(LED_BLUE, LOW); - digitalWrite(LED_RED, LOW); + digitalWrite(LED_RED, HIGH); // Serial.begin(115200); Serial.println("HTU21D-F"); digitalWrite(PWR_SENS, HIGH); @@ -85,8 +117,8 @@ void setup() { temp = htu.readTemperature(); rel_hum = htu.readHumidity(); //digitalWrite(PWR_SENS, LOW); - client.setServer(mqtt_server, 1883); - client.setCallback(callback); + //client.setServer(mqtt_server, 1883); + //client.setCallback(callback); EEPROM.begin(8); EEPROM.get(0, delta); adc = analogRead(A0); @@ -100,10 +132,10 @@ void loop() { lRed.tick(); lBlue.tick(); - if (!client.connected()) { - reconnect(); - } - client.loop(); + // if (!client.connected()) { + // reconnect(); + // } + // client.loop(); if(cRun + 99 < millis()){ cRun = millis(); @@ -111,13 +143,17 @@ void loop() { mv = digitalRead(MOVE_SENS); if(mv != oldmv){ oldmv = mv; - client.publish(TOPIC"smallroom/move", mv == 0 ? "0" : "1"); + lBlue.start(); + mqttClient.publish(TOPIC"smallroom/move", 0, false, mv == 0 ? "0" : "1"); + //client.publish(TOPIC"smallroom/move", mv == 0 ? "0" : "1"); }; //if(abs(adc - oldadc) > delta){ if(((adc < delta) && !lsSent) || ((adc >= (delta + 5)) && !lbSent)){ char strFVal[6]; itoa(adc, strFVal, 10); - client.publish(TOPIC"smallroom/light", strFVal); + lBlue.start(); + mqttClient.publish(TOPIC"smallroom/light", 0, false, strFVal); + //client.publish(TOPIC"smallroom/light", strFVal); oldadc = adc; if(adc < delta) {lsSent = true; lbSent = false;} else {lbSent = true; lsSent = false;} @@ -136,89 +172,164 @@ void loop() { publishMin(); minCnt = 0; } - if(minCnt % 100 == 0) publishSec(); + //if(minCnt % 100 == 0) publishSec(); } } -void reconnect() { - lRed.start(); - //digitalWrite(LED_RED, HIGH); - //Serial.print("Attempting MQTT connection..."); - // "Попытка подключиться к MQTT-брокеру... " - // Пытаемся подключиться: - if (client.connect("ESPSmallRoom")) { - //Serial.println("connected"); // "подключен" - // подписываемся или переподписываемся на топик; - // можно подписаться не только на один, а на несколько топиков - char v[6]; - itoa(delta, v, 10); - client.publish(TOPIC"smallroom/ldelta", v); - client.subscribe(TOPIC"smallroom/ldelta"); - } else { - //Serial.print("failed, rc="); // "подключение не удалось" - //Serial.print(client.state()); - //Serial.println(" try again in 5 seconds"); - } - //delay(100); - //digitalWrite(LED_RED, LOW); -} +// void reconnect() { +// lRed.start(); +// //digitalWrite(LED_RED, HIGH); +// //Serial.print("Attempting MQTT connection..."); +// // "Попытка подключиться к MQTT-брокеру... " +// // Пытаемся подключиться: +// if (client.connect("ESPSmallRoom")) { +// //Serial.println("connected"); // "подключен" +// // подписываемся или переподписываемся на топик; +// // можно подписаться не только на один, а на несколько топиков +// char v[6]; +// itoa(delta, v, 10); +// client.publish(TOPIC"smallroom/ldelta", v); +// client.subscribe(TOPIC"smallroom/ldelta"); +// } 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(); + //if (client.connected()) { + //digitalWrite(LED_BLUE, HIGH); + if (mqttClient.connected()) { + lBlue.start(); //digitalWrite(LED_BLUE, HIGH); if(!isnan(temp)){ dtostrf(temp, 6, 1, strFVal); - client.publish(TOPIC"smallroom/temp", strFVal); + mqttClient.publish(TOPIC"smallroom/temp", 0, false, strFVal); + //client.publish(TOPIC"smallroom/temp", strFVal); } if(!isnan(rel_hum)){ dtostrf(rel_hum, 6, 1, strFVal); - client.publish(TOPIC"smallroom/rel_hum", strFVal); + mqttClient.publish(TOPIC"smallroom/rel_hum", 0, false, strFVal); + //client.publish(TOPIC"smallroom/rel_hum", strFVal); } ultoa(adc, strFVal, 10); - client.publish(TOPIC"smallroom/light", strFVal); + mqttClient.publish(TOPIC"smallroom/light", 0, false, strFVal); + //client.publish(TOPIC"smallroom/light", strFVal); ultoa(cRun, strFVal, 10); - client.publish(TOPIC"smallroom/millis", strFVal); + mqttClient.publish(TOPIC"smallroom/millis", 0, false, strFVal); + //client.publish(TOPIC"smallroom/millis", strFVal); itoa(delta, strFVal, 10); - client.publish(TOPIC"smallroom/ldelta", strFVal); + mqttClient.publish(TOPIC"smallroom/ldelta", 0, false, strFVal); + //client.publish(TOPIC"smallroom/ldelta", strFVal); //digitalWrite(LED_BLUE, LOW); } + //digitalWrite(LED_BLUE, LOW); } void publishSec() { char strFVal[11]; - if (client.connected()) { + if (mqttClient.connected()) { lBlue.start(); + lGreen.start(); //digitalWrite(LED_GREEN, HIGH); if(!isnan(temp)){ dtostrf(temp, 7, 3, strFVal); - client.publish("/hometest/smallroom/temp", strFVal); + mqttClient.publish("/hometest/smallroom/temp", 0, false, strFVal); + //client.publish("/hometest/smallroom/temp", strFVal); } if(!isnan(rel_hum)){ dtostrf(rel_hum, 7, 3, strFVal); - client.publish("/hometest/smallroom/rel_hum", strFVal); + mqttClient.publish("/hometest/smallroom/rel_hum", 0, false, strFVal); + //client.publish("/hometest/smallroom/rel_hum", strFVal); } itoa(WiFi.RSSI(), strFVal, 10); - client.publish("/hometest/smallroom/RSSI", strFVal); + mqttClient.publish("/hometest/smallroom/RSSI", 0, false, strFVal); + //client.publish("/hometest/smallroom/RSSI", strFVal); ultoa(cRun, strFVal, 10); - client.publish("/hometest/smallroom/millis", strFVal); + mqttClient.publish("/hometest/smallroom/millis", 0, false, strFVal); + //client.publish("/hometest/smallroom/millis", strFVal); ltoa(adc, strFVal, 10); - client.publish("/hometest/smallroom/light", strFVal); + mqttClient.publish("/hometest/smallroom/light", 0, false, strFVal); + //client.publish("/hometest/smallroom/light", strFVal); itoa(delta, strFVal, 10); - client.publish("/hometest/smallroom/ldelta", strFVal); + mqttClient.publish("/hometest/smallroom/ldelta", 0, false, strFVal); + //client.publish("/hometest/smallroom/ldelta", strFVal); //digitalWrite(LED_GREEN, LOW); } } -void callback(char* topic, byte* payload, unsigned int length) { +// void callback(char* topic, byte* payload, unsigned int length) { +// if(strcmp(topic,TOPIC"smallroom/ldelta") == 0){ +// payload[length] = '\0'; +// String pl = String((char*)payload); +// delta = pl.toInt();// atoi((char*)payload); +// EEPROM.put(0, delta); +// EEPROM.commit(); +// } +// } + +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."); + connectToMqtt(); + digitalWrite(LED_GREEN, HIGH); + digitalWrite(LED_RED, 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_RED, HIGH); + digitalWrite(LED_GREEN, LOW); +} + +void onMqttConnect(bool sessionPresent) { + digitalWrite(LED_GREEN, LOW); + digitalWrite(LED_RED, LOW); + mqttClient.subscribe(TOPIC"smallroom/ldelta", 1); +} + +void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) { + Serial.println("Disconnected from MQTT."); + + if (WiFi.isConnected()) { + mqttReconnectTimer.once(2, connectToMqtt); + } + digitalWrite(LED_GREEN, HIGH); + digitalWrite(LED_RED, 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,TOPIC"smallroom/ldelta") == 0){ - payload[length] = '\0'; + payload[len] = '\0'; String pl = String((char*)payload); delta = pl.toInt();// atoi((char*)payload); EEPROM.put(0, delta); EEPROM.commit(); } } + +void onMqttPublish(uint16_t packetId) { +} \ No newline at end of file diff --git a/ESP32_Kor/.gitignore b/ESP32_Kor/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP32_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/ESP32_Kor/.vscode/extensions.json b/ESP32_Kor/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/ESP32_Kor/.vscode/extensions.json @@ -0,0 +1,10 @@ +{ + // See http://go.microsoft.com/fwlink/?LinkId=827846 + // for the documentation about the extensions.json format + "recommendations": [ + "platformio.platformio-ide" + ], + "unwantedRecommendations": [ + "ms-vscode.cpptools-extension-pack" + ] +} diff --git a/ESP32_Kor/include/README b/ESP32_Kor/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/ESP32_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/ESP32_Kor/lib/README b/ESP32_Kor/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/ESP32_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/ESP32_Kor/platformio.ini b/ESP32_Kor/platformio.ini new file mode 100644 index 0000000..4b30716 --- /dev/null +++ b/ESP32_Kor/platformio.ini @@ -0,0 +1,14 @@ +; 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:esp32dev] +platform = espressif32 +board = esp32dev +framework = arduino diff --git a/ESP32_Kor/src/main.cpp b/ESP32_Kor/src/main.cpp new file mode 100644 index 0000000..58b344c --- /dev/null +++ b/ESP32_Kor/src/main.cpp @@ -0,0 +1,9 @@ +#include + +void setup() { + // put your setup code here, to run once: +} + +void loop() { + // put your main code here, to run repeatedly: +} \ No newline at end of file diff --git a/ESP32_Kor/test/README b/ESP32_Kor/test/README new file mode 100644 index 0000000..b94d089 --- /dev/null +++ b/ESP32_Kor/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO 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 PlatformIO Unit Testing: +- https://docs.platformio.org/page/plus/unit-testing.html