From a84b1f5ef109b6b07681d9bec2af1d223e0fb42e Mon Sep 17 00:00:00 2001 From: lexa Date: Sat, 4 Jan 2025 17:21:46 +0300 Subject: [PATCH] Initial Box-balkon --- Box-ESP12/.gitignore | 5 + Box-ESP12/.vscode/extensions.json | 10 ++ Box-ESP12/include/README | 39 +++++ Box-ESP12/include/main.h | 67 +++++++++ Box-ESP12/lib/README | 46 ++++++ Box-ESP12/platformio.ini | 27 ++++ Box-ESP12/src/main.cpp | 236 ++++++++++++++++++++++++++++++ Box-ESP12/test/README | 11 ++ 8 files changed, 441 insertions(+) create mode 100644 Box-ESP12/.gitignore create mode 100644 Box-ESP12/.vscode/extensions.json create mode 100644 Box-ESP12/include/README create mode 100644 Box-ESP12/include/main.h create mode 100644 Box-ESP12/lib/README create mode 100644 Box-ESP12/platformio.ini create mode 100644 Box-ESP12/src/main.cpp create mode 100644 Box-ESP12/test/README diff --git a/Box-ESP12/.gitignore b/Box-ESP12/.gitignore new file mode 100644 index 0000000..89cc49c --- /dev/null +++ b/Box-ESP12/.gitignore @@ -0,0 +1,5 @@ +.pio +.vscode/.browse.c_cpp.db* +.vscode/c_cpp_properties.json +.vscode/launch.json +.vscode/ipch diff --git a/Box-ESP12/.vscode/extensions.json b/Box-ESP12/.vscode/extensions.json new file mode 100644 index 0000000..080e70d --- /dev/null +++ b/Box-ESP12/.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/Box-ESP12/include/README b/Box-ESP12/include/README new file mode 100644 index 0000000..194dcd4 --- /dev/null +++ b/Box-ESP12/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/Box-ESP12/include/main.h b/Box-ESP12/include/main.h new file mode 100644 index 0000000..fdb139d --- /dev/null +++ b/Box-ESP12/include/main.h @@ -0,0 +1,67 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +//#include "LedController.hpp" +#include +#define DIO_PIN 13 +#define CLK_PIN 14 +#define LAT_PIN 12 +Disp7219<1> disp(DIO_PIN, CLK_PIN, LAT_PIN); + +#include +#include + +#include + +#define ONE_WIRE_BUS 2 + +#define WIFI_SSID "wf-home" +#define WIFI_PASSWORD "0ndthnrf" +#define MQTT_SERV "192.168.1.111" +#define HOSTNAME "Box-balkon" + +#define TOPIC "home/box/" + +#define TRIAC_PIN 4 + +WiFiClient espClient; +PubSubClient client(espClient); +WiFiEventHandler wifiConnectHandler; +WiFiEventHandler wifiDisconnectHandler; +Ticker wifiReconnectTimer; + +AsyncWebServer server(80); + +//LedController lc; + +OneWire oneWire(ONE_WIRE_BUS); +DallasTemperature sensors(&oneWire); + + +float temp_sp, temp1, temp2; +float kp = 0, ki = 0, kd = 0; +double Output = 0, Setpoint = 0, Input = 0; + +PID myPID(&Input, &Output, &Setpoint, kp, ki, kd, DIRECT); +unsigned long WindowSize = 5000; +unsigned long windowStartTime; + +long lastReconnectAttempt = 0; + +boolean wifi = false; + +void connectToWifi(); +void connectToMqtt(); +void onWifiConnect(const WiFiEventStationModeGotIP& event); +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event); +void callback(char* topic, byte* payload, unsigned int length); +boolean reconnect(); +void out_value(byte digit, float val); diff --git a/Box-ESP12/lib/README b/Box-ESP12/lib/README new file mode 100644 index 0000000..2593a33 --- /dev/null +++ b/Box-ESP12/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 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/Box-ESP12/platformio.ini b/Box-ESP12/platformio.ini new file mode 100644 index 0000000..0e702b1 --- /dev/null +++ b/Box-ESP12/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:esp12e] +platform = espressif8266 +board = esp12e +framework = arduino +upload_protocol = espota +upload_port = 192.168.1.159 + +lib_deps = + noah1510/LedController @ ^1.7.0 + knolleary/PubSubClient @ ^2.8 + ottowinter/ESPAsyncWebServer-esphome @ ^2.1.0 + ayushsharma82/WebSerial @ ^1.3.0 + jwrw/ESP_EEPROM @ ^2.0.0 + br3ttb/PID @ ^1.2.1 + milesburton/DallasTemperature @ ^3.11.0 + thomasfredericks/Bounce2 @ ^2.72 + gyverlibs/GyverSegment @ ^1.4.7 diff --git a/Box-ESP12/src/main.cpp b/Box-ESP12/src/main.cpp new file mode 100644 index 0000000..c0e5d8e --- /dev/null +++ b/Box-ESP12/src/main.cpp @@ -0,0 +1,236 @@ +#include "main.h" + +void setup() { + Serial.begin(9600); + WiFi.mode(WIFI_STA); + WiFi.hostname("Box-Balkon"); + + client.setServer(MQTT_SERV, 1883); + client.setCallback(callback); + client.setKeepAlive(20); + + 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); + connectToWifi(); + + disp.setCursor(0); + disp.print("hello"); + disp.update(); + + sensors.begin(); + sensors.setWaitForConversion(false); + sensors.requestTemperatures(); + delay(750); + temp1 = sensors.getTempCByIndex(0); + if(temp1 < -100) temp1 = -99; + + EEPROM.begin(8); + + EEPROM.get(0, temp_sp); + //if(isnan(temp_sp) || temp_sp == 0) temp_sp = 4.0f; + //out_value(1, temp_sp); + + EEPROM.get(2, kp); + //if(isnan(kp) || kp == 0) kp = 2.0f; + EEPROM.get(4, ki); + //if(isnan(ki) || ki == 0) ki = 2.0f; + EEPROM.get(6, kd); + //if(isnan(kd)) kd = 0.0f; + + // // myPID.SetTunings(kp, ki, kd); + // // Setpoint = temp_sp; + // // windowStartTime = millis(); + // // myPID.SetOutputLimits(0, WindowSize); + // // myPID.SetMode(AUTOMATIC); + // lastReconnectAttempt = 0; + Serial.println("setup end"); +} + +void loop() { + static unsigned long cRun = millis(); + static bool measTemp = false; + ArduinoOTA.handle(); + + if(cRun + 1000 <= millis()){ + cRun = millis(); + Serial.print("WiFi: ");Serial.print(wifi); + Serial.print(", MQTT: ");Serial.println(client.connected()); + if(measTemp) { + temp1 = sensors.getTempCByIndex(0); + if(temp1 < -100) temp1 = -99.0; + //out_value(0, temp1); + Input = temp1; + } + else{ + sensors.requestTemperatures(); + } + measTemp = !measTemp; + disp.setCursor(1); + disp.printf("%4.1f%5.1f", temp_sp, temp1); + disp.update(); + } + if (wifi && !client.connected()) { + long now = millis(); + if (now - lastReconnectAttempt > 5000) { + Serial.println("Connect MQTT"); + lastReconnectAttempt = now; + // Attempt to reconnect + if (reconnect()) { + lastReconnectAttempt = 0; + } + } + } else { + // Client connected + client.loop(); + } + Input = temp1; + if(Input > -99){ + myPID.Compute(); + + if (millis() - windowStartTime > WindowSize) + { //time to shift the Relay Window + windowStartTime += WindowSize; + } + if (Output < millis() - windowStartTime) digitalWrite(TRIAC_PIN, HIGH); + else digitalWrite(TRIAC_PIN, LOW); + } + else digitalWrite(TRIAC_PIN, LOW); +} + +void connectToWifi() { + Serial.println("Connecting to Wi-Fi..."); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + disp.setCursor(0); + disp.print(' '); + disp.update(); +} + +void onWifiConnect(const WiFiEventStationModeGotIP& event) { + Serial.println("Connected to Wi-Fi."); + Serial.print("IP: "); + Serial.println(WiFi.localIP()); + disp.setCursor(0); + disp.print('_'); + disp.update(); + wifi = true; + //digitalWrite(LED_WF, HIGH); +} + +void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) { + wifi = false; + Serial.println("Disconnected from Wi-Fi."); + client.disconnect(); + wifiReconnectTimer.once(2, connectToWifi); + disp.setCursor(0); + disp.print(' '); + disp.update(); + //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]; + unsigned 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"temp_sp") == 0){ + temp_sp = atof(val); + EEPROM.put(0, temp_sp); + EEPROM.commit(); + out_value(1, temp_sp); + } + if(strcmp(topic, TOPIC"kp") == 0){ + kp = atof(val); + EEPROM.put(2, kp); + EEPROM.commit(); + } + if(strcmp(topic, TOPIC"ki") == 0){ + ki = atof(val); + EEPROM.put(4, ki); + EEPROM.commit(); + } + if(strcmp(topic, TOPIC"kd") == 0){ + kd = atof(val); + EEPROM.put(6, kd); + EEPROM.commit(); + } +} + +boolean reconnect() { + // Loop until we're reconnected + //digitalWrite(LED_MQ, LOW); + Serial.print("Attempting MQTT connection..."); + // Attempt to connect + if (client.connect(HOSTNAME, TOPIC"online", 1, 1, "0")) { + Serial.println("connected"); + disp.setCursor(0); + disp.print('='); + disp.update(); + + client.publish(TOPIC"online", "1"); + char vout[7]; + sprintf(vout, "%.2f", kp); + client.publish(TOPIC"kp", vout); + sprintf(vout, "%.2f", ki); + client.publish(TOPIC"ki", vout); + sprintf(vout, "%.2f", kd); + client.publish(TOPIC"kd", vout); + sprintf(vout, "%.1f", temp_sp); + client.publish(TOPIC"temp_sp", vout); + sprintf(vout, "%.1f", temp1); + client.publish(TOPIC"temp1", vout); + //sprintf(vout, "%.1f", temp2); + //client.publish(TOPIC"temp2", vout); + + client.subscribe(TOPIC"temp_sp"); + client.subscribe(TOPIC"kp"); + client.subscribe(TOPIC"ki"); + client.subscribe(TOPIC"kd"); + } else { + Serial.print("failed, rc="); + Serial.print(client.state()); + Serial.println(" try again in 5 seconds"); + // Wait 1 seconds before retrying + disp.setCursor(0); + disp.print('_'); + disp.update(); + } + return client.connected(); + //digitalWrite(LED_MQ, HIGH); +} + +void out_value(byte digit, float val){ + // if(!isnan(val)){ + // int value = (val * 100.0) + 0.5; + // char ch = '0' + ((value / 100) % 10); + // lc.setChar(0, 2 + digit * 4, ch, false); + // ch = '0' + ((value / 10) % 10); + // lc.setChar(0 , 1 + digit * 4, ch, true); + // ch = '0' + (value % 10); + // lc.setChar(0 , 0 + digit * 4, ch, false); + // } + // else{ + // lc.setChar(0, 2 + digit * 4, 'E', false); + // lc.setRow(0, 1 + digit * 4, 0); + // lc.setRow(0, 0 + digit * 4, 0); + + // } +} diff --git a/Box-ESP12/test/README b/Box-ESP12/test/README new file mode 100644 index 0000000..9b1e87b --- /dev/null +++ b/Box-ESP12/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