From 447d197af95fcd765922edbdc6751cbe4b876804 Mon Sep 17 00:00:00 2001 From: lexa Date: Sun, 27 Nov 2022 15:23:20 +0300 Subject: [PATCH] Midroom 2 --- ESP_Midroom2/.gitignore | 5 + ESP_Midroom2/.vscode/extensions.json | 10 ++ ESP_Midroom2/include/README | 39 +++++ ESP_Midroom2/lib/README | 46 ++++++ ESP_Midroom2/platformio.ini | 27 ++++ ESP_Midroom2/src/main.cpp | 230 +++++++++++++++++++++++++++ ESP_Midroom2/test/README | 11 ++ 7 files changed, 368 insertions(+) create mode 100644 ESP_Midroom2/.gitignore create mode 100644 ESP_Midroom2/.vscode/extensions.json create mode 100644 ESP_Midroom2/include/README create mode 100644 ESP_Midroom2/lib/README create mode 100644 ESP_Midroom2/platformio.ini create mode 100644 ESP_Midroom2/src/main.cpp create mode 100644 ESP_Midroom2/test/README diff --git a/ESP_Midroom2/.gitignore b/ESP_Midroom2/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/ESP_Midroom2/.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_Midroom2/.vscode/extensions.json b/ESP_Midroom2/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/ESP_Midroom2/.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/ESP_Midroom2/include/README b/ESP_Midroom2/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/ESP_Midroom2/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_Midroom2/lib/README b/ESP_Midroom2/lib/README new file mode 100644 index 0000000..6debab1 --- /dev/null +++ b/ESP_Midroom2/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_Midroom2/platformio.ini b/ESP_Midroom2/platformio.ini new file mode 100644 index 0000000..7ea6563 --- /dev/null +++ b/ESP_Midroom2/platformio.ini @@ -0,0 +1,27 @@ +; 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:d1_mini] +platform = espressif8266 +board = d1_mini +framework = arduino +upload_protocol = espota +upload_port = 192.168.1.136 + + +lib_deps = + ;enjoyneering/AHT10@^1.1.0 + ;ottowinter/AsyncMqttClient-esphome @ ^0.8.6 + knolleary/PubSubClient @ ^2.8 + ottowinter/ESPAsyncWebServer-esphome @ ^2.1.0 + ayushsharma82/AsyncElegantOTA @ ^2.2.6 + ayushsharma82/WebSerial @ ^1.3.0 + jwrw/ESP_EEPROM @ ^2.0.0 + adafruit/Adafruit AHTX0 @ ^2.0.3 diff --git a/ESP_Midroom2/src/main.cpp b/ESP_Midroom2/src/main.cpp new file mode 100644 index 0000000..20256fd --- /dev/null +++ b/ESP_Midroom2/src/main.cpp @@ -0,0 +1,230 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define WIFI_SSID "wf-home" +#define WIFI_PASSWORD "0ndthnrf" +#define WIFI_SSID2 "BR" +#define WIFI_PASSWORD2 "499727479o" +#define MQTT_SERV "192.168.1.111" +#define TOPIC "home/midroom/bed/" +#define HOSTNAME "ESP_Midroom2" + +#define LED_WF (D0) +#define LED_MQ (D4) +#define LED_WRK (D3) + +#define LAMP_OUT (D5) + +Adafruit_AHTX0 aht; +sensors_event_t humidity, temp; +float temp_out, hum_out; + +WiFiClient espClient; +PubSubClient client(espClient); +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void callback(char* topic, byte* payload, unsigned int length); +void reconnect(); + +unsigned long stled; +float wMins = 0; +bool led, aht_pesent; +uint8_t led_intense; + +ESP8266WiFiMulti wifiMulti; +AsyncWebServer server(80); + +void setup() { + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.persistent(false); + WiFi.hostname(HOSTNAME); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + wifiMulti.addAP(WIFI_SSID2, WIFI_PASSWORD2); + + client.setServer(MQTT_SERV, 1883); + client.setCallback(callback); + client.setKeepAlive(20); + + 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); + + pinMode(LED_WF, OUTPUT); + pinMode(LED_MQ, OUTPUT); + pinMode(LED_WRK, OUTPUT); + pinMode(LAMP_OUT, OUTPUT); + if (! aht.begin()) { + Serial.println("Could not find AHT? Check wiring"); + aht_pesent = false; + } else{ + if(aht.getEvent(&humidity, &temp)){ + temp_out += (temp.temperature- temp_out) * 0.1; + hum_out += (humidity.relative_humidity - hum_out) * 0.1; + } + aht_pesent = true; + } + EEPROM.begin(4); + EEPROM.get(0, led_intense); + Serial.print("Led intense: "); + Serial.println(int(led_intense / 2.55)); + connectToWifi(); + + stled = millis(); + WebSerial.begin(&server); + /* Attach Message Callback */ + server.begin(); +} + +void loop() { + static unsigned long cRun = millis(); + static byte bSecs = 0; + char v[10]; + + ArduinoOTA.handle(); + if(!client.connected()) reconnect(); + client.loop(); + if(stled + 300 < millis()){ + digitalWrite(LED_WRK, HIGH); + } + if(cRun + 1000 <= millis()){ + cRun = millis(); + Serial.println(bSecs); + if(aht_pesent && aht.getEvent(&humidity, &temp)){ + temp_out += (temp.temperature- temp_out) * 0.1; + hum_out += (humidity.relative_humidity - hum_out) * 0.1; + WebSerial.print("Temp: "); + WebSerial.print(temp.temperature); + WebSerial.print(", Hum: "); + WebSerial.println(humidity.relative_humidity); + if(bSecs == 59){ + bSecs = 0; + digitalWrite(LED_WRK, LOW); + sprintf(v, "%.1f", temp_out); + client.publish(TOPIC"tempout", v); + sprintf(v, "%.1f", hum_out); + client.publish(TOPIC"humout", v); + } + } + if((bSecs % 30) == 0){ + wMins += 0.5; + Serial.println("halfMinTick"); + sprintf(v, "%.1f", wMins); + digitalWrite(LED_WRK, LOW); + client.publish(TOPIC"wmins", v); + } + bSecs++; + } +} + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + wifiMulti.run(); + //WiFi.begin(WIFI_SSID, WIFI_PASSWORD); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + digitalWrite(LED_WF, HIGH); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + Serial.println("Disconnected from Wi-Fi."); + client.disconnect(); + wifiReconnectTimer.once(2, connectToWifi); + digitalWrite(LED_WF, LOW); +} + +void callback(char* topic, byte* payload, unsigned int length) { + Serial.print("Message arrived ["); + Serial.print(topic); + Serial.print("] "); + char val[4]; + int i; + for (i = 0; i < length && i < 3; i++) { + val[i] = (char)payload[i]; + } + Serial.println(val); + val[i] = 0; + if(strcmp(topic, TOPIC"light") == 0){ + if(atoi(val) == 0){ + analogWrite(LAMP_OUT, 0); + led = false; + } + else{ + analogWrite(LAMP_OUT, led_intense); + led = true; + } + } + if(strcmp(topic, TOPIC"ledint") == 0){ + led_intense = int(atoi(val) * 2.55); + EEPROM.put(0, led_intense); + EEPROM.commit(); + if (led) analogWrite(LAMP_OUT, led_intense); + } +} + +void reconnect() { + // Loop until we're reconnected + while (!client.connected()) { + digitalWrite(LED_MQ, LOW); + Serial.print("Attempting MQTT connection..."); + // Attempt to connect + if (client.connect(HOSTNAME)) { + Serial.println("connected"); + char v[4]; + client.publish(TOPIC"ledint", itoa(int(led_intense / 2.55), v, 10)); + client.publish(TOPIC"light", led ? "1" : "0"); + client.subscribe(TOPIC"light"); + client.subscribe(TOPIC"ledint"); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 1 seconds"); + // Wait 1 seconds before retrying + delay(1000); + } + } + digitalWrite(LED_MQ, HIGH); +} \ No newline at end of file diff --git a/ESP_Midroom2/test/README b/ESP_Midroom2/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/ESP_Midroom2/test/README @@ -0,0 +1,11 @@ + +This directory is intended for PlatformIO Test Runner 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/en/latest/advanced/unit-testing/index.html