From 6d3af9e18da32b9f89a457032fa2f9811e109605 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sun, 28 Jun 2020 11:39:05 +0200 Subject: [PATCH 01/23] Changd print message from sensor to light-sensor started --- src/lightSensor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 6b2c566..9ffc0e4 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -5,7 +5,7 @@ BH1750 lightMeter; void setupLightSensor() { Wire.begin(); lightMeter.begin(); - Serial.println("Sensor started..."); + Serial.println("Light-Sensor started..."); } int readLightSensorValue() { From ac9327179d935c3a2ff09e68bbab774fb96c5cea Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sun, 28 Jun 2020 18:56:04 +0200 Subject: [PATCH 02/23] new class LightningChecker to control led --- src/LightingChecker.cpp | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/LightingChecker.cpp diff --git a/src/LightingChecker.cpp b/src/LightingChecker.cpp new file mode 100644 index 0000000..01ec405 --- /dev/null +++ b/src/LightingChecker.cpp @@ -0,0 +1,48 @@ +#include + +#define RED_PIN 1 +#define GREEN_PIN 2 +#define BLUE_PIN 3 + +enum colorTypes { + purple, + blue, + green, + yellow, + orange, + red, + white +}; + +int valueNM; + +colorTypes color = white; + +void readPreferableLight() { + //preferableLight = Read from database +} + +void getColorBasedOnPreferableLight() { + if (valueNM <= 420) { + color = purple; + } + else if (valueNM <= 490) { + color = blue; + } + else if (valueNM <= 575) { + color = green; + } + else if (valueNM <= 585) { + color = yellow; + } + else if (valueNM <= 650) { + color = orange; + } + else if (valueNM <= 750) { + color = red; + } +} + +void activateLight(int duration) { + +} \ No newline at end of file From a0066f0811b3ebaa707f36c62f86b88d3321c8d4 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Mon, 29 Jun 2020 18:35:12 +0200 Subject: [PATCH 03/23] worked at RGBclass --- src/LightingChecker.cpp | 62 +++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/src/LightingChecker.cpp b/src/LightingChecker.cpp index 01ec405..eebbffa 100644 --- a/src/LightingChecker.cpp +++ b/src/LightingChecker.cpp @@ -1,9 +1,5 @@ #include -#define RED_PIN 1 -#define GREEN_PIN 2 -#define BLUE_PIN 3 - enum colorTypes { purple, blue, @@ -15,14 +11,36 @@ enum colorTypes { }; int valueNM; +// Colors in Array: purple, blue, green, yellow, orange, red, white +int colorValueArray[][3] = {{125,0,125}, {0,0,255}, {0,255,0}, {255,255,0}, {255,140,0}, {255,0,0}, {255,255,255}}; +int colorCounter = 6; colorTypes color = white; -void readPreferableLight() { - //preferableLight = Read from database +//Setting PWM properties +const int freqRed = 5000; +const int freqGreen = 5000; +const int freqBlue = 5000; +const int ledChannelRed = 0; +const int ledChannelGreen = 1; +const int ledChannelBlue= 2; +const int resolutionRed = 8; +const int resolutionGreen = 8; +const int resolutionBlue = 8; + +void setupPWM() { + ledcSetup(ledChannelRed, freqRed, resolutionRed); + ledcSetup(ledChannelGreen, freqGreen, resolutionGreen); + ledcSetup(ledChannelBlue, freqBlue, resolutionBlue); + + ledcAttachPin() } -void getColorBasedOnPreferableLight() { +void readValueNM() { + //valueNM = Read from database +} + +void getColorBasedOnValueNM() { if (valueNM <= 420) { color = purple; } @@ -38,11 +56,37 @@ void getColorBasedOnPreferableLight() { else if (valueNM <= 650) { color = orange; } - else if (valueNM <= 750) { + else if (valueNM > 650) { //650 to 750 is red color = red; } } void activateLight(int duration) { - + switch (color) { + case purple: + colorCounter = 0; + break; + case blue: + colorCounter = 1; + break; + case green: + colorCounter = 2; + break; + case yellow: + colorCounter = 3; + break; + case orange: + colorCounter = 4; + break; + case red: + colorCounter = 5; + break; + case white: + colorCounter = 6; + break; + } + + void activateLight() { + + } } \ No newline at end of file From 2827573bbc2e92ace3c6b6b48fedf7d0673241b4 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 1 Jul 2020 10:49:42 +0200 Subject: [PATCH 04/23] added lightChecker class and some basic pwm stuff --- src/LightingChecker.cpp | 92 ----------------------------------------- src/header.h | 6 ++- src/lightChecker.cpp | 0 src/main.cpp | 3 ++ 4 files changed, 8 insertions(+), 93 deletions(-) delete mode 100644 src/LightingChecker.cpp create mode 100644 src/lightChecker.cpp diff --git a/src/LightingChecker.cpp b/src/LightingChecker.cpp deleted file mode 100644 index eebbffa..0000000 --- a/src/LightingChecker.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include - -enum colorTypes { - purple, - blue, - green, - yellow, - orange, - red, - white -}; - -int valueNM; -// Colors in Array: purple, blue, green, yellow, orange, red, white -int colorValueArray[][3] = {{125,0,125}, {0,0,255}, {0,255,0}, {255,255,0}, {255,140,0}, {255,0,0}, {255,255,255}}; -int colorCounter = 6; - -colorTypes color = white; - -//Setting PWM properties -const int freqRed = 5000; -const int freqGreen = 5000; -const int freqBlue = 5000; -const int ledChannelRed = 0; -const int ledChannelGreen = 1; -const int ledChannelBlue= 2; -const int resolutionRed = 8; -const int resolutionGreen = 8; -const int resolutionBlue = 8; - -void setupPWM() { - ledcSetup(ledChannelRed, freqRed, resolutionRed); - ledcSetup(ledChannelGreen, freqGreen, resolutionGreen); - ledcSetup(ledChannelBlue, freqBlue, resolutionBlue); - - ledcAttachPin() -} - -void readValueNM() { - //valueNM = Read from database -} - -void getColorBasedOnValueNM() { - if (valueNM <= 420) { - color = purple; - } - else if (valueNM <= 490) { - color = blue; - } - else if (valueNM <= 575) { - color = green; - } - else if (valueNM <= 585) { - color = yellow; - } - else if (valueNM <= 650) { - color = orange; - } - else if (valueNM > 650) { //650 to 750 is red - color = red; - } -} - -void activateLight(int duration) { - switch (color) { - case purple: - colorCounter = 0; - break; - case blue: - colorCounter = 1; - break; - case green: - colorCounter = 2; - break; - case yellow: - colorCounter = 3; - break; - case orange: - colorCounter = 4; - break; - case red: - colorCounter = 5; - break; - case white: - colorCounter = 6; - break; - } - - void activateLight() { - - } -} \ No newline at end of file diff --git a/src/header.h b/src/header.h index 7eab5cf..262df6e 100644 --- a/src/header.h +++ b/src/header.h @@ -62,4 +62,8 @@ extern float readTemperature(); // mqtt & wifi extern void setupConnections(); -extern void publishMessage(const char *topic, const char *msg); \ No newline at end of file +extern void publishMessage(const char *topic, const char *msg); + +// RGB PWM LED +extern void setupPWM(); +extern void activateLight(); \ No newline at end of file diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/main.cpp b/src/main.cpp index 198940a..6988b3f 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,6 +12,7 @@ void setup() { pingTimer = millis(); setupConnections(); setupLightSensor(); + setupPWM(); setupTemperatureSensor(); setupCapacitiveSoilMoistureSensor(); Serial.println("Setup complete..."); @@ -47,6 +48,8 @@ void loop() { publishMessage("smartgarden/updates/esp-N2Ff4kaDgs45/temperature", buffer); Serial.print("\n"); + activateLight(); + pingTimer = millis(); } } \ No newline at end of file From 52e3ab8cdc030b38a0ec5d7e1082a7edfca00655 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 1 Jul 2020 10:52:26 +0200 Subject: [PATCH 05/23] update lightChecker --- src/lightChecker.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index e69de29..1a30e1e 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -0,0 +1,61 @@ +#include + +int valueNM; +// Colors in Array: purple, blue, green, yellow, orange, red, white +int colorValueArray[][3] = {{125,0,125}, {0,0,255}, {0,255,0}, {255,255,0}, {255,140,0}, {255,0,0}, {255,255,255}}; +int colorCounter = 6; + +// Setting PWM properties +const int freq = 5000; +const int ledChannelRed = 0; +const int ledChannelGreen = 1; +const int ledChannelBlue= 2; +const int resolution = 8; + +void setupPWM() { + // Set pins as output + pinMode(PIN_LED_R, OUTPUT); + pinMode(PIN_LED_G, OUTPUT); + pinMode(PIN_LED_B, OUTPUT); + + // Configure LED PWM functionalitites + ledcSetup(ledChannelRed, freq, resolution); + ledcSetup(ledChannelGreen, freq, resolution); + ledcSetup(ledChannelBlue, freq, resolution); + + // Attach the channel to the GPIO2 to be controlled + ledcAttachPin(PIN_LED_R, ledChannelRed); + ledcAttachPin(PIN_LED_G, ledChannelGreen); + ledcAttachPin(PIN_LED_B, ledChannelBlue); +} + +void readValueNM() { + // ValueNM = Read from database +} + +void getColorBasedOnValueNM() { + if (valueNM <= 420) { + colorCounter = 0; + } + else if (valueNM <= 490) { + colorCounter = 1; + } + else if (valueNM <= 575) { + colorCounter = 2; + } + else if (valueNM <= 585) { + colorCounter = 3; + } + else if (valueNM <= 650) { + colorCounter = 4; + } + else if (valueNM > 650) { // 650 to 750 is red + colorCounter = 5; + } +} + +void activateLight() { + ledcWrite(ledChannelRed, colorValueArray[colorCounter][0]); + ledcWrite(ledChannelGreen, colorValueArray[colorCounter][1]); + ledcWrite(ledChannelBlue, colorValueArray[colorCounter][2]); +} \ No newline at end of file From 03ea93b74122f08bbe58319674954430eee68388 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 1 Jul 2020 14:31:50 +0200 Subject: [PATCH 06/23] changed mqtt id --- src/header.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/header.h b/src/header.h index 3ecd521..fbd09ee 100644 --- a/src/header.h +++ b/src/header.h @@ -41,7 +41,7 @@ // MQTT #define MQTT_HOST "mqtt.timovolkmann.de" #define MQTT_PORT 1883 -#define MQTT_DEVICE_ID "esp-sebastian +#define MQTT_DEVICE_ID "esp-sebastian" #define MQTT_TOPIC_BASE_SUB "smartgarden/commands" #define MQTT_TOPIC_BASE_PUB "smartgarden/updates" #define MQTT_PATH_PUB MQTT_TOPIC_BASE_PUB "/" MQTT_DEVICE_ID "/" From b4ecfed027aff1a4a2b8cce075232b8b0607677f Mon Sep 17 00:00:00 2001 From: Sebastian Date: Thu, 2 Jul 2020 02:03:30 +0200 Subject: [PATCH 07/23] added example to read data from MQTT Server --- src/connections.cpp | 19 ++++++++++++++++++- src/header.h | 4 ++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/connections.cpp b/src/connections.cpp index 9971b25..0977360 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -64,6 +64,11 @@ void onMqttConnect(bool sessionPresent) uint16_t packetIdSub = mqttClient.subscribe(MQTT_PATH_SUB, 2); Serial.print("subscribed to: "); Serial.println(MQTT_PATH_SUB); + + //Testing read + uint16_t packetIdSub2 = mqttClient.subscribe("smartgarden/updates/esp-sebastian/brightness", 2); + Serial.print("also subscribed to: "); + Serial.println("smartgarden/updates/esp-sebastian/brightness"); } void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) @@ -103,6 +108,18 @@ void onMqttMessage(char *topic, char *payload, AsyncMqttClientMessageProperties Serial.println(topic); toggleValve(); } + + //Testing reading + String messageTemp; + for (int i = 0; i < len; i++) { + //Serial.print((char)payload[i]); + messageTemp += (char)payload[i]; + } + if (strcmp(topic, "smartgarden/updates/esp-sebastian/brightness") == 0) { + Serial.println("### Received brightness value: ###"); + Serial.println(messageTemp); + } + } void onMqttPublish(uint16_t packetId) @@ -135,4 +152,4 @@ void setupConnections() void publishMessage(const char *topic, const char *msg) { mqttClient.publish(topic, 1, true, msg); -} +} \ No newline at end of file diff --git a/src/header.h b/src/header.h index fbd09ee..5820402 100644 --- a/src/header.h +++ b/src/header.h @@ -17,6 +17,10 @@ #include #include +// BH1750 lightsensor +#define MIN_LIGHT 0 +#define MAX_LIGHT 54612 + // DHT11 #define PIN_DHT11 14 From 5d65dc79d089ae89efb341f4f54d25d40c0c2725 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Uribe=20Stengel?= Date: Thu, 2 Jul 2020 10:32:16 +0200 Subject: [PATCH 08/23] Update .gitignore File to ignore Visual Studio Files. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 89cc49c..3d1fbd7 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ .vscode/c_cpp_properties.json .vscode/launch.json .vscode/ipch +.vs From 68f75f252daf3893f93e58bbf46019692f4d8131 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Fri, 3 Jul 2020 13:21:13 +0200 Subject: [PATCH 09/23] deleted test stuff --- src/connections.cpp | 28 ---------------------------- src/lightSensor.cpp | 6 ------ 2 files changed, 34 deletions(-) diff --git a/src/connections.cpp b/src/connections.cpp index 9b7e9fe..3830f28 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -63,13 +63,6 @@ void connectMQTT() { mqttClient.subscribe(MQTT_PATH_SUB); Serial.print("subscribed to: "); Serial.println(MQTT_PATH_SUB); -<<<<<<< HEAD - - //Testing read - uint16_t packetIdSub2 = mqttClient.subscribe("smartgarden/updates/esp-sebastian/brightness", 2); - Serial.print("also subscribed to: "); - Serial.println("smartgarden/updates/esp-sebastian/brightness"); -======= xTaskCreate( mqttLoop, /* Task function. */ "mqttLoop", /* String with name of task. */ @@ -78,7 +71,6 @@ void connectMQTT() { 1, /* Priority of the task. */ &mqttTask); /* Task handle. */ //xTimerStart(mqttProcessingTimer, 0); ->>>>>>> develop } void WiFiEvent(WiFiEvent_t event) { @@ -114,20 +106,6 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { Serial.println(topic); toggleValve(); } -<<<<<<< HEAD - - //Testing reading - String messageTemp; - for (int i = 0; i < len; i++) { - //Serial.print((char)payload[i]); - messageTemp += (char)payload[i]; - } - if (strcmp(topic, "smartgarden/updates/esp-sebastian/brightness") == 0) { - Serial.println("### Received brightness value: ###"); - Serial.println(messageTemp); - } - -======= if (strcmp(topic, MQTT_SOIL_PROPERTIES) == 0) { Serial.println("receiving soil thresholds..."); Serial.println(topic); @@ -145,7 +123,6 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { Serial.println(err.c_str()); } } ->>>>>>> develop } void setupConnections() { @@ -168,11 +145,6 @@ void setupConnections() { } void publishMessage(const char *topic, const char *msg) { -<<<<<<< HEAD - mqttClient.publish(topic, 1, true, msg); -} -======= mqttClient.publish(topic, msg); // mqttClient.publish(topic, msg, true, 1); } ->>>>>>> develop diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 992b5dd..776a3fd 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -3,15 +3,9 @@ BH1750 lightMeter; void setupLightSensor() { -<<<<<<< HEAD - Wire.begin(); - lightMeter.begin(); - Serial.println("Light-Sensor started..."); -======= Wire.begin(); lightMeter.begin(); Serial.println("Sensor started..."); ->>>>>>> develop } float readLightSensorValue() { From 5fb882c59a093ffc078de508dbeb60ddb9cac2ee Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sat, 4 Jul 2020 17:09:44 +0200 Subject: [PATCH 10/23] light treshold will now be set based on mqtt command --- src/connections.cpp | 14 +++++++++++++- src/header.h | 4 +++- src/lightChecker.cpp | 8 +++++--- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/connections.cpp b/src/connections.cpp index 3830f28..88c0d2c 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -10,6 +10,7 @@ extern "C" { #define MQTT_VALVE_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/valve" #define MQTT_SOIL_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/soil" +#define MQTT_LIGHT_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/light" TimerHandle_t mqttReconnectTimer; TimerHandle_t wifiReconnectTimer; @@ -101,10 +102,21 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { } Serial.println(); + if (strcmp(topic, MQTT_LIGHT_COMMAND) == 0) { +Serial.println("receiving light treshold..."); + Serial.println(topic); + } if (strcmp(topic, MQTT_VALVE_COMMAND) == 0) { Serial.println("toggling valve..."); Serial.println(topic); - toggleValve(); + StaticJsonDocument<1024> doc; + DeserializationError err = deserializeJson(doc, payload); + if (err == DeserializationError::Ok) { + int nm = doc["nm"]; + setValueNM(nm); + } else { + Serial.println(err.c_str()); + } } if (strcmp(topic, MQTT_SOIL_PROPERTIES) == 0) { Serial.println("receiving soil thresholds..."); diff --git a/src/header.h b/src/header.h index 53d67c9..1a34635 100644 --- a/src/header.h +++ b/src/header.h @@ -77,7 +77,9 @@ extern void publishMessage(const char *topic, const char *msg); // RGB PWM LED extern void setupPWM(); -extern void activateLight(); +extern bool activateLight(); +extern void setValueNM(int NM); +extern void getColorBasedOnValueNM(); // sensors void readSensors(); diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 1a30e1e..79713d5 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -29,8 +29,9 @@ void setupPWM() { ledcAttachPin(PIN_LED_B, ledChannelBlue); } -void readValueNM() { - // ValueNM = Read from database +void setValueNM(int NM) { + valueNM = NM; + getColorBasedOnValueNM(); } void getColorBasedOnValueNM() { @@ -54,8 +55,9 @@ void getColorBasedOnValueNM() { } } -void activateLight() { +bool activateLight() { ledcWrite(ledChannelRed, colorValueArray[colorCounter][0]); ledcWrite(ledChannelGreen, colorValueArray[colorCounter][1]); ledcWrite(ledChannelBlue, colorValueArray[colorCounter][2]); + return true; } \ No newline at end of file From 62bf9a17c53386f2f9919947ece4f5034fbea496 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Mon, 6 Jul 2020 12:41:14 +0200 Subject: [PATCH 11/23] fixed light subscription --- src/connections.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/connections.cpp b/src/connections.cpp index 88c0d2c..4abc8a5 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -10,7 +10,7 @@ extern "C" { #define MQTT_VALVE_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/valve" #define MQTT_SOIL_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/soil" -#define MQTT_LIGHT_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/light" +#define MQTT_LIGHT_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/light" TimerHandle_t mqttReconnectTimer; TimerHandle_t wifiReconnectTimer; @@ -102,13 +102,9 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { } Serial.println(); - if (strcmp(topic, MQTT_LIGHT_COMMAND) == 0) { + if (strcmp(topic, MQTT_LIGHT_PROPERTIES) == 0) { Serial.println("receiving light treshold..."); Serial.println(topic); - } - if (strcmp(topic, MQTT_VALVE_COMMAND) == 0) { - Serial.println("toggling valve..."); - Serial.println(topic); StaticJsonDocument<1024> doc; DeserializationError err = deserializeJson(doc, payload); if (err == DeserializationError::Ok) { @@ -118,6 +114,11 @@ Serial.println("receiving light treshold..."); Serial.println(err.c_str()); } } + if (strcmp(topic, MQTT_VALVE_COMMAND) == 0) { + Serial.println("toggling valve..."); + Serial.println(topic); + toggleValve(); + } if (strcmp(topic, MQTT_SOIL_PROPERTIES) == 0) { Serial.println("receiving soil thresholds..."); Serial.println(topic); From cbf51999db1358ad444bae8d3cafe79e625b6e03 Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Mon, 6 Jul 2020 21:44:53 +0200 Subject: [PATCH 12/23] improved wifi & mqtt; preparation for deep sleep --- platformio.ini | 1 + src/connections.cpp | 73 ++++++++++++++++++++++++++++----------------- src/header.h | 11 ++++--- src/main.cpp | 20 +++++++++++-- src/peripherals.cpp | 4 +++ 5 files changed, 74 insertions(+), 35 deletions(-) diff --git a/platformio.ini b/platformio.ini index 346cfd9..e211cbf 100644 --- a/platformio.ini +++ b/platformio.ini @@ -13,6 +13,7 @@ platform = espressif32 board = az-delivery-devkit-v4 framework = arduino monitor_speed = 115200 +; build_flags = -DCORE_DEBUG_LEVEL=5 lib_deps = 439 #ID of Lightsensor library BH1750 diff --git a/src/connections.cpp b/src/connections.cpp index 3830f28..1cbce8c 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -13,8 +13,6 @@ extern "C" { TimerHandle_t mqttReconnectTimer; TimerHandle_t wifiReconnectTimer; - -// TimerHandle_t mqttProcessingTimer; TaskHandle_t mqttTask; WebServer Server; @@ -22,12 +20,10 @@ AutoConnect Portal(Server); WiFiClient client; AutoConnectConfig Config; -// Config.autoReconnect = true; -// WiFi.config(Config); -// MQTTClient mqttClient; PubSubClient mqttClient(client); void connectWiFi() { + yield(); Serial.println("Start WiFi..."); if (Portal.begin()) { digitalWrite(PIN_LED_G, HIGH); @@ -36,14 +32,15 @@ void connectWiFi() { void mqttLoop(void *parameter) { do { + yield(); mqttClient.loop(); - delay(50); + delay(100); } while (mqttClient.connected()); Serial.println("Disconnected from MQTT."); if (!mqttClient.connected()) { Serial.println("Checking WiFi Connection."); if (WiFi.isConnected()) { - Serial.println("Starting reconnect timer for MQTT."); + Serial.println("WiFi OK. Starting reconnect timer for MQTT."); xTimerStart(mqttReconnectTimer, 0); } } @@ -51,9 +48,12 @@ void mqttLoop(void *parameter) { } void connectMQTT() { + yield(); + if (mqttClient.connected()) return; Serial.println("Connecting to MQTT..."); // mqttClient.begin(MQTT_HOST, MQTT_PORT, client); mqttClient.setServer(MQTT_HOST, MQTT_PORT); + mqttClient.disconnect(); mqttClient.connect(MQTT_DEVICE_ID); if (mqttClient.connected()) { Serial.println("Connected!"); @@ -63,17 +63,24 @@ void connectMQTT() { mqttClient.subscribe(MQTT_PATH_SUB); Serial.print("subscribed to: "); Serial.println(MQTT_PATH_SUB); - xTaskCreate( - mqttLoop, /* Task function. */ - "mqttLoop", /* String with name of task. */ - 8192, /* Stack size in bytes. */ - NULL, /* Parameter passed as input of the task */ - 1, /* Priority of the task. */ - &mqttTask); /* Task handle. */ - //xTimerStart(mqttProcessingTimer, 0); + xTaskCreatePinnedToCore( + mqttLoop, + "mqttLoop", + 8192, + NULL, + 2, + &mqttTask, + 1); + // xTaskCreate( + // mqttLoop, /* Task function. */ + // "mqttLoop", /* String with name of task. */ + // 8192, /* Stack size in bytes. */ + // NULL, /* Parameter passed as input of the task */ + // 1, /* Priority of the task. */ + // &mqttTask); /* Task handle. */ } -void WiFiEvent(WiFiEvent_t event) { +void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info) { Serial.printf("[WiFi-event] event: %d\n", event); switch (event) { case SYSTEM_EVENT_STA_GOT_IP: @@ -84,14 +91,18 @@ void WiFiEvent(WiFiEvent_t event) { break; case SYSTEM_EVENT_STA_DISCONNECTED: digitalWrite(PIN_LED_G, LOW); + // workaround for 202 auth failed bug: https://github.com/espressif/arduino-esp32/issues/2501 + if (info.disconnected.reason == 202) { + Serial.println("weirdbehaviour"); + Serial.println(info.disconnected.reason); + ESP.restart(); + } xTimerStop(mqttReconnectTimer, 0); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi - // xTimerStop(mqttProcessingTimer, 0); xTimerStart(wifiReconnectTimer, 0); break; } } -// void onMqttMessage(MQTTClient *client, char topic[], char payload[], int payload_length) { void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { Serial.print("Message arrived ["); Serial.print(topic); @@ -109,9 +120,6 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { if (strcmp(topic, MQTT_SOIL_PROPERTIES) == 0) { Serial.println("receiving soil thresholds..."); Serial.println(topic); - //Serial.println(reinterpret_cast(payload)); - // Serial.println(payload); - // const int capacity = JSON_OBJECT_SIZE(3) + 2 * JSON_OBJECT_SIZE(1); StaticJsonDocument<1024> doc; DeserializationError err = deserializeJson(doc, payload); if (err == DeserializationError::Ok) { @@ -128,23 +136,32 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { void setupConnections() { Serial.println(); Serial.println(); + disableCore0WDT(); + // disableCore1WDT(); + Config.autoReconnect = true; + // Config.autoReset = true; + Portal.config(Config); mqttReconnectTimer = xTimerCreate( "mqttTimer", pdMS_TO_TICKS(2000), pdFALSE, (void *)0, reinterpret_cast(connectMQTT)); wifiReconnectTimer = xTimerCreate( "wifiTimer", pdMS_TO_TICKS(2000), pdFALSE, (void *)0, reinterpret_cast(connectWiFi)); - // mqttProcessingTimer = xTimerCreate( - // "messageTimer", pdMS_TO_TICKS(50), pdTRUE, (void *)0, reinterpret_cast(mqttLoop)); - + WiFi.onEvent(WiFiEvent); - // mqttClient.onMessageAdvanced(onMqttMessage); + connectWiFi(); + connectMQTT(); + mqttClient.setCallback(onMqttMessage); - connectWiFi(); } void publishMessage(const char *topic, const char *msg) { - mqttClient.publish(topic, msg); - // mqttClient.publish(topic, msg, true, 1); + if(mqttClient.connected()) { + mqttClient.publish(topic, msg); + Serial.print(topic); + Serial.println(" successfully sent.\n"); + } else { + Serial.println("couldn't send message. waiting for reconnect.\n"); + } } diff --git a/src/header.h b/src/header.h index 7955c34..39aa356 100644 --- a/src/header.h +++ b/src/header.h @@ -17,8 +17,8 @@ #include // fix for core panic during wifi initialization -// #define configMINIMAL_STACK_SIZE 2048 -// #define CONFIG_TIMER_TASK_STACK_SIZE 8192 +#define configMINIMAL_STACK_SIZE 4096 +#define CONFIG_TIMER_TASK_STACK_SIZE 8192 // DHT11 #define PIN_DHT11 14 @@ -52,7 +52,7 @@ // MQTT_DEVICE_ID "/#" // PUBLISH FREQUENCY (MS) -#define FREQUENCY 3000 +#define FREQUENCY 5000 //30000 // moisture extern void setupCapacitiveSoilMoistureSensor(); @@ -75,4 +75,7 @@ extern void publishMessage(const char *topic, const char *msg); void readSensors(); void toggleValve(); void setSoilProperties(int FC, int PWP, int SAT); -void setupStore(); \ No newline at end of file +void setupStore(); + +void takeSemaphore(); +void releaseSemaphore(); \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 3a609ee..3407490 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -6,6 +6,9 @@ #include +#define TIME_TO_SLEEP 30 +volatile int noSleepTasks = 0; + unsigned long sensorReadTimer = 0; bool valveOpen = false; @@ -25,6 +28,7 @@ void setup() { setupLightSensor(); setupTemperatureSensor(); setupCapacitiveSoilMoistureSensor(); + // esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 1000000); Serial.println("Setup complete..."); Serial.println(); Serial.println(); @@ -35,8 +39,18 @@ void loop() { if (millis() - sensorReadTimer >= FREQUENCY) { readSensors(); sensorReadTimer = millis(); - } - // toggle valve - if (valveOpen) { + + // if(noSleepTasks == 0) { + // delay(200); + // esp_deep_sleep_start(); + // } } } + +void takeSemaphore() { + noSleepTasks++; +} + +void releaseSemaphore() { + noSleepTasks--; +} \ No newline at end of file diff --git a/src/peripherals.cpp b/src/peripherals.cpp index 6d93cf9..4e99140 100644 --- a/src/peripherals.cpp +++ b/src/peripherals.cpp @@ -70,6 +70,7 @@ bool closeValve() { } void valveTask(void *parameter) { + takeSemaphore(); unsigned long valveTimeoutTimer = millis(); bool valveOpen = openValve(); @@ -84,6 +85,7 @@ void valveTask(void *parameter) { // valveOpen = closeValve(); // } } + releaseSemaphore(); vTaskDelete(NULL); } @@ -98,6 +100,7 @@ void toggleValve() { } void persistSoilProps(int FC, int PWP, int SAT) { + takeSemaphore(); Serial.println("persistSoilProps"); bool f = NVS.setInt("fieldCapacity", FC); bool p = NVS.setInt("permanentWilt", PWP); @@ -109,6 +112,7 @@ void persistSoilProps(int FC, int PWP, int SAT) { else { Serial.println("error occured while trying to persist soil properties"); } + releaseSemaphore(); } void restoreSoilProps() { From 71e58773cbdaada0d870eab412971052e115d991 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sat, 11 Jul 2020 10:34:06 +0200 Subject: [PATCH 13/23] Light will now turn on if lx below minLX also color can be changed based on nanoMeters of prefered light --- src/connections.cpp | 3 ++- src/header.h | 15 ++++++++--- src/lightChecker.cpp | 62 +++++++++++++++++++++++++++++++++----------- src/peripherals.cpp | 13 ++++++++++ 4 files changed, 73 insertions(+), 20 deletions(-) diff --git a/src/connections.cpp b/src/connections.cpp index 4abc8a5..87eaff3 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -109,7 +109,8 @@ Serial.println("receiving light treshold..."); DeserializationError err = deserializeJson(doc, payload); if (err == DeserializationError::Ok) { int nm = doc["nm"]; - setValueNM(nm); + int minLX = doc["minLX"]; + setLightningProperties(nm, minLX); } else { Serial.println(err.c_str()); } diff --git a/src/header.h b/src/header.h index 1a34635..2df6a10 100644 --- a/src/header.h +++ b/src/header.h @@ -40,11 +40,17 @@ #define PIN_VALVE 32 #define MAX_VALVE_TIMEOUT 10000 -// LED +// STATUS LED #define PIN_LED_R 2 #define PIN_LED_G 0 #define PIN_LED_B 4 +// LIGHT LED +#define LIGHT_LED_PIN_R 27 +#define LIGHT_LED_PIN_G 26 +#define LIGHT_LED_PIN_B 25 +#define MAX_LIGHT_TIMEOUT 10000 + // MQTT #define MQTT_HOST "mqtt.timovolkmann.de" #define MQTT_PORT 1883 @@ -77,12 +83,13 @@ extern void publishMessage(const char *topic, const char *msg); // RGB PWM LED extern void setupPWM(); -extern bool activateLight(); extern void setValueNM(int NM); -extern void getColorBasedOnValueNM(); +extern void getColorBasedOnValueNM(int valueNM); +extern void triggerLight(); // sensors void readSensors(); void toggleValve(); void setSoilProperties(int FC, int PWP, int SAT); -void setupStore(); \ No newline at end of file +void setupStore(); +void setLightningProperties(int NM, int minLX); \ No newline at end of file diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 79713d5..923189c 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -1,6 +1,6 @@ #include -int valueNM; +bool lightActive = false; // Colors in Array: purple, blue, green, yellow, orange, red, white int colorValueArray[][3] = {{125,0,125}, {0,0,255}, {0,255,0}, {255,255,0}, {255,140,0}, {255,0,0}, {255,255,255}}; int colorCounter = 6; @@ -14,9 +14,9 @@ const int resolution = 8; void setupPWM() { // Set pins as output - pinMode(PIN_LED_R, OUTPUT); - pinMode(PIN_LED_G, OUTPUT); - pinMode(PIN_LED_B, OUTPUT); + pinMode(LIGHT_LED_PIN_R, OUTPUT); + pinMode(LIGHT_LED_PIN_G, OUTPUT); + pinMode(LIGHT_LED_PIN_B, OUTPUT); // Configure LED PWM functionalitites ledcSetup(ledChannelRed, freq, resolution); @@ -24,35 +24,47 @@ void setupPWM() { ledcSetup(ledChannelBlue, freq, resolution); // Attach the channel to the GPIO2 to be controlled - ledcAttachPin(PIN_LED_R, ledChannelRed); - ledcAttachPin(PIN_LED_G, ledChannelGreen); - ledcAttachPin(PIN_LED_B, ledChannelBlue); + ledcAttachPin(LIGHT_LED_PIN_R, ledChannelRed); + ledcAttachPin(LIGHT_LED_PIN_G, ledChannelGreen); + ledcAttachPin(LIGHT_LED_PIN_B, ledChannelBlue); } void setValueNM(int NM) { - valueNM = NM; - getColorBasedOnValueNM(); + getColorBasedOnValueNM(NM); + // TODO: add persistenz for colorCounter } -void getColorBasedOnValueNM() { - if (valueNM <= 420) { +void getColorBasedOnValueNM(int valueNM) { + if (valueNM <= 420) { //Purple colorCounter = 0; } - else if (valueNM <= 490) { + else if (valueNM <= 490) { //Blue colorCounter = 1; } - else if (valueNM <= 575) { + else if (valueNM <= 575) { //Green colorCounter = 2; } - else if (valueNM <= 585) { + else if (valueNM <= 585) { //Yellow colorCounter = 3; } - else if (valueNM <= 650) { + else if (valueNM <= 650) { //Orange colorCounter = 4; } else if (valueNM > 650) { // 650 to 750 is red colorCounter = 5; } + Serial.println("New color set based on: "); + Serial.print(valueNM); +} + +bool shutdownLight() { + //digitalWrite(LIGHT_LED_PIN_R, LOW); + //digitalWrite(LIGHT_LED_PIN_G, LOW); + //digitalWrite(LIGHT_LED_PIN_B, LOW); + ledcWrite(ledChannelRed, 0); + ledcWrite(ledChannelGreen, 0); + ledcWrite(ledChannelBlue, 0); + return false; } bool activateLight() { @@ -60,4 +72,24 @@ bool activateLight() { ledcWrite(ledChannelGreen, colorValueArray[colorCounter][1]); ledcWrite(ledChannelBlue, colorValueArray[colorCounter][2]); return true; +} + +void lightTask(void *parameter) { + unsigned long lightTimeoutTimer = millis(); + if (lightActive == false) { + lightActive = activateLight(); + while (millis() - lightTimeoutTimer <= MAX_LIGHT_TIMEOUT) { + } + lightActive = shutdownLight(); + } +} + +void triggerLight() { + xTaskCreate( + lightTask, /* Task function. */ + "lightTask", /* String with name of task. */ + 2048, /* Stack size in bytes. */ + NULL, /* Parameter passed as input of the task */ + 1, /* Priority of the task. */ + NULL); /* Task handle. */ } \ No newline at end of file diff --git a/src/peripherals.cpp b/src/peripherals.cpp index 6d93cf9..b72df8b 100644 --- a/src/peripherals.cpp +++ b/src/peripherals.cpp @@ -19,6 +19,8 @@ int fieldCapacity = 44; int permanentWiltingPoint = 25; // Boden vollständig gesättigt bei (Prozent): Standard ist Humus int soilSaturation = 69; +// Helligkeitswert der mindestens vorhanden sein muss +int minimumLightValueLX = 50; void readSensors() { StaticJsonDocument<128> doc; @@ -27,6 +29,9 @@ void readSensors() { Serial.print(lxValue); Serial.println(" lx"); doc["brightness"] = lxValue; + if(lxValue < minimumLightValueLX) { + triggerLight(); + } //sprintf(buffer, "%f", lxValue); //publishMessage(MQTT_BRIGHTNESS, buffer); @@ -148,3 +153,11 @@ void setSoilProperties(int FC, int PWP, int SAT) { Serial.println(soilSaturation); } +void setLightningProperties(int NM, int minLX) { + setValueNM(NM); + minimumLightValueLX = minLX; + Serial.print("new minimum Light Value LX: "); + Serial.println(minimumLightValueLX); + // TODO: add Persistenz for minLX +} + From 18b5c0bfeceb30e12c570e73ae16fb9bc390c4e1 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Sun, 12 Jul 2020 18:28:59 +0200 Subject: [PATCH 14/23] Added class to get timestamps from NTP server --- src/connections.cpp | 2 +- src/header.h | 11 ++++++++++- src/lightChecker.cpp | 4 +++- src/main.cpp | 1 + src/ntpManager.cpp | 41 +++++++++++++++++++++++++++++++++++++++++ src/peripherals.cpp | 44 ++++++++++++++++++++++++++++++++++++-------- 6 files changed, 92 insertions(+), 11 deletions(-) create mode 100644 src/ntpManager.cpp diff --git a/src/connections.cpp b/src/connections.cpp index a2cea3d..bb0dca5 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -121,7 +121,7 @@ Serial.println("receiving light treshold..."); if (err == DeserializationError::Ok) { int nm = doc["nm"]; int minLX = doc["minLX"]; - setLightningProperties(nm, minLX); + setLightProperties(nm, minLX); } else { Serial.println(err.c_str()); } diff --git a/src/header.h b/src/header.h index c9ec72a..df7db75 100644 --- a/src/header.h +++ b/src/header.h @@ -15,6 +15,7 @@ #include #include #include +#include "time.h" // fix for core panic during wifi initialization #define configMINIMAL_STACK_SIZE 4096 @@ -87,12 +88,20 @@ extern void setValueNM(int NM); extern void getColorBasedOnValueNM(int valueNM); extern void triggerLight(); +// NTP Timestamps +void printTimestamp(); +void setupNTP(); +bool checkForDay(); +int getCurrentHour(); + // sensors void readSensors(); void toggleValve(); void setSoilProperties(int FC, int PWP, int SAT); void setupStore(); -void setLightningProperties(int NM, int minLX); +void setLightProperties(int NM, int minLX); +void restoreLightProbs(); +void persistLightProps(int NM, int minLX); void takeSemaphore(); void releaseSemaphore(); diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 923189c..5ecf944 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -31,7 +31,6 @@ void setupPWM() { void setValueNM(int NM) { getColorBasedOnValueNM(NM); - // TODO: add persistenz for colorCounter } void getColorBasedOnValueNM(int valueNM) { @@ -75,6 +74,7 @@ bool activateLight() { } void lightTask(void *parameter) { + takeSemaphore(); unsigned long lightTimeoutTimer = millis(); if (lightActive == false) { lightActive = activateLight(); @@ -82,6 +82,8 @@ void lightTask(void *parameter) { } lightActive = shutdownLight(); } + releaseSemaphore(); + vTaskDelete(NULL); } void triggerLight() { diff --git a/src/main.cpp b/src/main.cpp index 56f2f2c..9b624f6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -29,6 +29,7 @@ void setup() { setupPWM(); setupTemperatureSensor(); setupCapacitiveSoilMoistureSensor(); + setupNTP(); // esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 1000000); Serial.println("Setup complete..."); Serial.println(); diff --git a/src/ntpManager.cpp b/src/ntpManager.cpp new file mode 100644 index 0000000..ef5be48 --- /dev/null +++ b/src/ntpManager.cpp @@ -0,0 +1,41 @@ +#include + +const char* ntpServer = "pool.ntp.org"; +const long gmtOffset_sec = 3600; +const int daylightOffset_sec = 3600; + +// start and end hour of the date +const int dayStart = 8; +const int dayEnd = 20; +struct tm timeinfo; + +void setupNTP() { + if (WiFi.isConnected()) { + Serial.println("WiFi OK. Getting Timestamp"); + configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); + printTimestamp(); + } +} + +bool checkForDay() { + printTimestamp(); + if((getCurrentHour() > dayStart) && (getCurrentHour() < dayEnd)) { + return true; + } + else { + return false; + } +} + +int getCurrentHour() { + int currentHour = timeinfo.tm_hour; + return currentHour; +} + +void printTimestamp() { + if(!getLocalTime(&timeinfo)){ + Serial.println("Failed to obtain time"); + return; + } + Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); +} \ No newline at end of file diff --git a/src/peripherals.cpp b/src/peripherals.cpp index 1a47872..730aeb9 100644 --- a/src/peripherals.cpp +++ b/src/peripherals.cpp @@ -29,7 +29,7 @@ void readSensors() { Serial.print(lxValue); Serial.println(" lx"); doc["brightness"] = lxValue; - if(lxValue < minimumLightValueLX) { + if((lxValue < minimumLightValueLX) && checkForDay()) { triggerLight(); } //sprintf(buffer, "%f", lxValue); @@ -98,7 +98,7 @@ void toggleValve() { xTaskCreate( valveTask, /* Task function. */ "valveTask", /* String with name of task. */ - 2048, /* Stack size in bytes. */ + 2048, /* Stack size in bytes. */ NULL, /* Parameter passed as input of the task */ 1, /* Priority of the task. */ NULL); /* Task handle. */ @@ -142,6 +142,7 @@ void restoreSoilProps() { void setupStore() { NVS.begin("store"); restoreSoilProps(); + restoreLightProbs(); } void setSoilProperties(int FC, int PWP, int SAT) { @@ -157,11 +158,38 @@ void setSoilProperties(int FC, int PWP, int SAT) { Serial.println(soilSaturation); } -void setLightningProperties(int NM, int minLX) { - setValueNM(NM); - minimumLightValueLX = minLX; - Serial.print("new minimum Light Value LX: "); - Serial.println(minimumLightValueLX); - // TODO: add Persistenz for minLX +void persistLightProps(int NM, int minLX) { + takeSemaphore(); + Serial.println("persistSoilProps"); + bool n = NVS.setInt("nanoMeter", NM); + bool m = NVS.setInt("minimumLux", minLX); + if (n && m) { + Serial.println("Light properties sucessfully stored."); + NVS.commit(); + } + else { + Serial.println("error occured while trying to persist soil properties"); + } + releaseSemaphore(); } +void restoreLightProbs() { + Serial.println("restoreLightProps"); + int nm = NVS.getInt("nanoMeter"); + int minLX = NVS.getInt("minimumLux"); + if (nm != 0) { + setValueNM(nm); + } + if (minLX != 0) { + minimumLightValueLX = minLX; + } + Serial.print(minimumLightValueLX); +} + +void setLightProperties(int NM, int minLX) { + setValueNM(NM); + minimumLightValueLX = minLX; + persistLightProps(NM, minLX); + Serial.print("new minimum Light Value LX: "); + Serial.println(minimumLightValueLX); +} From 2cf9157ebb84e7875a89d233a79ea2e35e134525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Uribe=20Stengel?= Date: Tue, 14 Jul 2020 15:22:03 +0200 Subject: [PATCH 15/23] Change brightness to int and change publish intervall to one minute. --- src/header.h | 4 ++-- src/lightSensor.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/header.h b/src/header.h index 39aa356..d40476f 100644 --- a/src/header.h +++ b/src/header.h @@ -44,7 +44,7 @@ // MQTT #define MQTT_HOST "mqtt.timovolkmann.de" #define MQTT_PORT 1883 -#define MQTT_DEVICE_ID "esp-timo" +#define MQTT_DEVICE_ID "esp-andy" #define MQTT_TOPIC_BASE_SUB "smartgarden/commands" #define MQTT_TOPIC_BASE_PUB "smartgarden/updates" #define MQTT_PATH_PUB MQTT_TOPIC_BASE_PUB "/" MQTT_DEVICE_ID "/" @@ -52,7 +52,7 @@ // MQTT_DEVICE_ID "/#" // PUBLISH FREQUENCY (MS) -#define FREQUENCY 5000 //30000 +#define FREQUENCY 60000 // moisture extern void setupCapacitiveSoilMoistureSensor(); diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 776a3fd..78cb5ac 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -9,6 +9,6 @@ void setupLightSensor() { } float readLightSensorValue() { - float intensity = lightMeter.readLightLevel(); + int intensity = lightMeter.readLightLevel(); return intensity; } \ No newline at end of file From decdf72f7df7b99d76dd505ae367916decd07dfe Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Tue, 14 Jul 2020 18:23:29 +0200 Subject: [PATCH 16/23] resolved unresolved merge conflict xD --- src/header.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/header.h b/src/header.h index bacec3d..9f8f33a 100644 --- a/src/header.h +++ b/src/header.h @@ -55,13 +55,7 @@ // MQTT #define MQTT_HOST "mqtt.timovolkmann.de" #define MQTT_PORT 1883 -<<<<<<< HEAD -#define MQTT_DEVICE_ID "esp-andy" -||||||| cbf5199 #define MQTT_DEVICE_ID "esp-timo" -======= -#define MQTT_DEVICE_ID "esp-sebastian" ->>>>>>> 18b5c0bfeceb30e12c570e73ae16fb9bc390c4e1 #define MQTT_TOPIC_BASE_SUB "smartgarden/commands" #define MQTT_TOPIC_BASE_PUB "smartgarden/updates" #define MQTT_PATH_PUB MQTT_TOPIC_BASE_PUB "/" MQTT_DEVICE_ID "/" From 93561d4273f4f34ecd55625d40dcecf52d15bb90 Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Thu, 16 Jul 2020 10:55:17 +0200 Subject: [PATCH 17/23] implemented irrigation logic + autotoggle by mqtt --- src/capacitiveSoilMoistureSensor.cpp | 16 ++-- src/connections.cpp | 22 +++++- src/header.h | 11 ++- src/main.cpp | 2 + src/peripherals.cpp | 105 ++++++++++++++++++++------- 5 files changed, 116 insertions(+), 40 deletions(-) diff --git a/src/capacitiveSoilMoistureSensor.cpp b/src/capacitiveSoilMoistureSensor.cpp index 3b67af6..40e5367 100644 --- a/src/capacitiveSoilMoistureSensor.cpp +++ b/src/capacitiveSoilMoistureSensor.cpp @@ -20,14 +20,16 @@ int readCapacitiveSoilMoistureSensor() delay(2); } int measurement = total / numReadings; - Serial.print("soil moisture raw: "); - Serial.println(measurement); - // add the reading to the total: - //int measurement = analogRead(PIN_MS); - if (map(measurement, VALUE_AIR, VALUE_WATER, 0, 100) < 0) { + int finalRes = map(measurement, VALUE_AIR, VALUE_WATER, 0, 100); + Serial.print("current soil moisture: "); + Serial.println(finalRes); + + if (finalRes < 0) { return 0; - } else if (map(measurement, VALUE_AIR, VALUE_WATER, 0, 100) > 100) { + } else if (finalRes > 100) { return 100; - } else {return map(measurement, VALUE_AIR, VALUE_WATER, 0, 100);} + } else { + return finalRes; + } } \ No newline at end of file diff --git a/src/connections.cpp b/src/connections.cpp index bb0dca5..21071e0 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -11,6 +11,7 @@ extern "C" { #define MQTT_VALVE_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/valve" #define MQTT_SOIL_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/soil" #define MQTT_LIGHT_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/light" +#define MQTT_AUTO_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/automatic" TimerHandle_t mqttReconnectTimer; TimerHandle_t wifiReconnectTimer; @@ -114,7 +115,7 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { Serial.println(); if (strcmp(topic, MQTT_LIGHT_PROPERTIES) == 0) { -Serial.println("receiving light treshold..."); + Serial.println("receiving light treshold..."); Serial.println(topic); StaticJsonDocument<1024> doc; DeserializationError err = deserializeJson(doc, payload); @@ -129,7 +130,7 @@ Serial.println("receiving light treshold..."); if (strcmp(topic, MQTT_VALVE_COMMAND) == 0) { Serial.println("toggling valve..."); Serial.println(topic); - toggleValve(); + toggleValve(false); } if (strcmp(topic, MQTT_SOIL_PROPERTIES) == 0) { Serial.println("receiving soil thresholds..."); @@ -145,6 +146,19 @@ Serial.println("receiving light treshold..."); Serial.println(err.c_str()); } } + if (strcmp(topic, MQTT_AUTO_PROPERTIES) == 0) { + Serial.println("receiving auto settings..."); + Serial.println(topic); + StaticJsonDocument<1024> doc; + DeserializationError err = deserializeJson(doc, payload); + if (err == DeserializationError::Ok) { + bool ir = doc["irrigation"]; + bool li = doc["light"]; + setAutoProperties(li, ir); + } else { + Serial.println(err.c_str()); + } + } } void setupConnections() { @@ -174,8 +188,8 @@ void publishMessage(const char *topic, const char *msg) { if(mqttClient.connected()) { mqttClient.publish(topic, msg); Serial.print(topic); - Serial.println(" successfully sent.\n"); + Serial.println(" successfully sent."); } else { - Serial.println("couldn't send message. waiting for reconnect.\n"); + Serial.println("couldn't send message. waiting for reconnect."); } } diff --git a/src/header.h b/src/header.h index 9f8f33a..19655b0 100644 --- a/src/header.h +++ b/src/header.h @@ -39,7 +39,7 @@ // Ventil #define PIN_VALVE 32 -#define MAX_VALVE_TIMEOUT 10000 +#define MAX_VALVE_TIMEOUT 5000 // STATUS LED #define PIN_LED_R 2 @@ -63,7 +63,7 @@ // MQTT_DEVICE_ID "/#" // PUBLISH FREQUENCY (MS) -#define FREQUENCY 60000 +#define FREQUENCY 20000 // moisture extern void setupCapacitiveSoilMoistureSensor(); @@ -96,12 +96,15 @@ int getCurrentHour(); // sensors void readSensors(); -void toggleValve(); +void toggleValve(bool automatic); void setSoilProperties(int FC, int PWP, int SAT); void setupStore(); void setLightProperties(int NM, int minLX); -void restoreLightProbs(); +void restoreLightProps(); void persistLightProps(int NM, int minLX); +void restoreAutoProps(); +void persistAutoProps(bool light, bool irrigation); +void setAutoProperties(bool light, bool irrigation); void takeSemaphore(); void releaseSemaphore(); diff --git a/src/main.cpp b/src/main.cpp index 9b624f6..27b9bd7 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -34,6 +34,8 @@ void setup() { Serial.println("Setup complete..."); Serial.println(); Serial.println(); + // first read without delay + readSensors(); } void loop() { diff --git a/src/peripherals.cpp b/src/peripherals.cpp index 730aeb9..0ff6898 100644 --- a/src/peripherals.cpp +++ b/src/peripherals.cpp @@ -21,8 +21,12 @@ int permanentWiltingPoint = 25; int soilSaturation = 69; // Helligkeitswert der mindestens vorhanden sein muss int minimumLightValueLX = 50; +// switches for automatic light and irrigation control +bool automaticLight = true; +bool automaticIrrigation = true; void readSensors() { + Serial.println(); StaticJsonDocument<128> doc; float lxValue = readLightSensorValue(); Serial.print("Light intensity: "); @@ -32,30 +36,33 @@ void readSensors() { if((lxValue < minimumLightValueLX) && checkForDay()) { triggerLight(); } - //sprintf(buffer, "%f", lxValue); - //publishMessage(MQTT_BRIGHTNESS, buffer); int mstValue = readCapacitiveSoilMoistureSensor(); Serial.print("Soil moisture: "); Serial.println(mstValue); - // sprintf(buffer, "%i", mstValue); - // publishMessage(MQTT_MOISTURE, buffer); + // if (mstValue > fieldCapacity) { + // Serial.println("Field capacity reached. No irrigation needed. "); + // } + // if (mstValue < permanentWiltingPoint) { + // Serial.println("Permanent wilting point reached. Plant needs irrigation. "); + // } + if (automaticIrrigation) { + toggleValve(true); + } + doc["moisture"] = mstValue; float humidityValue = readHumidity(); Serial.print("Humidity: "); Serial.println(humidityValue); - // sprintf(buffer, "%f", humidityValue); - // publishMessage(MQTT_HUMIDITY, buffer); + doc["humidity"] = humidityValue; float temperatureValue = readTemperature(); Serial.print("Temperature: "); Serial.println(temperatureValue); - // sprintf(buffer, "%f", temperatureValue); - // publishMessage(MQTT_TEMPERATURE, buffer); + doc["temperature"] = temperatureValue; - Serial.print("\n"); serializeJson(doc, buffer); publishMessage(MQTT_SENSOR_DATA, buffer); } @@ -76,31 +83,42 @@ bool closeValve() { void valveTask(void *parameter) { takeSemaphore(); + bool isAutomatic = (bool)parameter; + Serial.println("Valve task triggered."); unsigned long valveTimeoutTimer = millis(); - bool valveOpen = openValve(); + bool valveOpen = false; + int initialSoilMoisture = readCapacitiveSoilMoistureSensor(); + + if (initialSoilMoisture > permanentWiltingPoint) { + Serial.println("Soil contains enough water. No irrigation needed. "); + } else { + valveOpen = openValve(); + } while (valveOpen) { delay(500); int mstValue = readCapacitiveSoilMoistureSensor(); - if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) { + if (mstValue > fieldCapacity) { // && isAutomatic + Serial.println("Field capacity reached. No irrigation needed. "); + valveOpen = closeValve(); + } + if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) { + Serial.println("Irrigation timeout reached. close valve. "); valveOpen = closeValve(); } - // if (mstValue > 80) { - // valveOpen = closeValve(); - // } } releaseSemaphore(); vTaskDelete(NULL); } -void toggleValve() { +void toggleValve(bool automatic) { xTaskCreate( valveTask, /* Task function. */ "valveTask", /* String with name of task. */ 2048, /* Stack size in bytes. */ - NULL, /* Parameter passed as input of the task */ - 1, /* Priority of the task. */ + &automatic, /* Parameter passed as input of the task */ + 3, /* Priority of the task. */ NULL); /* Task handle. */ } @@ -134,15 +152,19 @@ void restoreSoilProps() { if (sat != 0) { soilSaturation = sat; } - Serial.print(fieldCapacity); - Serial.print(permanentWiltingPoint); - Serial.print(soilSaturation); + Serial.print("fieldCapacity: "); + Serial.println(fieldCapacity); + Serial.print("permanentWiltingPoint: "); + Serial.println(permanentWiltingPoint); + Serial.print("soilSaturation: "); + Serial.println(soilSaturation); } void setupStore() { NVS.begin("store"); restoreSoilProps(); - restoreLightProbs(); + restoreLightProps(); + restoreAutoProps(); } void setSoilProperties(int FC, int PWP, int SAT) { @@ -160,7 +182,7 @@ void setSoilProperties(int FC, int PWP, int SAT) { void persistLightProps(int NM, int minLX) { takeSemaphore(); - Serial.println("persistSoilProps"); + Serial.println("persistLightProps"); bool n = NVS.setInt("nanoMeter", NM); bool m = NVS.setInt("minimumLux", minLX); if (n && m) { @@ -168,12 +190,12 @@ void persistLightProps(int NM, int minLX) { NVS.commit(); } else { - Serial.println("error occured while trying to persist soil properties"); + Serial.println("error occured while trying to persist light properties"); } releaseSemaphore(); } -void restoreLightProbs() { +void restoreLightProps() { Serial.println("restoreLightProps"); int nm = NVS.getInt("nanoMeter"); int minLX = NVS.getInt("minimumLux"); @@ -183,7 +205,7 @@ void restoreLightProbs() { if (minLX != 0) { minimumLightValueLX = minLX; } - Serial.print(minimumLightValueLX); + Serial.println(minimumLightValueLX); } void setLightProperties(int NM, int minLX) { @@ -193,3 +215,36 @@ void setLightProperties(int NM, int minLX) { Serial.print("new minimum Light Value LX: "); Serial.println(minimumLightValueLX); } + +void persistAutoProps(bool light, bool irrigation) { + takeSemaphore(); + Serial.println("persistAutoProps"); + // saved in NVS as Integer: 1 = true, 2 = false, 0 = not persisted, use standard settings + bool n = NVS.setInt("automaticLight", (light ? 1 : 2)); + bool m = NVS.setInt("automaticIrrigation", (irrigation ? 1 : 2)); + if (n && m) { + NVS.commit(); + Serial.println("Auto properties sucessfully stored."); + } else { + Serial.println("error occured while trying to persist auto properties"); + } + releaseSemaphore(); +} + +void restoreAutoProps() { + Serial.println("restoreLightProps"); + int li = NVS.getInt("automaticLight"); + int ir = NVS.getInt("automaticIrrigation"); + automaticLight = (bool) (li != 2); + automaticIrrigation = (bool) (ir != 2); + Serial.println(minimumLightValueLX); +} + +void setAutoProperties(bool light, bool irrigation) { + automaticLight = light; + automaticIrrigation = irrigation; + persistAutoProps(light, irrigation); + Serial.print("new auto settings: "); + Serial.println(automaticLight); + Serial.println(automaticIrrigation); +} \ No newline at end of file From 5136a4619739eed5a33086bb32931afdd7121add Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Wed, 22 Jul 2020 16:37:31 +0200 Subject: [PATCH 18/23] replaced device_id with UUID --- platformio.ini | 2 +- src/connections.cpp | 39 ++++++++++++++++++++++++---- src/header.h | 6 +++-- src/peripherals.cpp | 62 +++++++++++++++++++++++++++++++++++---------- 4 files changed, 88 insertions(+), 21 deletions(-) diff --git a/platformio.ini b/platformio.ini index e211cbf..28c817a 100644 --- a/platformio.ini +++ b/platformio.ini @@ -25,4 +25,4 @@ lib_deps = ; MQTT@^2.4.7 PubSubClient@^2.8 ArduinoNvs@^2.5 - ; ESPRandom@^1.3.3 \ No newline at end of file + ESPRandom@^1.3.3 \ No newline at end of file diff --git a/src/connections.cpp b/src/connections.cpp index 21071e0..c702145 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -8,10 +8,14 @@ extern "C" { #include "freertos/timers.h" } -#define MQTT_VALVE_COMMAND MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/valve" -#define MQTT_SOIL_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/soil" -#define MQTT_LIGHT_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/light" -#define MQTT_AUTO_PROPERTIES MQTT_TOPIC_BASE_SUB "/" MQTT_DEVICE_ID "/automatic" +// #define MQTT_VALVE_COMMAND(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/valve") +// #define MQTT_SOIL_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/soil") +// #define MQTT_LIGHT_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/light") +// #define MQTT_AUTO_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/automatic") +char MQTT_VALVE_COMMAND[72]; +char MQTT_SOIL_PROPERTIES[72]; +char MQTT_LIGHT_PROPERTIES[72]; +char MQTT_AUTO_PROPERTIES[72]; TimerHandle_t mqttReconnectTimer; TimerHandle_t wifiReconnectTimer; @@ -56,7 +60,7 @@ void connectMQTT() { // mqttClient.begin(MQTT_HOST, MQTT_PORT, client); mqttClient.setServer(MQTT_HOST, MQTT_PORT); mqttClient.disconnect(); - mqttClient.connect(MQTT_DEVICE_ID); + mqttClient.connect(getDeviceIDcharArr()); if (mqttClient.connected()) { Serial.println("Connected!"); } else { @@ -161,7 +165,32 @@ void onMqttMessage(char *topic, byte *payload, unsigned int payload_length) { } } +void constructMQTTpaths() { + strcpy(MQTT_VALVE_COMMAND, MQTT_TOPIC_BASE_SUB "/"); + strcat(MQTT_VALVE_COMMAND, getDeviceIDcharArr()); + strcat(MQTT_VALVE_COMMAND, "/valve"); + + strcpy(MQTT_SOIL_PROPERTIES, MQTT_TOPIC_BASE_SUB "/"); + strcat(MQTT_SOIL_PROPERTIES, getDeviceIDcharArr()); + strcat(MQTT_SOIL_PROPERTIES, "/soil"); + + strcpy(MQTT_LIGHT_PROPERTIES, MQTT_TOPIC_BASE_SUB "/"); + strcat(MQTT_LIGHT_PROPERTIES, getDeviceIDcharArr()); + strcat(MQTT_LIGHT_PROPERTIES, "/light"); + + strcpy(MQTT_AUTO_PROPERTIES, MQTT_TOPIC_BASE_SUB "/"); + strcat(MQTT_AUTO_PROPERTIES, getDeviceIDcharArr()); + strcat(MQTT_AUTO_PROPERTIES, "/automatic"); + + Serial.println("MQTT_COMMANDS:"); + Serial.println(MQTT_VALVE_COMMAND); + Serial.println(MQTT_SOIL_PROPERTIES); + Serial.println(MQTT_LIGHT_PROPERTIES); + Serial.println(MQTT_AUTO_PROPERTIES); +} + void setupConnections() { + constructMQTTpaths(); Serial.println(); Serial.println(); disableCore0WDT(); diff --git a/src/header.h b/src/header.h index 19655b0..79820b2 100644 --- a/src/header.h +++ b/src/header.h @@ -55,10 +55,8 @@ // MQTT #define MQTT_HOST "mqtt.timovolkmann.de" #define MQTT_PORT 1883 -#define MQTT_DEVICE_ID "esp-timo" #define MQTT_TOPIC_BASE_SUB "smartgarden/commands" #define MQTT_TOPIC_BASE_PUB "smartgarden/updates" -#define MQTT_PATH_PUB MQTT_TOPIC_BASE_PUB "/" MQTT_DEVICE_ID "/" #define MQTT_PATH_SUB MQTT_TOPIC_BASE_SUB "/#" // MQTT_DEVICE_ID "/#" @@ -106,5 +104,9 @@ void restoreAutoProps(); void persistAutoProps(bool light, bool irrigation); void setAutoProperties(bool light, bool irrigation); +void initDeviceID(); +String getDeviceID(); +const char *getDeviceIDcharArr(); + void takeSemaphore(); void releaseSemaphore(); diff --git a/src/peripherals.cpp b/src/peripherals.cpp index 0ff6898..fb661b6 100644 --- a/src/peripherals.cpp +++ b/src/peripherals.cpp @@ -1,6 +1,8 @@ #include #include +#include #include +#include #include //using namespace std; @@ -9,7 +11,7 @@ extern "C" { #include "freertos/task.h" } -#define MQTT_SENSOR_DATA MQTT_PATH_PUB "data" +char MQTT_SENSOR_DATA_TOPIC[64]; char buffer[128]; @@ -24,6 +26,8 @@ int minimumLightValueLX = 50; // switches for automatic light and irrigation control bool automaticLight = true; bool automaticIrrigation = true; +// make sure device irrigates until fieldcapacity is reached +bool irrigateUntilFC = false; void readSensors() { Serial.println(); @@ -40,12 +44,7 @@ void readSensors() { int mstValue = readCapacitiveSoilMoistureSensor(); Serial.print("Soil moisture: "); Serial.println(mstValue); - // if (mstValue > fieldCapacity) { - // Serial.println("Field capacity reached. No irrigation needed. "); - // } - // if (mstValue < permanentWiltingPoint) { - // Serial.println("Permanent wilting point reached. Plant needs irrigation. "); - // } + if (automaticIrrigation) { toggleValve(true); } @@ -64,7 +63,7 @@ void readSensors() { doc["temperature"] = temperatureValue; serializeJson(doc, buffer); - publishMessage(MQTT_SENSOR_DATA, buffer); + publishMessage(MQTT_SENSOR_DATA_TOPIC, buffer); } bool openValve() { @@ -83,16 +82,18 @@ bool closeValve() { void valveTask(void *parameter) { takeSemaphore(); - bool isAutomatic = (bool)parameter; - Serial.println("Valve task triggered."); + bool isAutomatic = (bool) parameter; + Serial.print(isAutomatic); + Serial.println(" Valve task triggered."); unsigned long valveTimeoutTimer = millis(); bool valveOpen = false; int initialSoilMoisture = readCapacitiveSoilMoistureSensor(); - if (initialSoilMoisture > permanentWiltingPoint) { - Serial.println("Soil contains enough water. No irrigation needed. "); - } else { + if (initialSoilMoisture <= permanentWiltingPoint || irrigateUntilFC) { valveOpen = openValve(); + irrigateUntilFC = true; + } else { + Serial.println("Soil contains enough water. No irrigation needed. "); } while (valveOpen) { @@ -102,6 +103,7 @@ void valveTask(void *parameter) { if (mstValue > fieldCapacity) { // && isAutomatic Serial.println("Field capacity reached. No irrigation needed. "); valveOpen = closeValve(); + irrigateUntilFC = false; } if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) { Serial.println("Irrigation timeout reached. close valve. "); @@ -161,10 +163,18 @@ void restoreSoilProps() { } void setupStore() { + NVS.begin("store"); + initDeviceID(); restoreSoilProps(); restoreLightProps(); restoreAutoProps(); + + strcpy(MQTT_SENSOR_DATA_TOPIC, MQTT_TOPIC_BASE_PUB "/"); + strcat(MQTT_SENSOR_DATA_TOPIC, getDeviceIDcharArr()); + strcat(MQTT_SENSOR_DATA_TOPIC, "/data"); + Serial.println("MQTT_SENSOR_DATA_TOPIC:"); + Serial.println(MQTT_SENSOR_DATA_TOPIC); } void setSoilProperties(int FC, int PWP, int SAT) { @@ -247,4 +257,30 @@ void setAutoProperties(bool light, bool irrigation) { Serial.print("new auto settings: "); Serial.println(automaticLight); Serial.println(automaticIrrigation); +} + +String DEVICE_ID = ""; + +void initDeviceID() { + DEVICE_ID = NVS.getString("UUID"); + if (!DEVICE_ID.isEmpty()) { + Serial.print("Fetched Device ID from NVS: "); + Serial.println(DEVICE_ID); + } else { + uint8_t uuid[16]; + ESPRandom::uuid(uuid); + DEVICE_ID = ESPRandom::uuidToString(uuid); + NVS.setString("UUID", DEVICE_ID); + NVS.commit(); + Serial.print("New Device ID: "); + Serial.println(DEVICE_ID); + } +} + +String getDeviceID() { + return DEVICE_ID; +} + +const char* getDeviceIDcharArr() { + return DEVICE_ID.c_str(); } \ No newline at end of file From 80b6e5269f888cbe3470cff503f9af57a8ebdfe6 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 22 Jul 2020 16:52:15 +0200 Subject: [PATCH 19/23] added comments for ntpManager --- src/ntpManager.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/ntpManager.cpp b/src/ntpManager.cpp index ef5be48..b4c1705 100644 --- a/src/ntpManager.cpp +++ b/src/ntpManager.cpp @@ -1,14 +1,19 @@ #include +// Url to ntp server const char* ntpServer = "pool.ntp.org"; +// Time offset based on gmt in seconds const long gmtOffset_sec = 3600; +// Offset in seconds for daylight saving time const int daylightOffset_sec = 3600; -// start and end hour of the date +// Start and end hour of the date const int dayStart = 8; const int dayEnd = 20; +// Time info structure comes from time.h struct tm timeinfo; +// If wifi is connected configure time of esp32 void setupNTP() { if (WiFi.isConnected()) { Serial.println("WiFi OK. Getting Timestamp"); @@ -17,6 +22,7 @@ void setupNTP() { } } +// Method to check if it is currently day or night bool checkForDay() { printTimestamp(); if((getCurrentHour() > dayStart) && (getCurrentHour() < dayEnd)) { @@ -27,11 +33,13 @@ bool checkForDay() { } } +// Method to get current hour in 24 hour format int getCurrentHour() { int currentHour = timeinfo.tm_hour; return currentHour; } +// Method to print a timestamp void printTimestamp() { if(!getLocalTime(&timeinfo)){ Serial.println("Failed to obtain time"); From 08bdb58a6cb42eed6740c5e6aa3f3c5ba18d4ce4 Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Wed, 22 Jul 2020 18:55:35 +0200 Subject: [PATCH 20/23] refactored and restructured --- src/capacitiveSoilMoistureSensor.cpp | 11 +-- src/capacitiveSoilMoistureSensor.h | 2 + src/common.h | 46 ++++++++++ src/connections.cpp | 25 +++--- src/connections.h | 5 ++ src/header.h | 112 ------------------------ src/lightChecker.cpp | 15 ++-- src/lightChecker.h | 3 + src/lightSensor.cpp | 5 +- src/lightSensor.h | 2 + src/main.cpp | 29 ++----- src/ntpManager.cpp | 4 +- src/ntpManager.h | 4 + src/sensors.cpp | 65 ++++++++++++++ src/sensors.h | 2 + src/{peripherals.cpp => store.cpp} | 125 +-------------------------- src/store.h | 29 +++++++ src/temperatureSensor.cpp | 6 +- src/temperatureSensor.h | 3 + src/valve.cpp | 66 ++++++++++++++ src/valve.h | 1 + 21 files changed, 268 insertions(+), 292 deletions(-) create mode 100644 src/capacitiveSoilMoistureSensor.h create mode 100644 src/common.h create mode 100644 src/connections.h delete mode 100644 src/header.h create mode 100644 src/lightChecker.h create mode 100644 src/lightSensor.h create mode 100644 src/ntpManager.h create mode 100644 src/sensors.cpp create mode 100644 src/sensors.h rename src/{peripherals.cpp => store.cpp} (59%) create mode 100644 src/store.h create mode 100644 src/temperatureSensor.h create mode 100644 src/valve.cpp create mode 100644 src/valve.h diff --git a/src/capacitiveSoilMoistureSensor.cpp b/src/capacitiveSoilMoistureSensor.cpp index 40e5367..776046d 100644 --- a/src/capacitiveSoilMoistureSensor.cpp +++ b/src/capacitiveSoilMoistureSensor.cpp @@ -1,8 +1,7 @@ /* Code for the Capacitive Soil Moisture Sensor */ - -#include +#include const int numReadings = 20; @@ -10,12 +9,10 @@ void setupCapacitiveSoilMoistureSensor() { // pinMode(PIN_MS, INPUT); } -int readCapacitiveSoilMoistureSensor() -{ - int total = 0; // the running total +int readCapacitiveSoilMoistureSensor() { + int total = 0; // the running total // read from the sensor: - for (int readIndex = 0; readIndex < numReadings; readIndex++) - { + for (int readIndex = 0; readIndex < numReadings; readIndex++) { total = total + analogRead(PIN_MS); delay(2); } diff --git a/src/capacitiveSoilMoistureSensor.h b/src/capacitiveSoilMoistureSensor.h new file mode 100644 index 0000000..573661d --- /dev/null +++ b/src/capacitiveSoilMoistureSensor.h @@ -0,0 +1,2 @@ +void setupCapacitiveSoilMoistureSensor(); +int readCapacitiveSoilMoistureSensor(); \ No newline at end of file diff --git a/src/common.h b/src/common.h new file mode 100644 index 0000000..716844a --- /dev/null +++ b/src/common.h @@ -0,0 +1,46 @@ +#include + +// PUBLISH FREQUENCY (MS) +#define FREQUENCY 20000 + +// fix for core panic during wifi initialization +// #define configMINIMAL_STACK_SIZE 4096 +// #define CONFIG_TIMER_TASK_STACK_SIZE 8192 + +// BH1750 lightsensor +#define MIN_LIGHT 0 +#define MAX_LIGHT 54612 + +// DHT11 +#define PIN_DHT11 14 + +// MQ-135 +#define PIN_MQ135_A 12 +#define PIN_MQ135_D 13 + +// MOISTURE SENSOR // A7 +#define PIN_MS 35 +#define VALUE_WATER 1650 +#define VALUE_AIR 3500 + +// Ventil +#define PIN_VALVE 32 +#define MAX_VALVE_TIMEOUT 5000 + +// STATUS LED +#define PIN_LED_R 2 +#define PIN_LED_G 0 +#define PIN_LED_B 4 + +// LIGHT LED +#define LIGHT_LED_PIN_R 27 +#define LIGHT_LED_PIN_G 26 +#define LIGHT_LED_PIN_B 25 +#define MAX_LIGHT_TIMEOUT (FREQUENCY - 5) + +// MQTT +#define MQTT_HOST "mqtt.timovolkmann.de" +#define MQTT_PORT 1883 +#define MQTT_TOPIC_BASE_SUB "smartgarden/commands" +#define MQTT_TOPIC_BASE_PUB "smartgarden/updates" +#define MQTT_PATH_SUB MQTT_TOPIC_BASE_SUB "/#" diff --git a/src/connections.cpp b/src/connections.cpp index c702145..2f7d557 100644 --- a/src/connections.cpp +++ b/src/connections.cpp @@ -1,17 +1,19 @@ #include -// #include +#include #include -#include +#include +#include +#include +#include +#include extern "C" { -#include "freertos/FreeRTOS.h" -#include "freertos/timers.h" + #include "freertos/FreeRTOS.h" + #include "freertos/timers.h" } -// #define MQTT_VALVE_COMMAND(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/valve") -// #define MQTT_SOIL_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/soil") -// #define MQTT_LIGHT_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/light") -// #define MQTT_AUTO_PROPERTIES(device_id) (MQTT_TOPIC_BASE_SUB "/" device_id "/automatic") +#include + char MQTT_VALVE_COMMAND[72]; char MQTT_SOIL_PROPERTIES[72]; char MQTT_LIGHT_PROPERTIES[72]; @@ -77,13 +79,6 @@ void connectMQTT() { 2, &mqttTask, 1); - // xTaskCreate( - // mqttLoop, /* Task function. */ - // "mqttLoop", /* String with name of task. */ - // 8192, /* Stack size in bytes. */ - // NULL, /* Parameter passed as input of the task */ - // 1, /* Priority of the task. */ - // &mqttTask); /* Task handle. */ } void WiFiEvent(WiFiEvent_t event, WiFiEventInfo_t info) { diff --git a/src/connections.h b/src/connections.h new file mode 100644 index 0000000..7e035fa --- /dev/null +++ b/src/connections.h @@ -0,0 +1,5 @@ +void connectWiFi(); +void mqttLoop(void *parameter); +void connectMQTT(); +void setupConnections(); +void publishMessage(const char *topic, const char *msg); \ No newline at end of file diff --git a/src/header.h b/src/header.h deleted file mode 100644 index 79820b2..0000000 --- a/src/header.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - Header file for the SmartGarden project -*/ - -#define HEADER_H - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include "time.h" - -// fix for core panic during wifi initialization -#define configMINIMAL_STACK_SIZE 4096 -#define CONFIG_TIMER_TASK_STACK_SIZE 8192 - -// BH1750 lightsensor -#define MIN_LIGHT 0 -#define MAX_LIGHT 54612 - -// DHT11 -#define PIN_DHT11 14 - -// MQ-135 -#define PIN_MQ135_A 12 -#define PIN_MQ135_D 13 - -// MOISTURE SENSOR // A7 -#define PIN_MS 35 -#define VALUE_WATER 1650 -#define VALUE_AIR 3500 - -// Ventil -#define PIN_VALVE 32 -#define MAX_VALVE_TIMEOUT 5000 - -// STATUS LED -#define PIN_LED_R 2 -#define PIN_LED_G 0 -#define PIN_LED_B 4 - -// LIGHT LED -#define LIGHT_LED_PIN_R 27 -#define LIGHT_LED_PIN_G 26 -#define LIGHT_LED_PIN_B 25 -#define MAX_LIGHT_TIMEOUT 10000 - -// MQTT -#define MQTT_HOST "mqtt.timovolkmann.de" -#define MQTT_PORT 1883 -#define MQTT_TOPIC_BASE_SUB "smartgarden/commands" -#define MQTT_TOPIC_BASE_PUB "smartgarden/updates" -#define MQTT_PATH_SUB MQTT_TOPIC_BASE_SUB "/#" -// MQTT_DEVICE_ID "/#" - -// PUBLISH FREQUENCY (MS) -#define FREQUENCY 20000 - -// moisture -extern void setupCapacitiveSoilMoistureSensor(); -extern int readCapacitiveSoilMoistureSensor(); - -// light -extern void setupLightSensor(); -extern float readLightSensorValue(); - -// temperature & humidity -extern void setupTemperatureSensor(); -extern float readHumidity(); -extern float readTemperature(); - -// mqtt & wifi -extern void setupConnections(); -extern void publishMessage(const char *topic, const char *msg); - -// RGB PWM LED -extern void setupPWM(); -extern void setValueNM(int NM); -extern void getColorBasedOnValueNM(int valueNM); -extern void triggerLight(); - -// NTP Timestamps -void printTimestamp(); -void setupNTP(); -bool checkForDay(); -int getCurrentHour(); - -// sensors -void readSensors(); -void toggleValve(bool automatic); -void setSoilProperties(int FC, int PWP, int SAT); -void setupStore(); -void setLightProperties(int NM, int minLX); -void restoreLightProps(); -void persistLightProps(int NM, int minLX); -void restoreAutoProps(); -void persistAutoProps(bool light, bool irrigation); -void setAutoProperties(bool light, bool irrigation); - -void initDeviceID(); -String getDeviceID(); -const char *getDeviceIDcharArr(); - -void takeSemaphore(); -void releaseSemaphore(); diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 5ecf944..8a8a87d 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -1,4 +1,4 @@ -#include +#include bool lightActive = false; // Colors in Array: purple, blue, green, yellow, orange, red, white @@ -29,10 +29,6 @@ void setupPWM() { ledcAttachPin(LIGHT_LED_PIN_B, ledChannelBlue); } -void setValueNM(int NM) { - getColorBasedOnValueNM(NM); -} - void getColorBasedOnValueNM(int valueNM) { if (valueNM <= 420) { //Purple colorCounter = 0; @@ -56,10 +52,11 @@ void getColorBasedOnValueNM(int valueNM) { Serial.print(valueNM); } +void setValueNM(int NM) { + getColorBasedOnValueNM(NM); +} + bool shutdownLight() { - //digitalWrite(LIGHT_LED_PIN_R, LOW); - //digitalWrite(LIGHT_LED_PIN_G, LOW); - //digitalWrite(LIGHT_LED_PIN_B, LOW); ledcWrite(ledChannelRed, 0); ledcWrite(ledChannelGreen, 0); ledcWrite(ledChannelBlue, 0); @@ -74,7 +71,6 @@ bool activateLight() { } void lightTask(void *parameter) { - takeSemaphore(); unsigned long lightTimeoutTimer = millis(); if (lightActive == false) { lightActive = activateLight(); @@ -82,7 +78,6 @@ void lightTask(void *parameter) { } lightActive = shutdownLight(); } - releaseSemaphore(); vTaskDelete(NULL); } diff --git a/src/lightChecker.h b/src/lightChecker.h new file mode 100644 index 0000000..2057252 --- /dev/null +++ b/src/lightChecker.h @@ -0,0 +1,3 @@ +void setupPWM(); +void setValueNM(int NM); +void triggerLight(); \ No newline at end of file diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 78cb5ac..612f761 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -1,4 +1,7 @@ -#include +#include +#include +#include +#include BH1750 lightMeter; diff --git a/src/lightSensor.h b/src/lightSensor.h new file mode 100644 index 0000000..b07a3b6 --- /dev/null +++ b/src/lightSensor.h @@ -0,0 +1,2 @@ +void setupLightSensor(); +float readLightSensorValue(); \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 27b9bd7..c6196c5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,9 +2,10 @@ Main file for the SmartGarden project */ -#include - -#include +#include +#include +#include +#include #define TIME_TO_SLEEP 30 volatile int noSleepTasks = 0; @@ -23,13 +24,10 @@ void setup() { digitalWrite(PIN_VALVE, LOW); + setupStore(); + setupSensors(); setupConnections(); - setupLightSensor(); - setupPWM(); - setupTemperatureSensor(); - setupCapacitiveSoilMoistureSensor(); - setupNTP(); // esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 1000000); Serial.println("Setup complete..."); Serial.println(); @@ -39,22 +37,9 @@ void setup() { } void loop() { - // read sensors + // main loop: read sensors if (millis() - sensorReadTimer >= FREQUENCY) { readSensors(); sensorReadTimer = millis(); - - // if(noSleepTasks == 0) { - // delay(200); - // esp_deep_sleep_start(); - // } } -} - -void takeSemaphore() { - noSleepTasks++; -} - -void releaseSemaphore() { - noSleepTasks--; } \ No newline at end of file diff --git a/src/ntpManager.cpp b/src/ntpManager.cpp index ef5be48..3161ff5 100644 --- a/src/ntpManager.cpp +++ b/src/ntpManager.cpp @@ -1,4 +1,6 @@ -#include +#include +#include +#include const char* ntpServer = "pool.ntp.org"; const long gmtOffset_sec = 3600; diff --git a/src/ntpManager.h b/src/ntpManager.h new file mode 100644 index 0000000..0fb627b --- /dev/null +++ b/src/ntpManager.h @@ -0,0 +1,4 @@ +void setupNTP(); +bool checkForDay(); +int getCurrentHour(); +void printTimestamp(); \ No newline at end of file diff --git a/src/sensors.cpp b/src/sensors.cpp new file mode 100644 index 0000000..71f3e00 --- /dev/null +++ b/src/sensors.cpp @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char buffer[128]; +char MQTT_SENSOR_DATA_TOPIC[64]; + +void setupSensors() { + setupLightSensor(); + setupPWM(); + setupTemperatureSensor(); + setupCapacitiveSoilMoistureSensor(); + setupNTP(); + + strcpy(MQTT_SENSOR_DATA_TOPIC, MQTT_TOPIC_BASE_PUB "/"); + strcat(MQTT_SENSOR_DATA_TOPIC, getDeviceIDcharArr()); + strcat(MQTT_SENSOR_DATA_TOPIC, "/data"); + Serial.println("MQTT_SENSOR_DATA_TOPIC:"); + Serial.println(MQTT_SENSOR_DATA_TOPIC); +} + +void readSensors() { + Serial.println(); + StaticJsonDocument<128> doc; + float lxValue = readLightSensorValue(); + Serial.print("Light intensity: "); + Serial.print(lxValue); + Serial.println(" lx"); + doc["brightness"] = lxValue; + if ((lxValue < minimumLightValueLX) && checkForDay()) { + triggerLight(); + } + + int mstValue = readCapacitiveSoilMoistureSensor(); + Serial.print("Soil moisture: "); + Serial.println(mstValue); + + if (automaticIrrigation) { + toggleValve(true); + } + + doc["moisture"] = mstValue; + + float humidityValue = readHumidity(); + Serial.print("Humidity: "); + Serial.println(humidityValue); + + doc["humidity"] = humidityValue; + + float temperatureValue = readTemperature(); + Serial.print("Temperature: "); + Serial.println(temperatureValue); + + doc["temperature"] = temperatureValue; + serializeJson(doc, buffer); + publishMessage(MQTT_SENSOR_DATA_TOPIC, buffer); +} diff --git a/src/sensors.h b/src/sensors.h new file mode 100644 index 0000000..8f52f9e --- /dev/null +++ b/src/sensors.h @@ -0,0 +1,2 @@ +void setupSensors(); +void readSensors(); \ No newline at end of file diff --git a/src/peripherals.cpp b/src/store.cpp similarity index 59% rename from src/peripherals.cpp rename to src/store.cpp index fb661b6..5aa7ac3 100644 --- a/src/peripherals.cpp +++ b/src/store.cpp @@ -1,19 +1,8 @@ -#include #include #include -#include -#include - -#include -//using namespace std; -extern "C" { -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -} - -char MQTT_SENSOR_DATA_TOPIC[64]; - -char buffer[128]; +#include +#include +#include // Feldkapazität des Bodens in Prozent: Standard ist Humus int fieldCapacity = 44; @@ -29,103 +18,7 @@ bool automaticIrrigation = true; // make sure device irrigates until fieldcapacity is reached bool irrigateUntilFC = false; -void readSensors() { - Serial.println(); - StaticJsonDocument<128> doc; - float lxValue = readLightSensorValue(); - Serial.print("Light intensity: "); - Serial.print(lxValue); - Serial.println(" lx"); - doc["brightness"] = lxValue; - if((lxValue < minimumLightValueLX) && checkForDay()) { - triggerLight(); - } - - int mstValue = readCapacitiveSoilMoistureSensor(); - Serial.print("Soil moisture: "); - Serial.println(mstValue); - - if (automaticIrrigation) { - toggleValve(true); - } - - doc["moisture"] = mstValue; - - float humidityValue = readHumidity(); - Serial.print("Humidity: "); - Serial.println(humidityValue); - - doc["humidity"] = humidityValue; - - float temperatureValue = readTemperature(); - Serial.print("Temperature: "); - Serial.println(temperatureValue); - - doc["temperature"] = temperatureValue; - serializeJson(doc, buffer); - publishMessage(MQTT_SENSOR_DATA_TOPIC, buffer); -} - -bool openValve() { - digitalWrite(PIN_VALVE, HIGH); - digitalWrite(PIN_LED_G, LOW); - digitalWrite(PIN_LED_B, HIGH); - return true; -} - -bool closeValve() { - digitalWrite(PIN_VALVE, LOW); - digitalWrite(PIN_LED_G, HIGH); - digitalWrite(PIN_LED_B, LOW); - return false; -} - -void valveTask(void *parameter) { - takeSemaphore(); - bool isAutomatic = (bool) parameter; - Serial.print(isAutomatic); - Serial.println(" Valve task triggered."); - unsigned long valveTimeoutTimer = millis(); - bool valveOpen = false; - int initialSoilMoisture = readCapacitiveSoilMoistureSensor(); - - if (initialSoilMoisture <= permanentWiltingPoint || irrigateUntilFC) { - valveOpen = openValve(); - irrigateUntilFC = true; - } else { - Serial.println("Soil contains enough water. No irrigation needed. "); - } - - while (valveOpen) { - delay(500); - int mstValue = readCapacitiveSoilMoistureSensor(); - - if (mstValue > fieldCapacity) { // && isAutomatic - Serial.println("Field capacity reached. No irrigation needed. "); - valveOpen = closeValve(); - irrigateUntilFC = false; - } - if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) { - Serial.println("Irrigation timeout reached. close valve. "); - valveOpen = closeValve(); - } - } - releaseSemaphore(); - vTaskDelete(NULL); -} - -void toggleValve(bool automatic) { - xTaskCreate( - valveTask, /* Task function. */ - "valveTask", /* String with name of task. */ - 2048, /* Stack size in bytes. */ - &automatic, /* Parameter passed as input of the task */ - 3, /* Priority of the task. */ - NULL); /* Task handle. */ -} - void persistSoilProps(int FC, int PWP, int SAT) { - takeSemaphore(); Serial.println("persistSoilProps"); bool f = NVS.setInt("fieldCapacity", FC); bool p = NVS.setInt("permanentWilt", PWP); @@ -137,7 +30,6 @@ void persistSoilProps(int FC, int PWP, int SAT) { else { Serial.println("error occured while trying to persist soil properties"); } - releaseSemaphore(); } void restoreSoilProps() { @@ -163,18 +55,11 @@ void restoreSoilProps() { } void setupStore() { - NVS.begin("store"); initDeviceID(); restoreSoilProps(); restoreLightProps(); restoreAutoProps(); - - strcpy(MQTT_SENSOR_DATA_TOPIC, MQTT_TOPIC_BASE_PUB "/"); - strcat(MQTT_SENSOR_DATA_TOPIC, getDeviceIDcharArr()); - strcat(MQTT_SENSOR_DATA_TOPIC, "/data"); - Serial.println("MQTT_SENSOR_DATA_TOPIC:"); - Serial.println(MQTT_SENSOR_DATA_TOPIC); } void setSoilProperties(int FC, int PWP, int SAT) { @@ -191,7 +76,6 @@ void setSoilProperties(int FC, int PWP, int SAT) { } void persistLightProps(int NM, int minLX) { - takeSemaphore(); Serial.println("persistLightProps"); bool n = NVS.setInt("nanoMeter", NM); bool m = NVS.setInt("minimumLux", minLX); @@ -202,7 +86,6 @@ void persistLightProps(int NM, int minLX) { else { Serial.println("error occured while trying to persist light properties"); } - releaseSemaphore(); } void restoreLightProps() { @@ -227,7 +110,6 @@ void setLightProperties(int NM, int minLX) { } void persistAutoProps(bool light, bool irrigation) { - takeSemaphore(); Serial.println("persistAutoProps"); // saved in NVS as Integer: 1 = true, 2 = false, 0 = not persisted, use standard settings bool n = NVS.setInt("automaticLight", (light ? 1 : 2)); @@ -238,7 +120,6 @@ void persistAutoProps(bool light, bool irrigation) { } else { Serial.println("error occured while trying to persist auto properties"); } - releaseSemaphore(); } void restoreAutoProps() { diff --git a/src/store.h b/src/store.h new file mode 100644 index 0000000..5830269 --- /dev/null +++ b/src/store.h @@ -0,0 +1,29 @@ +// Feldkapazität des Bodens in Prozent: Standard ist Humus +extern int fieldCapacity; +// PWP des Bodens in Prozent: Standard ist Humus +extern int permanentWiltingPoint; +// Boden vollständig gesättigt bei (Prozent): Standard ist Humus +extern int soilSaturation; +// Helligkeitswert der mindestens vorhanden sein muss +extern int minimumLightValueLX; +// switches for automatic light and irrigation control +extern bool automaticLight; +extern bool automaticIrrigation; +// make sure device irrigates until fieldcapacity is reached +extern bool irrigateUntilFC; +// Device UUID will be set on first boot. +extern String DEVICE_ID; + +void persistSoilProps(int FC, int PWP, int SAT); +void restoreSoilProps(); +void setupStore(); +void setSoilProperties(int FC, int PWP, int SAT); +void persistLightProps(int NM, int minLX); +void restoreLightProps(); +void setLightProperties(int NM, int minLX); +void persistAutoProps(bool light, bool irrigation); +void restoreAutoProps(); +void setAutoProperties(bool light, bool irrigation); +void initDeviceID(); +String getDeviceID(); +const char* getDeviceIDcharArr(); \ No newline at end of file diff --git a/src/temperatureSensor.cpp b/src/temperatureSensor.cpp index 61ba0be..83ffdc1 100644 --- a/src/temperatureSensor.cpp +++ b/src/temperatureSensor.cpp @@ -1,7 +1,9 @@ -#include +#include +#include +#include + #define DHTPIN PIN_DHT11 - #define DHTTYPE DHT11 diff --git a/src/temperatureSensor.h b/src/temperatureSensor.h new file mode 100644 index 0000000..a53a7aa --- /dev/null +++ b/src/temperatureSensor.h @@ -0,0 +1,3 @@ +void setupTemperatureSensor(); +float readHumidity(); +float readTemperature(); \ No newline at end of file diff --git a/src/valve.cpp b/src/valve.cpp new file mode 100644 index 0000000..29c7d07 --- /dev/null +++ b/src/valve.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +extern "C" { + #include "freertos/FreeRTOS.h" + #include "freertos/task.h" +} + +#include + +bool openValve() { + digitalWrite(PIN_VALVE, HIGH); + digitalWrite(PIN_LED_G, LOW); + digitalWrite(PIN_LED_B, HIGH); + return true; +} + +bool closeValve() { + digitalWrite(PIN_VALVE, LOW); + digitalWrite(PIN_LED_G, HIGH); + digitalWrite(PIN_LED_B, LOW); + return false; +} + +void valveTask(void *parameter) { + bool isAutomatic = (bool)parameter; + Serial.print(isAutomatic); + Serial.println(" Valve task triggered."); + unsigned long valveTimeoutTimer = millis(); + bool valveOpen = false; + int initialSoilMoisture = readCapacitiveSoilMoistureSensor(); + + if (initialSoilMoisture <= permanentWiltingPoint || irrigateUntilFC) { + valveOpen = openValve(); + irrigateUntilFC = true; + } else { + Serial.println("Soil contains enough water. No irrigation needed. "); + } + + while (valveOpen) { + delay(500); + int mstValue = readCapacitiveSoilMoistureSensor(); + + if (mstValue > fieldCapacity) { // && isAutomatic + Serial.println("Field capacity reached. No irrigation needed. "); + valveOpen = closeValve(); + irrigateUntilFC = false; + } + if (millis() - valveTimeoutTimer >= MAX_VALVE_TIMEOUT) { + Serial.println("Irrigation timeout reached. close valve. "); + valveOpen = closeValve(); + } + } + vTaskDelete(NULL); +} + +void toggleValve(bool automatic) { + xTaskCreate( + valveTask, /* Task function. */ + "valveTask", /* String with name of task. */ + 2048, /* Stack size in bytes. */ + &automatic, /* Parameter passed as input of the task */ + 3, /* Priority of the task. */ + NULL); /* Task handle. */ +} diff --git a/src/valve.h b/src/valve.h new file mode 100644 index 0000000..5017d35 --- /dev/null +++ b/src/valve.h @@ -0,0 +1 @@ +void toggleValve(bool automatic); From 903e1e101adb3dd0b9650f2c24d5399ea200e098 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Wed, 22 Jul 2020 23:28:13 +0200 Subject: [PATCH 21/23] added comments to light classes --- src/lightChecker.cpp | 13 ++++++++++--- src/lightSensor.cpp | 3 +++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 5ecf944..dea1c80 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -1,8 +1,10 @@ #include +// Bool to check if light is already active bool lightActive = false; // Colors in Array: purple, blue, green, yellow, orange, red, white int colorValueArray[][3] = {{125,0,125}, {0,0,255}, {0,255,0}, {255,255,0}, {255,140,0}, {255,0,0}, {255,255,255}}; +// Pointer for color array int colorCounter = 6; // Setting PWM properties @@ -12,6 +14,7 @@ const int ledChannelGreen = 1; const int ledChannelBlue= 2; const int resolution = 8; +// Setup method for PWM configurations void setupPWM() { // Set pins as output pinMode(LIGHT_LED_PIN_R, OUTPUT); @@ -29,10 +32,12 @@ void setupPWM() { ledcAttachPin(LIGHT_LED_PIN_B, ledChannelBlue); } +// Takes a int value representing nanometers and sets color array pointer to appropriate color void setValueNM(int NM) { getColorBasedOnValueNM(NM); } +// Logic to set color array pointer void getColorBasedOnValueNM(int valueNM) { if (valueNM <= 420) { //Purple colorCounter = 0; @@ -56,16 +61,15 @@ void getColorBasedOnValueNM(int valueNM) { Serial.print(valueNM); } +// Shuts down the light bool shutdownLight() { - //digitalWrite(LIGHT_LED_PIN_R, LOW); - //digitalWrite(LIGHT_LED_PIN_G, LOW); - //digitalWrite(LIGHT_LED_PIN_B, LOW); ledcWrite(ledChannelRed, 0); ledcWrite(ledChannelGreen, 0); ledcWrite(ledChannelBlue, 0); return false; } +// Activates the light based on colorValueArray bool activateLight() { ledcWrite(ledChannelRed, colorValueArray[colorCounter][0]); ledcWrite(ledChannelGreen, colorValueArray[colorCounter][1]); @@ -73,11 +77,13 @@ bool activateLight() { return true; } +// Activate light for given amount of time if not already activated void lightTask(void *parameter) { takeSemaphore(); unsigned long lightTimeoutTimer = millis(); if (lightActive == false) { lightActive = activateLight(); + // If current time is below or equal to light timeout do nothing while (millis() - lightTimeoutTimer <= MAX_LIGHT_TIMEOUT) { } lightActive = shutdownLight(); @@ -86,6 +92,7 @@ void lightTask(void *parameter) { vTaskDelete(NULL); } +// Trigger for lightTask void triggerLight() { xTaskCreate( lightTask, /* Task function. */ diff --git a/src/lightSensor.cpp b/src/lightSensor.cpp index 78cb5ac..8ed3779 100644 --- a/src/lightSensor.cpp +++ b/src/lightSensor.cpp @@ -1,13 +1,16 @@ #include +// New BH1750 class BH1750 lightMeter; +// Setup for reading light sensor (prepares i2c communication) void setupLightSensor() { Wire.begin(); lightMeter.begin(); Serial.println("Sensor started..."); } +// Method to read and return the light value measured by BH1750 sensor float readLightSensorValue() { int intensity = lightMeter.readLightLevel(); return intensity; From 68d45f636351011427ecaabb22555381faf27521 Mon Sep 17 00:00:00 2001 From: Sebastian Date: Thu, 23 Jul 2020 12:30:44 +0200 Subject: [PATCH 22/23] Added some comments --- src/lightChecker.cpp | 12 ++++++------ src/main.cpp | 4 ++-- src/store.cpp | 18 +++++++++++------- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index 1152c90..a191c11 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -39,22 +39,22 @@ void setValueNM(int NM) { // Logic to set color array pointer void getColorBasedOnValueNM(int valueNM) { - if (valueNM <= 420) { //Purple + if (valueNM <= 420) { // Purple colorCounter = 0; } - else if (valueNM <= 490) { //Blue + else if (valueNM <= 490) { // Blue colorCounter = 1; } - else if (valueNM <= 575) { //Green + else if (valueNM <= 575) { // Green colorCounter = 2; } - else if (valueNM <= 585) { //Yellow + else if (valueNM <= 585) { // Yellow colorCounter = 3; } - else if (valueNM <= 650) { //Orange + else if (valueNM <= 650) { // Orange colorCounter = 4; } - else if (valueNM > 650) { // 650 to 750 is red + else if (valueNM > 650) { // 650 to 750 is Red colorCounter = 5; } Serial.println("New color set based on: "); diff --git a/src/main.cpp b/src/main.cpp index c6196c5..f12a32d 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -32,12 +32,12 @@ void setup() { Serial.println("Setup complete..."); Serial.println(); Serial.println(); - // first read without delay + // First read without delay readSensors(); } void loop() { - // main loop: read sensors + // Main loop: read sensors if (millis() - sensorReadTimer >= FREQUENCY) { readSensors(); sensorReadTimer = millis(); diff --git a/src/store.cpp b/src/store.cpp index 5aa7ac3..8a814aa 100644 --- a/src/store.cpp +++ b/src/store.cpp @@ -4,18 +4,18 @@ #include #include -// Feldkapazität des Bodens in Prozent: Standard ist Humus +// Fieldcapacity of the Ground in Percentage: Standard is Humus int fieldCapacity = 44; -// PWP des Bodens in Prozent: Standard ist Humus +// PWP of the Ground in Percentage: Standard is Humus int permanentWiltingPoint = 25; -// Boden vollständig gesättigt bei (Prozent): Standard ist Humus +// Ground completely saturated by (Percentage): Standard is Humus int soilSaturation = 69; -// Helligkeitswert der mindestens vorhanden sein muss +// Minimum light value before light turns on int minimumLightValueLX = 50; -// switches for automatic light and irrigation control +// Switches for automatic light and irrigation control bool automaticLight = true; bool automaticIrrigation = true; -// make sure device irrigates until fieldcapacity is reached +// Make sure device irrigates until fieldcapacity is reached bool irrigateUntilFC = false; void persistSoilProps(int FC, int PWP, int SAT) { @@ -75,6 +75,7 @@ void setSoilProperties(int FC, int PWP, int SAT) { Serial.println(soilSaturation); } +// Method to persist save the given lightning properties to NVS void persistLightProps(int NM, int minLX) { Serial.println("persistLightProps"); bool n = NVS.setInt("nanoMeter", NM); @@ -88,6 +89,7 @@ void persistLightProps(int NM, int minLX) { } } +// Method to restore light properties from Non-Volatile Storage (NVS) void restoreLightProps() { Serial.println("restoreLightProps"); int nm = NVS.getInt("nanoMeter"); @@ -101,6 +103,7 @@ void restoreLightProps() { Serial.println(minimumLightValueLX); } +// Method to set given light properties void setLightProperties(int NM, int minLX) { setValueNM(NM); minimumLightValueLX = minLX; @@ -111,7 +114,7 @@ void setLightProperties(int NM, int minLX) { void persistAutoProps(bool light, bool irrigation) { Serial.println("persistAutoProps"); - // saved in NVS as Integer: 1 = true, 2 = false, 0 = not persisted, use standard settings + // Saved in NVS as Integer: 1 = true, 2 = false, 0 = not persisted, use standard settings bool n = NVS.setInt("automaticLight", (light ? 1 : 2)); bool m = NVS.setInt("automaticIrrigation", (irrigation ? 1 : 2)); if (n && m) { @@ -158,6 +161,7 @@ void initDeviceID() { } } +// Returns the device ID String getDeviceID() { return DEVICE_ID; } From 28dfd4a9f4a3cbe22e40ab1713468bd41de6356e Mon Sep 17 00:00:00 2001 From: Sebastian Date: Thu, 23 Jul 2020 13:09:27 +0200 Subject: [PATCH 23/23] now publishes every 60 seconds --- src/common.h | 2 +- src/lightChecker.cpp | 1 + src/lightChecker.h | 3 ++- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/common.h b/src/common.h index 716844a..faaa43c 100644 --- a/src/common.h +++ b/src/common.h @@ -1,7 +1,7 @@ #include // PUBLISH FREQUENCY (MS) -#define FREQUENCY 20000 +#define FREQUENCY 60000 // fix for core panic during wifi initialization // #define configMINIMAL_STACK_SIZE 4096 diff --git a/src/lightChecker.cpp b/src/lightChecker.cpp index a191c11..90b5600 100644 --- a/src/lightChecker.cpp +++ b/src/lightChecker.cpp @@ -1,4 +1,5 @@ #include +#include // Bool to check if light is already active bool lightActive = false; diff --git a/src/lightChecker.h b/src/lightChecker.h index 2057252..df385d4 100644 --- a/src/lightChecker.h +++ b/src/lightChecker.h @@ -1,3 +1,4 @@ void setupPWM(); void setValueNM(int NM); -void triggerLight(); \ No newline at end of file +void triggerLight(); +void getColorBasedOnValueNM(int valueNM); \ No newline at end of file