New project ESP32_Kor

This commit is contained in:
2022-02-23 09:15:00 +03:00
parent 97c6f7a271
commit 8b6684deb0
9 changed files with 304 additions and 58 deletions

View File

@@ -17,6 +17,7 @@ board_build.f_cpu = 26000000L
upload_protocol = espota upload_protocol = espota
upload_port = 192.168.1.148 upload_port = 192.168.1.148
lib_deps = lib_deps =
Adafruit HTU21DF Library @ ^1.1.0 ;Adafruit HTU21DF Library @ ^1.1.0
PubSubClient @ ^2.8 PubSubClient @ ^2.8
jwrw/ESP_EEPROM @ ^2.0.0 jwrw/ESP_EEPROM @ ^2.0.0
marvinroger/AsyncMqttClient @ ^0.9.0

View File

@@ -5,9 +5,11 @@
#include <ArduinoOTA.h> #include <ArduinoOTA.h>
#include <Wire.h> #include <Wire.h>
#include <Adafruit_HTU21DF.h> #include <Adafruit_HTU21DF.h>
#include <PubSubClient.h> //#include <PubSubClient.h>
#include <leds.h> #include <leds.h>
#include <ESP_EEPROM.h> #include <ESP_EEPROM.h>
#include <Ticker.h>
#include <AsyncMqttClient.h>
#define LED_BLUE D5 //GPIO14 #define LED_BLUE D5 //GPIO14
#define LED_GREEN D6 //GPIO12 #define LED_GREEN D6 //GPIO12
@@ -17,7 +19,9 @@
Adafruit_HTU21DF htu = Adafruit_HTU21DF(); Adafruit_HTU21DF htu = Adafruit_HTU21DF();
WiFiClient espClient; WiFiClient espClient;
PubSubClient client(espClient); //PubSubClient client(espClient);
AsyncMqttClient mqttClient;
Ticker mqttReconnectTimer;
leds lGreen(LED_GREEN, 200); leds lGreen(LED_GREEN, 200);
leds lRed(LED_RED, 200); leds lRed(LED_RED, 200);
leds lBlue(LED_BLUE, 200); leds lBlue(LED_BLUE, 200);
@@ -39,20 +43,34 @@ void reconnect();
void publishMin(); void publishMin();
void publishSec(); void publishSec();
void callback(char* topic, byte* payload, unsigned int length); 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() { void setup() {
Serial.begin(9600); Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); pinMode(LED_BUILTIN, OUTPUT);
WiFi.mode(WIFI_STA); WiFi.mode(WIFI_STA);
WiFi.setOutputPower(20.5f); //WiFi.setOutputPower(20.5f);
WiFi.hostname("ESP-SmallRoom"); WiFi.hostname("ESP-SmallRoom");
WiFi.begin(ssid, password); //WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) { //while (WiFi.waitForConnectResult() != WL_CONNECTED) {
//Serial.println("Connection Failed! Rebooting..."); //Serial.println("Connection Failed! Rebooting...");
// "Соединиться не удалось! Перезагрузка..." // "Соединиться не удалось! Перезагрузка..."
delay(5000); // delay(5000);
ESP.restart(); // ESP.restart();
} // }
digitalWrite(LED_BUILTIN, !WiFi.isConnected()); digitalWrite(LED_BUILTIN, !WiFi.isConnected());
ArduinoOTA.onStart([]() { /*Serial.println("Start");*/}); // "Начало OTA-апдейта" ArduinoOTA.onStart([]() { /*Serial.println("Start");*/}); // "Начало OTA-апдейта"
ArduinoOTA.onEnd([]() { /*Serial.println("\nEnd");*/}); // "Завершение 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_RECEIVE_ERROR) Serial.println("Receive Failed"); // "Ошибка при получении данных"
else if (error == OTA_END_ERROR) Serial.println("End Failed"); // "Ошибка при завершении OTA-апдейта"*/ 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(); ArduinoOTA.begin();
pinMode(LED_GREEN, OUTPUT); pinMode(LED_GREEN, OUTPUT);
pinMode(LED_BLUE, OUTPUT); pinMode(LED_BLUE, OUTPUT);
pinMode(LED_RED, OUTPUT); pinMode(LED_RED, OUTPUT);
pinMode(PWR_SENS, OUTPUT); pinMode(PWR_SENS, OUTPUT);
pinMode(MOVE_SENS, INPUT); pinMode(MOVE_SENS, INPUT);
digitalWrite(LED_GREEN, LOW); digitalWrite(LED_GREEN, HIGH);
digitalWrite(LED_BLUE, LOW); digitalWrite(LED_BLUE, LOW);
digitalWrite(LED_RED, LOW); digitalWrite(LED_RED, HIGH);
// Serial.begin(115200); // Serial.begin(115200);
Serial.println("HTU21D-F"); Serial.println("HTU21D-F");
digitalWrite(PWR_SENS, HIGH); digitalWrite(PWR_SENS, HIGH);
@@ -85,8 +117,8 @@ void setup() {
temp = htu.readTemperature(); temp = htu.readTemperature();
rel_hum = htu.readHumidity(); rel_hum = htu.readHumidity();
//digitalWrite(PWR_SENS, LOW); //digitalWrite(PWR_SENS, LOW);
client.setServer(mqtt_server, 1883); //client.setServer(mqtt_server, 1883);
client.setCallback(callback); //client.setCallback(callback);
EEPROM.begin(8); EEPROM.begin(8);
EEPROM.get(0, delta); EEPROM.get(0, delta);
adc = analogRead(A0); adc = analogRead(A0);
@@ -100,10 +132,10 @@ void loop() {
lRed.tick(); lRed.tick();
lBlue.tick(); lBlue.tick();
if (!client.connected()) { // if (!client.connected()) {
reconnect(); // reconnect();
} // }
client.loop(); // client.loop();
if(cRun + 99 < millis()){ if(cRun + 99 < millis()){
cRun = millis(); cRun = millis();
@@ -111,13 +143,17 @@ void loop() {
mv = digitalRead(MOVE_SENS); mv = digitalRead(MOVE_SENS);
if(mv != oldmv){ if(mv != oldmv){
oldmv = mv; 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(abs(adc - oldadc) > delta){
if(((adc < delta) && !lsSent) || ((adc >= (delta + 5)) && !lbSent)){ if(((adc < delta) && !lsSent) || ((adc >= (delta + 5)) && !lbSent)){
char strFVal[6]; char strFVal[6];
itoa(adc, strFVal, 10); 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; oldadc = adc;
if(adc < delta) {lsSent = true; lbSent = false;} if(adc < delta) {lsSent = true; lbSent = false;}
else {lbSent = true; lsSent = false;} else {lbSent = true; lsSent = false;}
@@ -136,89 +172,164 @@ void loop() {
publishMin(); publishMin();
minCnt = 0; minCnt = 0;
} }
if(minCnt % 100 == 0) publishSec(); //if(minCnt % 100 == 0) publishSec();
} }
} }
void reconnect() { // void reconnect() {
lRed.start(); // lRed.start();
//digitalWrite(LED_RED, HIGH); // //digitalWrite(LED_RED, HIGH);
//Serial.print("Attempting MQTT connection..."); // //Serial.print("Attempting MQTT connection...");
// "Попытка подключиться к MQTT-брокеру... " // // "Попытка подключиться к MQTT-брокеру... "
// Пытаемся подключиться: // // Пытаемся подключиться:
if (client.connect("ESPSmallRoom")) { // if (client.connect("ESPSmallRoom")) {
//Serial.println("connected"); // "подключен" // //Serial.println("connected"); // "подключен"
// подписываемся или переподписываемся на топик; // // подписываемся или переподписываемся на топик;
// можно подписаться не только на один, а на несколько топиков // // можно подписаться не только на один, а на несколько топиков
char v[6]; // char v[6];
itoa(delta, v, 10); // itoa(delta, v, 10);
client.publish(TOPIC"smallroom/ldelta", v); // client.publish(TOPIC"smallroom/ldelta", v);
client.subscribe(TOPIC"smallroom/ldelta"); // client.subscribe(TOPIC"smallroom/ldelta");
} else { // } else {
//Serial.print("failed, rc="); // "подключение не удалось" // //Serial.print("failed, rc="); // "подключение не удалось"
//Serial.print(client.state()); // //Serial.print(client.state());
//Serial.println(" try again in 5 seconds"); // //Serial.println(" try again in 5 seconds");
} // }
//delay(100); // //delay(100);
//digitalWrite(LED_RED, LOW); // //digitalWrite(LED_RED, LOW);
} // }
void publishMin() void publishMin()
{ {
char strFVal[11]; char strFVal[11];
if (client.connected()) { //if (client.connected()) {
lGreen.start(); //digitalWrite(LED_BLUE, HIGH);
if (mqttClient.connected()) {
lBlue.start();
//digitalWrite(LED_BLUE, HIGH); //digitalWrite(LED_BLUE, HIGH);
if(!isnan(temp)){ if(!isnan(temp)){
dtostrf(temp, 6, 1, strFVal); 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)){ if(!isnan(rel_hum)){
dtostrf(rel_hum, 6, 1, strFVal); 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); 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); 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); 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);
} }
//digitalWrite(LED_BLUE, LOW);
} }
void publishSec() void publishSec()
{ {
char strFVal[11]; char strFVal[11];
if (client.connected()) { if (mqttClient.connected()) {
lBlue.start(); lBlue.start();
lGreen.start();
//digitalWrite(LED_GREEN, HIGH); //digitalWrite(LED_GREEN, HIGH);
if(!isnan(temp)){ if(!isnan(temp)){
dtostrf(temp, 7, 3, strFVal); 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)){ if(!isnan(rel_hum)){
dtostrf(rel_hum, 7, 3, strFVal); 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); 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); 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); 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); 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); //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){ if(strcmp(topic,TOPIC"smallroom/ldelta") == 0){
payload[length] = '\0'; payload[len] = '\0';
String pl = String((char*)payload); String pl = String((char*)payload);
delta = pl.toInt();// atoi((char*)payload); delta = pl.toInt();// atoi((char*)payload);
EEPROM.put(0, delta); EEPROM.put(0, delta);
EEPROM.commit(); EEPROM.commit();
} }
} }
void onMqttPublish(uint16_t packetId) {
}

5
ESP32_Kor/.gitignore vendored Normal file
View File

@@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

10
ESP32_Kor/.vscode/extensions.json vendored Normal file
View File

@@ -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"
]
}

39
ESP32_Kor/include/README Normal file
View File

@@ -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

46
ESP32_Kor/lib/README Normal file
View File

@@ -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 <Foo.h>
#include <Bar.h>
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

14
ESP32_Kor/platformio.ini Normal file
View File

@@ -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

9
ESP32_Kor/src/main.cpp Normal file
View File

@@ -0,0 +1,9 @@
#include <Arduino.h>
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}

11
ESP32_Kor/test/README Normal file
View File

@@ -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