From cbf51999db1358ad444bae8d3cafe79e625b6e03 Mon Sep 17 00:00:00 2001 From: Timo Volkmann Date: Mon, 6 Jul 2020 21:44:53 +0200 Subject: [PATCH] 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() {