diff --git a/esp32/src/main.cpp b/esp32/src/main.cpp index 78ed413..5dfc947 100644 --- a/esp32/src/main.cpp +++ b/esp32/src/main.cpp @@ -1,18 +1,18 @@ /** \addtogroup Controller * @{ - * + * * @file main.cpp * @author Ollo * @brief PlantControl * @version 0.1 * @date 2020-05-01 - * + * * @copyright Copyright (c) 2020 */ /****************************************************************************** * INCLUDES -******************************************************************************/ + ******************************************************************************/ #include "LogDefines.h" #include "FileUtils.h" #include "TimeUtils.h" @@ -37,20 +37,19 @@ #include "MQTTUtils.h" #include "esp_ota_ops.h" #if defined(TIMED_LIGHT_PIN) - #include "ulp-pwm.h" +#include "ulp-pwm.h" #endif - /****************************************************************************** * DEFINES -******************************************************************************/ + ******************************************************************************/ #define AMOUNT_SENOR_QUERYS 8 #define MAX_TANK_DEPTH 2000 #define REBOOT_LOOP_DETECTION_ERROR 5 /****************************************************************************** * FUNCTION PROTOTYPES -******************************************************************************/ + ******************************************************************************/ int determineNextPump(bool lowLight); void plantcontrol(); @@ -60,7 +59,7 @@ bool otaRunning = false; /****************************************************************************** * NON VOLATILE VARIABLES in DEEP SLEEP -******************************************************************************/ + ******************************************************************************/ #if defined(TIMED_LIGHT_PIN) RTC_DATA_ATTR bool timedLightLowVoltageTriggered = false; /**remember if it was shut down due to voltage level */ #endif // TIMED_LIGHT_PIN @@ -70,7 +69,7 @@ RTC_DATA_ATTR long consecutiveWateringPlant[MAX_PLANTS] = {0}; /****************************************************************************** * LOCAL VARIABLES -******************************************************************************/ + ******************************************************************************/ bool volatile mDownloadMode = false; /**< Controller must not sleep */ bool volatile mSensorsRead = false; /**< Sensors are read without Wifi or MQTT */ int volatile pumpToRun = -1; /** pump to run at the end of the cycle */ @@ -131,7 +130,7 @@ Plant mPlants[MAX_PLANTS] = { /****************************************************************************** * LOCAL FUNCTIONS -******************************************************************************/ + ******************************************************************************/ void finsihedCycleSucessfully() { @@ -153,7 +152,7 @@ void espDeepSleep(bool afterPump = false) if (mDownloadMode) { log(LOG_LEVEL_DEBUG, "abort deepsleep, DownloadMode active", LOG_DEBUG_CODE); - //if we manage to get to the download mode, the device can be restored + // if we manage to get to the download mode, the device can be restored finsihedCycleSucessfully(); return; } @@ -213,7 +212,7 @@ void espDeepSleep(bool afterPump = false) } } -//requires homie being started +// requires homie being started void readOneWireSensors() { for (uint8_t i = 0; i < sensors.getDeviceCount(); i++) @@ -241,7 +240,7 @@ void readOneWireSensors() if (!valid) { - //wrong family or crc errors on each retry + // wrong family or crc errors on each retry continue; } @@ -316,17 +315,19 @@ void readPowerSwitchedSensors() Plant plant = mPlants[i]; switch (plant.getSensorMode()) { - case CAPACITIVE_FREQUENCY: { - Serial << "Plant " << i << " measurement: " << mPlants[i].getCurrentMoistureRaw() << " hz " << mPlants[i].getCurrentMoisturePCT() << "%" << endl; - break; - } - case ANALOG_RESISTANCE_PROBE : { - Serial << "Plant " << i << " measurement: " << mPlants[i].getCurrentMoistureRaw() << " mV " << mPlants[i].getCurrentMoisturePCT() << "%" << endl; - break; - } - case NONE : { - - } + case CAPACITIVE_FREQUENCY: + { + Serial << "Plant " << i << " measurement: " << mPlants[i].getCurrentMoistureRaw() << " hz " << mPlants[i].getCurrentMoisturePCT() << "%" << endl; + break; + } + case ANALOG_RESISTANCE_PROBE: + { + Serial << "Plant " << i << " measurement: " << mPlants[i].getCurrentMoistureRaw() << " mV " << mPlants[i].getCurrentMoisturePCT() << "%" << endl; + break; + } + case NONE: + { + } } } @@ -486,12 +487,14 @@ int determineNextPump(bool isLowLight) } else { - if(mDownloadMode){ + if (mDownloadMode) + { plant.publishState("active+supressed"); - }else { + } + else + { plant.publishState("active"); } - } if (!plant.isHydroponic()) @@ -520,7 +523,7 @@ int determineNextPump(bool isLowLight) else { plant.publishState("wet"); - //plant was detected as wet, remove consecutive count + // plant was detected as wet, remove consecutive count consecutiveWateringPlant[i] = 0; } } @@ -529,7 +532,7 @@ int determineNextPump(bool isLowLight) /** * @brief Handle Mqtt commands to keep controller alive - * + * * @param range multiple transmitted values (not used for this function) * @param value single value * @return true when the command was parsed and executed succuessfully @@ -606,12 +609,12 @@ bool switch7(const HomieRange &range, const String &value) void initPumpLogic() { - //set targets + // set targets #ifdef FLOWMETER_PIN pumpTargetMl = mPlants[pumpToRun].getPumpMl(); - //0-6 are used for moisture measurment + // 0-6 are used for moisture measurment pcnt_unit_t unit = (pcnt_unit_t)(PCNT_UNIT_7); pcnt_config_t pcnt_config = {}; // Instancia PCNT config pcnt_config.pulse_gpio_num = FLOWMETER_PIN; // Configura GPIO para entrada dos pulsos @@ -630,14 +633,13 @@ void initPumpLogic() #endif pumpStartTime = millis(); pumpTarget = millis() + (mPlants[pumpToRun].getPumpDuration() * 1000); - #ifdef FLOWMETER_PIN - log(LOG_LEVEL_INFO, "Starting pump " + String(pumpToRun) + " for " + String(mPlants[pumpToRun].getPumpDuration()) + "s or " + String(pumpTargetMl) + "ml", LOG_PUMP_STARTED_CODE); - #else - log(LOG_LEVEL_INFO, "Starting pump " + String(pumpToRun) + " for " + String(mPlants[pumpToRun].getPumpDuration()) + "s", LOG_PUMP_STARTED_CODE); - #endif - +#ifdef FLOWMETER_PIN + log(LOG_LEVEL_INFO, "Starting pump " + String(pumpToRun) + " for " + String(mPlants[pumpToRun].getPumpDuration()) + "s or " + String(pumpTargetMl) + "ml", LOG_PUMP_STARTED_CODE); +#else + log(LOG_LEVEL_INFO, "Starting pump " + String(pumpToRun) + " for " + String(mPlants[pumpToRun].getPumpDuration()) + "s", LOG_PUMP_STARTED_CODE); +#endif - //enable power + // enable power WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); digitalWrite(OUTPUT_ENABLE_PUMP, HIGH); delay(100); @@ -664,7 +666,7 @@ void pumpActiveLoop() mqttUpdateTick = true; } -long duration = millis() - pumpStartTime; + long duration = millis() - pumpStartTime; #ifdef FLOWMETER_PIN int16_t pulses; pcnt_unit_t unit = (pcnt_unit_t)(PCNT_UNIT_7); @@ -674,11 +676,10 @@ long duration = millis() - pumpStartTime; log(LOG_LEVEL_ERROR, LOG_HARDWARECOUNTER_ERROR_MESSAGE, LOG_HARDWARECOUNTER_ERROR_CODE); targetReached = true; log(LOG_LEVEL_INFO, "Reached pump target ml " + String(pumpToRun), LOG_PUMP_STARTED_CODE); - } else { - float mLPumped = pulses/FLOWMETER_PULSES_PER_ML; //mLperMs*duration; + float mLPumped = pulses / FLOWMETER_PULSES_PER_ML; // mLperMs*duration; if (mLPumped >= pumpTargetMl) { targetReached = true; @@ -686,7 +687,7 @@ long duration = millis() - pumpStartTime; mPlants[pumpToRun].setProperty("pulses").send(String(pulses)); mPlants[pumpToRun].setProperty("waterusage").send(String(mLPumped)); } - + else if (mqttUpdateTick) { mPlants[pumpToRun].setProperty("pulses").send(String(pulses)); @@ -695,7 +696,6 @@ long duration = millis() - pumpStartTime; } #endif - if (millis() > pumpTarget) { mPlants[pumpToRun].setProperty("watertime").send(String(duration)); @@ -709,12 +709,12 @@ long duration = millis() - pumpStartTime; if (targetReached) { - //disable all + // disable all digitalWrite(OUTPUT_ENABLE_PUMP, LOW); mPlants[pumpToRun].deactivatePump(); - //disable loop, to prevent multi processing + // disable loop, to prevent multi processing pumpStarted = false; - //if runtime is larger than cooldown, else it would run continously + // if runtime is larger than cooldown, else it would run continously rtcLastWateringPlant[pumpToRun] = getCurrentTime(); espDeepSleep(true); } @@ -731,7 +731,7 @@ void safeSetup() WiFi.mode(WIFI_OFF); Serial.flush(); -//restore state before releasing pin, to prevent flickering +// restore state before releasing pin, to prevent flickering #if defined(TIMED_LIGHT_PIN) ulp_pwm_init(); #endif // TIMED_LIGHT_PIN @@ -754,25 +754,25 @@ void safeSetup() static_assert(HomieInternals::MAX_CONFIG_SETTING_SIZE >= MAX_CONFIG_SETTING_ITEMS, "Limits.hpp not adjusted MAX_CONFIG_SETTING_ITEMS"); if (HomieInternals::MAX_CONFIG_SETTING_SIZE < MAX_CONFIG_SETTING_ITEMS) { - //increase the config settings + // increase the config settings Serial << "Limits.hpp is not adjusted, please search for this string and increase" << endl; return; } static_assert(HomieInternals::MAX_JSON_CONFIG_FILE_SIZE >= MAX_JSON_CONFIG_FILE_SIZE_CUSTOM, "Limits.hpp not adjusted MAX_JSON_CONFIG_FILE_SIZE"); if (HomieInternals::MAX_JSON_CONFIG_FILE_SIZE < MAX_JSON_CONFIG_FILE_SIZE_CUSTOM) { - //increase the config settings + // increase the config settings Serial << "Limits.hpp is not adjusted, please search for this string and increase" << endl; return; } - /************************* Start Homie Framework ***************/ + /************************* Start Homie Framework ***************/ Homie_setFirmware("PlantControl", FIRMWARE_VERSION); Homie.disableLedFeedback(); Homie_setBrand("PlantControl"); // Set default values - //in seconds + // in seconds deepSleepTime.setDefaultValue(600).setValidator([](long candidate) { return (candidate > 0) && (candidate < (60 * 60 * 2) /** 2h max sleep */); }); deepSleepNightTime.setDefaultValue(600); @@ -789,7 +789,7 @@ void safeSetup() #if defined(TIMED_LIGHT_PIN) timedLightPowerLevel.setDefaultValue(25).setValidator([](long candidate) - { return (candidate > 0) && (candidate <= (255)); }); + { return (candidate > 0) && (candidate <= (255)); }); timedLightStart.setDefaultValue(18).setValidator([](long candidate) { return (candidate > 0) && (candidate < (25)); }); timedLightEnd.setDefaultValue(23).setValidator([](long candidate) @@ -809,15 +809,13 @@ void safeSetup() } readPowerSwitchedSensors(); - Homie.setup(); Wire = TwoWire(0); Wire.setPins(SENSOR_TANK_SDA, SENSOR_TANK_SCL); Wire.begin(); - - /************************* Start One-Wire bus ***************/ + /************************* Start One-Wire bus ***************/ int tempInitStartTime = millis(); uint8_t sensorCount = 0U; @@ -835,7 +833,7 @@ void safeSetup() /* Measure temperature TODO idea: move this into setup */ if (sensorCount > 0) { - //sensors.setResolution(DS18B20_RESOLUTION); + // sensors.setResolution(DS18B20_RESOLUTION); sensors.requestTemperatures(); } @@ -905,7 +903,7 @@ void safeSetup() } readOneWireSensors(); - //prevent BOD to be paranoid + // prevent BOD to be paranoid WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); digitalWrite(OUTPUT_ENABLE_PUMP, HIGH); delay(100); @@ -1077,18 +1075,21 @@ void plantcontrol() #if defined(TIMED_LIGHT_PIN) bool isLowLight = mSolarVoltage <= 9; bool shouldLight = determineTimedLightState(isLowLight); - if(shouldLight){ + if (shouldLight) + { ulp_pwm_set_level(timedLightPowerLevel.get()); - }else { + } + else + { ulp_pwm_set_level(0); } - + #endif // TIMED_LIGHT_PIN - bool hasWater = true; //FIXME remaining > waterLevelMin.get(); - //FIXME no water warning message + bool hasWater = true; // FIXME remaining > waterLevelMin.get(); + // FIXME no water warning message pumpToRun = determineNextPump(isLowLight); - //early aborts + // early aborts if (pumpToRun != -1) { if (hasWater) @@ -1122,7 +1123,7 @@ bool determineTimedLightState(bool lowLight) long hoursStart = timedLightStart.get(); long hoursEnd = timedLightEnd.get(); - //ntp missing + // ntp missing if (getCurrentTime() < 10000) { timedLightNode.setProperty("state").send(String("Off, missing ntp"));