From ab59073274873e22ccf8a12cd15c748047be48f3 Mon Sep 17 00:00:00 2001
From: Zoe Pfister <zoe.pfister@uibk.ac.at>
Date: Thu, 23 Mar 2023 13:55:26 +0100
Subject: [PATCH] update dr26 library, early exit if sensor not connected,
 minimize rs485 delay, minor SentecSensorsRS485 refactor, logging changes in
 host

---
 .../libs/SentecSensors/SentecSensorsRS485.cpp | 32 +++++++++++--------
 .../libs/SentecSensors/SentecSensorsRS485.h   |  1 +
 client/libs/dr26_analogue/dr26.cpp            | 32 ++++++++-----------
 client/libs/dr26_analogue/dr26.hpp            |  2 +-
 client/libs/rs485/rs485.cpp                   |  2 +-
 .../lib/Utilities/SDCardLogger.cpp            |  8 +++--
 6 files changed, 40 insertions(+), 37 deletions(-)

diff --git a/client/libs/SentecSensors/SentecSensorsRS485.cpp b/client/libs/SentecSensors/SentecSensorsRS485.cpp
index d483631..a3a0903 100644
--- a/client/libs/SentecSensors/SentecSensorsRS485.cpp
+++ b/client/libs/SentecSensors/SentecSensorsRS485.cpp
@@ -130,18 +130,8 @@ ErrorType SentecSensorRS485::getResponse() {
 
         ESP_LOGD(TAG, "Response: 0x%s", formatBytes(answerFrame, responseLength).c_str());
 
-        // TODO: Not optimal, has precedence
-        auto connectionEndedPrematurelyReturnCode = checkConnectionEndedPrematurely(idx, responseLength);
-        auto sensorConnectedReturnCode = checkSensorConnected();
-        auto crcReturnCode = checkCRC(responseLength);
-
-        if (sensorConnectedReturnCode != ErrorType::DATA_OK) {
-            returnCode = sensorConnectedReturnCode;
-        } else if (connectionEndedPrematurelyReturnCode != ErrorType::DATA_OK) {
-            returnCode = connectionEndedPrematurelyReturnCode;
-        } else if (crcReturnCode != ErrorType::DATA_OK) {
-            returnCode = crcReturnCode;
-        }
+        // TODO: Test this @future_zoe
+        returnCode = checkForErrors(idx, responseLength);
 
         // breaking after first successfull try
         if (returnCode == ErrorType::DATA_OK) {
@@ -149,9 +139,25 @@ ErrorType SentecSensorRS485::getResponse() {
         }
     }
 
-    // ESP_LOGE(TAG, "Returncode: %d", returnCode);
     return returnCode;
 }
