Initial Box-balkon

This commit is contained in:
2025-01-04 17:21:46 +03:00
parent 7b20c656a9
commit a84b1f5ef1
8 changed files with 441 additions and 0 deletions

5
Box-ESP12/.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
Box-ESP12/.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
Box-ESP12/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

67
Box-ESP12/include/main.h Normal file
View File

@@ -0,0 +1,67 @@
#include <Arduino.h>
#include <Ticker.h>
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <WebSerial.h>
#include <ESP_EEPROM.h>
#include <PubSubClient.h>
#include <SPI.h>
//#include "LedController.hpp"
#include <GyverSegment.h>
#define DIO_PIN 13
#define CLK_PIN 14
#define LAT_PIN 12
Disp7219<1> disp(DIO_PIN, CLK_PIN, LAT_PIN);
#include <OneWire.h>
#include <DallasTemperature.h>
#include <PID_v1.h>
#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);

46
Box-ESP12/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 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

27
Box-ESP12/platformio.ini Normal file
View File

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

236
Box-ESP12/src/main.cpp Normal file
View File

@@ -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);
// }
}

11
Box-ESP12/test/README Normal file
View File

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