+
+ErrorType SentecSensorRS485::checkForErrors(int idx, int responseLength) {
+    // TODO: Not optimal, has precedence
+    auto connectionEndedPrematurelyReturnCode = checkConnectionEndedPrematurely(idx, responseLength);
+    auto sensorConnectedReturnCode = checkSensorConnected();
+    auto crcReturnCode = checkCRC(responseLength);
+
+    if (sensorConnectedReturnCode != ErrorType::DATA_OK) {
+        return sensorConnectedReturnCode;
+    } else if (connectionEndedPrematurelyReturnCode != ErrorType::DATA_OK) {
+        return connectionEndedPrematurelyReturnCode;
+    } else if (crcReturnCode != ErrorType::DATA_OK) {
+        return crcReturnCode;
+    }
+    return ErrorType::DATA_OK;
+}
+
 ErrorType SentecSensorRS485::checkCRC(int responseLength) {
     word crc_received = word(answerFrame[responseLength - 2], answerFrame[responseLength - 1]);
     word crc = calculateCRC(answerFrame, responseLength - 2);
diff --git a/client/libs/SentecSensors/SentecSensorsRS485.h b/client/libs/SentecSensors/SentecSensorsRS485.h
index af867df..cab2500 100644
--- a/client/libs/SentecSensors/SentecSensorsRS485.h
+++ b/client/libs/SentecSensors/SentecSensorsRS485.h
@@ -80,6 +80,7 @@ class SentecSensorRS485 {
     ErrorType checkSensorConnected() const;
     ErrorType checkConnectionEndedPrematurely(int idx, int responseLength) const;
     ErrorType checkCRC(int responseLength);
+    ErrorType checkForErrors(int idx, int responseLength);
 };
 
 #endif
diff --git a/client/libs/dr26_analogue/dr26.cpp b/client/libs/dr26_analogue/dr26.cpp
index c0e7d0e..ea7f1fb 100644
--- a/client/libs/dr26_analogue/dr26.cpp
+++ b/client/libs/dr26_analogue/dr26.cpp
@@ -3,8 +3,11 @@
 static const char *TAG = "DR26";
 
 void ForteDR26::setup() {
+    if (sensorConnected) {
+        ESP_LOGD(TAG, "ADS already initialized");
+        return;
+    }
     Wire.begin();
-
     ads.setGain(GAIN_ONE);
     ads.setDataRate(RATE_ADS1115_8SPS);
     if (ads.begin()) {
@@ -14,8 +17,6 @@ void ForteDR26::setup() {
         ESP_LOGE(TAG, "failed to initialize ADS");
         sensorConnected = false;
     }
-
-    delay(100);
     channel = 0;
 }
 
@@ -23,25 +24,22 @@ Measurement ForteDR26::readData() {
     float volts = 0;
     int16_t adc = 0;
 
+    if (!sensorConnected) {
+        return {ERROR_VALUE, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT,
+                ErrorType::SENSOR_INIT_FAILED};
+    }
+
     try {
         // TODO: This function might never return if conversionComplete is never true. Check if this is the case
         // FIXME: How to notice from the dr if a value is incorrect?
         adc = ads.readADC_SingleEnded(channel);
         volts = ads.computeVolts(adc);
-    }
-    catch (NoDataAvailableException &e) {
+    } catch (NoDataAvailableException &e) {
         // FIXME: This catch block will never be called since we aint throwing any exceptions
-        return {ERROR_VALUE, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT,
-                ErrorType::NO_DATA};
-    }
-
-    if (!sensorConnected) {
-        return {ERROR_VALUE, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT,
-                ErrorType::SENSOR_INIT_FAILED};
+        return {ERROR_VALUE, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT, ErrorType::NO_DATA};
     }
 
-    return {volts, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT,
-            ErrorType::DATA_OK};
+    return {volts, channel, NO_I2C_ADDRESS, MeasurementType::CIRCUMFERENCE_INCREMENT, ErrorType::DATA_OK};
 }
 
 // The following functions change the ADC input range: be careful
@@ -70,9 +68,7 @@ void ForteDR26::setChannel(int c) {
 std::list<Message> ForteDR26::buildMessages() {
     std::list<Message> messages;
     auto data = readData();
-    messages.emplace_back(data,
-                          sensorInformation,
-                          Time::getInstance().getEpochSeconds());
+    messages.emplace_back(data, sensorInformation, Time::getInstance().getEpochSeconds());
     return messages;
 }
 
@@ -80,7 +76,5 @@ SensorInformation ForteDR26::getSensorInformation() const {
     return sensorInformation;
 }
 
-
 // TODO: What is this?
 Adafruit_ADS1115 ForteDR26::ads = ads;
-
diff --git a/client/libs/dr26_analogue/dr26.hpp b/client/libs/dr26_analogue/dr26.hpp
index ea209f5..b84b612 100644
--- a/client/libs/dr26_analogue/dr26.hpp
+++ b/client/libs/dr26_analogue/dr26.hpp
@@ -23,7 +23,7 @@ class ForteDR26: public ForteSensor<Measurement> {
   const SensorInformation
       sensorInformation{HardwareName::DRS26, SensorProtocol::Analog};
   int channel;
-  bool sensorConnected = true;
+  bool sensorConnected = false;
 };
 
 #endif
\ No newline at end of file
diff --git a/client/libs/rs485/rs485.cpp b/client/libs/rs485/rs485.cpp
index 58c8c8b..62b749d 100644
--- a/client/libs/rs485/rs485.cpp
+++ b/client/libs/rs485/rs485.cpp
@@ -52,7 +52,7 @@ void ForteRS485::powerOnRS485Sensors() { // Power on sensor
     digitalWrite(POWER_SWITCH_PIN_12V, HIGH);
     digitalWrite(POWER_SWITCH_PIN_5V, HIGH); // Wait for sensors to power up
     // TODO minimize delay
-    delay(1000);
+    delay(100);
 }
 
 std::list<Message> ForteRS485::buildMessages() {
diff --git a/host/host_central_mast/lib/Utilities/SDCardLogger.cpp b/host/host_central_mast/lib/Utilities/SDCardLogger.cpp
index e351965..86735a0 100644
--- a/host/host_central_mast/lib/Utilities/SDCardLogger.cpp
+++ b/host/host_central_mast/lib/Utilities/SDCardLogger.cpp
@@ -13,12 +13,14 @@ namespace SDCardLogger {
         printToSerial = printToSerialAsWell;
     }
     int vprintf_into_sd(const char *szFormat, va_list args) {
-        String logstring = "[" + rtc.getDateTime() + "] ";
-        logstring += szFormat;
+        auto timeSinceBootMs = esp_timer_get_time() / 1000;
+        String logstring = String(timeSinceBootMs) + ", ";
         // print current core
         logstring += "Core: ";
         logstring += xPortGetCoreID();
-        logstring += ". ";
+        logstring += ", ";
+        logstring += "[" + rtc.getDateTime() + "] ";
+        logstring += szFormat;
         if (!SDUtilities::isSDAvailable()) {
             if (printToSerial) {
                 logstring += " (SD card not available)\n";
-- 
GitLab