From dffd0ea817901de7912d1de53e3c9961bc13c33c Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Fri, 18 May 2018 16:10:22 -0400 Subject: [PATCH 01/54] Fixed missed end() in sdi-12, updated maxbotix solo example --- examples/single_sensor/single_sensor.ino | 27 +++++++++++++++++++----- src/SDI12Sensors.cpp | 9 +++++++- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/examples/single_sensor/single_sensor.ino b/examples/single_sensor/single_sensor.ino index e766aeb78..6f2ef739d 100644 --- a/examples/single_sensor/single_sensor.ino +++ b/examples/single_sensor/single_sensor.ino @@ -45,10 +45,24 @@ const int SonarData = 11; // data pin const int SonarTrigger = -1; // Trigger pin const int8_t SonarPower = 22; // excite (power) pin + #if defined __AVR__ -#include // for the stream communication -SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx -#elif defined __SAMD21G18A__ + +// #include // for the stream communication +// SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx + +#include // for the stream communication +NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +void NeoSWSISR() +{ + NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +} + +#endif + + + +#if defined __SAMD21G18A__ #include "wiring_private.h" // pinPeripheral() function Uart Serial3(&sercom2, 5, 2, SERCOM_RX_PAD_3, UART_TX_PAD_2); void SERCOM2_Handler() @@ -56,8 +70,6 @@ void SERCOM2_Handler() Serial3.IrqHandler(); } HardwareSerial &sonarSerial = Serial3; -#else -HardwareSerial &sonarSerial = Serial1; #endif // Create a new instance of the sonar sensor; @@ -96,10 +108,15 @@ void setup() Serial.begin(serialBaud); // Start the stream for the sonar sonarSerial.begin(9600); + // Allow interrupts for software serial #if defined SoftwareSerial_ExtInts_h enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); #endif + #if defined NeoSWSerial_h + enableInterrupt(SonarData, NeoSWSISR, CHANGE); + #endif + #if defined __SAMD21G18A__ // Assign pins to SERCOM functionality pinPeripheral(2, PIO_SERCOM); diff --git a/src/SDI12Sensors.cpp b/src/SDI12Sensors.cpp index 9e183304a..e1dcc5c5d 100644 --- a/src/SDI12Sensors.cpp +++ b/src/SDI12Sensors.cpp @@ -67,6 +67,13 @@ bool SDI12Sensors::setup(void) retVal &= getSensorInfo(); + // Empty the SDI-12 buffer + _SDI12Internal.clearBuffer(); + + // De-activate the SDI-12 Object + // Use end() instead of just forceHold to un-set the timers + _SDI12Internal.end(); + return retVal; } @@ -347,7 +354,7 @@ bool SDI12Sensors::addSingleMeasurementResult(void) // De-activate the SDI-12 Object // Use end() instead of just forceHold to un-set the timers - _SDI12Internal.forceHold(); + _SDI12Internal.end(); // Unset the time stamp for the beginning of this measurement _millisMeasurementRequested = 0; From 51332bf0029cfc05fd11c7b6612c2a9a740fd6e2 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Fri, 18 May 2018 16:43:51 -0400 Subject: [PATCH 02/54] Moved system sleep out of begin And into the end of the setup of all examples The system was going to sleep before setting up the test button. --- examples/DRWI_CitSci/DRWI_CitSci.ino | 3 +++ examples/DRWI_NoCellular/DRWI_NoCellular.ino | 3 +++ examples/baro_rho_correction/baro_rho_correction.ino | 3 +++ examples/data_saving/data_saving.ino | 6 +++++- examples/double_logger/double_logger.ino | 4 ++++ examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino | 3 +++ .../logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino | 4 ++++ examples/simple_logging/simple_logging.ino | 3 +++ library.json | 2 +- src/LoggerBase.cpp | 3 --- src/LoggerEnviroDIY.cpp | 3 --- 11 files changed, 29 insertions(+), 8 deletions(-) diff --git a/examples/DRWI_CitSci/DRWI_CitSci.ino b/examples/DRWI_CitSci/DRWI_CitSci.ino index 5e82bb3eb..d9f3fffd2 100644 --- a/examples/DRWI_CitSci/DRWI_CitSci.ino +++ b/examples/DRWI_CitSci/DRWI_CitSci.ino @@ -228,6 +228,9 @@ void setup() // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); + + // Sleep + EnviroDIYLogger.systemSleep(); } diff --git a/examples/DRWI_NoCellular/DRWI_NoCellular.ino b/examples/DRWI_NoCellular/DRWI_NoCellular.ino index e6e33a0ac..f3f5eb77b 100644 --- a/examples/DRWI_NoCellular/DRWI_NoCellular.ino +++ b/examples/DRWI_NoCellular/DRWI_NoCellular.ino @@ -179,6 +179,9 @@ void setup() // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); + + // Sleep + EnviroDIYLogger.systemSleep(); } diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index 97f9b4a49..e3fe88dcd 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -388,6 +388,9 @@ void setup() // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); + + // Sleep + EnviroDIYLogger.systemSleep(); } diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index 186f6c7f8..fbee6c18d 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -344,6 +344,10 @@ void setup() // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); + + // Call the processor sleep + // Only need to do this for one of the loggers + loggerComplete.systemSleep(); } @@ -390,7 +394,7 @@ void loop() // End the stream for the modbus sensors // Because RS485 adapters tend to "steal" current from the data pins - // we will explicitly start and end the serial connection in the loop. + // we will explicitly start and end the serial connection in the loop. modbusSerial.end(); // Create a csv data record and save it to the log file diff --git a/examples/double_logger/double_logger.ino b/examples/double_logger/double_logger.ino index 7ce048dc0..80ce3efb2 100644 --- a/examples/double_logger/double_logger.ino +++ b/examples/double_logger/double_logger.ino @@ -251,6 +251,10 @@ void setup() Serial.println(F("Logger setup finished!\n")); Serial.println(F("------------------------------------------")); Serial.println(); + + // Call the processor sleep + // Only need to do this for one of the loggers + logger1min.systemSleep(); } diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index deda5628f..6f50866c5 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -610,6 +610,9 @@ void setup() // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); + + // Sleep + EnviroDIYLogger.systemSleep(); } diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index c5abfedcc..eefd5964c 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -437,6 +437,7 @@ const char *DOptoDI12address = "5"; // The SDI-12 Address of the Zebra Tech D-O // Create and return the Zebra Tech DOpto dissolved oxygen sensor object ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); + // ========================================================================== // The array that contains all variables to be logged // ========================================================================== @@ -610,6 +611,9 @@ void setup() // Begin the logger EnviroDIYLogger.begin(); + + // Sleep + EnviroDIYLogger.systemSleep(); } diff --git a/examples/simple_logging/simple_logging.ino b/examples/simple_logging/simple_logging.ino index 5941b7ba4..720fd6c45 100644 --- a/examples/simple_logging/simple_logging.ino +++ b/examples/simple_logging/simple_logging.ino @@ -517,6 +517,9 @@ void setup() Serial.print(buttonPin); Serial.println(F(" at any time to enter sensor testing mode.")); + // Sleep + logger.systemSleep(); + } diff --git a/library.json b/library.json index 9ac12538b..a03573ea2 100644 --- a/library.json +++ b/library.json @@ -195,7 +195,7 @@ { "name": "Arduino-SDI-12_ExtInts", "version": "https://github.com/EnviroDIY/Arduino-SDI-12.git#ExtInts", - "version_note": ">=1.3.1", + "version_note": ">=1.3.2", "note": "EnviroDIY SDI-12 Library, dependent on external library for interrupts", "authors": [ "Kevin M. Smith", diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index aff9dc58d..30090fe44 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -806,9 +806,6 @@ void Logger::testingMode() PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); - - // Sleep - if(_sleep){systemSleep();} } diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 6b137601a..ae7f701e2 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -369,9 +369,6 @@ void LoggerEnviroDIY::begin(void) PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); - - // Sleep - if(_sleep){systemSleep();} } From e1e3ecc927ac7b170992dcb59f1b4c8afdb2717c Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Fri, 18 May 2018 17:17:50 -0400 Subject: [PATCH 03/54] Checking if SDI12 object is active before re-beginning --- src/MaxBotixSonar.cpp | 9 +++++++++ src/SDI12Sensors.cpp | 24 +++++++++++++++--------- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/MaxBotixSonar.cpp b/src/MaxBotixSonar.cpp index 90ce110fa..33ae3c555 100644 --- a/src/MaxBotixSonar.cpp +++ b/src/MaxBotixSonar.cpp @@ -93,6 +93,15 @@ bool MaxBotixSonar::addSingleMeasurementResult(void) int rangeAttempts = 0; int result = -9999; + // Clear anything out of the stream buffer + int junkChars = _stream->available(); + if (junkChars) + { + MS_DBG(F("Dumping "), junkChars, " characters from MaxBotix stream buffer\n"); + for (uint8_t i = 0; i < junkChars; i++) + _stream->read(); + } + if (_millisMeasurementRequested > 0) { MS_DBG(F("Getting readings from MaxBotix on "), getSensorLocation(), '\n'); diff --git a/src/SDI12Sensors.cpp b/src/SDI12Sensors.cpp index e1dcc5c5d..64146cc52 100644 --- a/src/SDI12Sensors.cpp +++ b/src/SDI12Sensors.cpp @@ -137,9 +137,11 @@ bool SDI12Sensors::getSensorInfo(void) { MS_DBG(F(" Activating SDI-12 instance for "), getSensorName(), F(" at "), getSensorLocation(), '\n'); - // Make this the currently active SDI-12 Object + // Check if this the currently active SDI-12 Object + bool wasActive = _SDI12Internal.isActive(); + // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. - _SDI12Internal.begin();; + if (!wasActive) _SDI12Internal.begin(); // Empty the buffer _SDI12Internal.clearBuffer(); @@ -169,7 +171,7 @@ bool SDI12Sensors::getSensorInfo(void) // De-activate the SDI-12 Object // Use end() instead of just forceHold to un-set the timers - _SDI12Internal.end(); + if (!wasActive) _SDI12Internal.end(); if (sdiResponse.length() > 1) { @@ -232,9 +234,11 @@ bool SDI12Sensors::startSingleMeasurement(void) MS_DBG(F(" Activating SDI-12 instance for "), getSensorName(), F(" at "), getSensorLocation(), '\n'); - // Make this the currently active SDI-12 Object + // Check if this the currently active SDI-12 Object + bool wasActive = _SDI12Internal.isActive(); + // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. - _SDI12Internal.begin();; + if (!wasActive) _SDI12Internal.begin(); // Empty the buffer _SDI12Internal.clearBuffer(); @@ -267,7 +271,7 @@ bool SDI12Sensors::startSingleMeasurement(void) // De-activate the SDI-12 Object // Use end() instead of just forceHold to un-set the timers - _SDI12Internal.end(); + if (!wasActive) _SDI12Internal.end(); // Verify the number of results the sensor will send // int numVariables = sdiResponse.substring(4,5).toInt(); @@ -315,9 +319,11 @@ bool SDI12Sensors::addSingleMeasurementResult(void) { MS_DBG(F(" Activating SDI-12 instance for "), getSensorName(), F(" at "), getSensorLocation(), '\n'); - // Make this the currently active SDI-12 Object + // Check if this the currently active SDI-12 Object + bool wasActive = _SDI12Internal.isActive(); + // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. - _SDI12Internal.begin();; + if (!wasActive) _SDI12Internal.begin(); // Empty the buffer _SDI12Internal.clearBuffer(); @@ -354,7 +360,7 @@ bool SDI12Sensors::addSingleMeasurementResult(void) // De-activate the SDI-12 Object // Use end() instead of just forceHold to un-set the timers - _SDI12Internal.end(); + if (!wasActive) _SDI12Internal.end(); // Unset the time stamp for the beginning of this measurement _millisMeasurementRequested = 0; From 802632825de23d899e5d318822b47950527d8183 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 11:17:03 -0400 Subject: [PATCH 04/54] Added a bit of extra debugging --- src/MaxBotixSonar.cpp | 3 +++ src/SDI12Sensors.cpp | 6 ++++++ 2 files changed, 9 insertions(+) diff --git a/src/MaxBotixSonar.cpp b/src/MaxBotixSonar.cpp index 33ae3c555..1ddd92c7c 100644 --- a/src/MaxBotixSonar.cpp +++ b/src/MaxBotixSonar.cpp @@ -76,6 +76,9 @@ bool MaxBotixSonar::wake(void) // RoHS 1.8b090 0713 // TempI + // NOTE ALSO: Depending on what type of serial stream you are using, there + // may also be a bunch of junk in the buffer that this will clear out. + MS_DBG(F("Parsing Header Lines from MaxBotix on "), getSensorLocation(), '\n'); for(int i = 0; i < 6; i++) { diff --git a/src/SDI12Sensors.cpp b/src/SDI12Sensors.cpp index 64146cc52..6278204a3 100644 --- a/src/SDI12Sensors.cpp +++ b/src/SDI12Sensors.cpp @@ -141,6 +141,8 @@ bool SDI12Sensors::getSensorInfo(void) bool wasActive = _SDI12Internal.isActive(); // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. + if (wasActive) MS_DBG(F(" SDI-12 instance for "), getSensorName(), + F(" at "), getSensorLocation(), " was already active!\n"); if (!wasActive) _SDI12Internal.begin(); // Empty the buffer _SDI12Internal.clearBuffer(); @@ -236,6 +238,8 @@ bool SDI12Sensors::startSingleMeasurement(void) F(" at "), getSensorLocation(), '\n'); // Check if this the currently active SDI-12 Object bool wasActive = _SDI12Internal.isActive(); + if (wasActive) MS_DBG(F(" SDI-12 instance for "), getSensorName(), + F(" at "), getSensorLocation(), " was already active!\n"); // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. if (!wasActive) _SDI12Internal.begin(); @@ -321,6 +325,8 @@ bool SDI12Sensors::addSingleMeasurementResult(void) F(" at "), getSensorLocation(), '\n'); // Check if this the currently active SDI-12 Object bool wasActive = _SDI12Internal.isActive(); + if (wasActive) MS_DBG(F(" SDI-12 instance for "), getSensorName(), + F(" at "), getSensorLocation(), " was already active!\n"); // If it wasn't active, activate it now. // Use begin() instead of just setActive() to ensure timer is set correctly. if (!wasActive) _SDI12Internal.begin(); From 908a7d9084203c51d4bcb8e0ae5108ea22aad1da Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 12:09:18 -0400 Subject: [PATCH 05/54] Beginning stages of calculated vars Totally untested --- src/VariableBase.cpp | 84 ++++++++++++++++++++++++++++++++++++-------- src/VariableBase.h | 18 +++++++++- 2 files changed, 87 insertions(+), 15 deletions(-) diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 9eea1a21f..536b067d0 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -14,13 +14,16 @@ // The class and functions for interfacing with a specific variable. // ============================================================================ -// The constructor +// The constructor for a measured variable - that is, one whos values are +// updated by a sensor. Variable::Variable(Sensor *parentSense, int varNum, String varName, String varUnit, unsigned int decimalResolution, String defaultVarCode, String UUID, String customVarCode) { + _isCalculated = false; + _calcFxn = NULL; parentSensor = parentSense; _varNum = varNum; _varName = varName; @@ -35,26 +38,63 @@ Variable::Variable(Sensor *parentSense, int varNum, _currentValue = -9999; } -void Variable::attachSensor(int varNum, Sensor *parentSense) { - MS_DBG(F("Attempting to register "), getVarName()); - MS_DBG(F(" to "), parentSense->getSensorName()); - MS_DBG(F(" attached at "), parentSense->getSensorLocation(), F("... ")); - parentSense->registerVariable(varNum, this); +// The constructor for a calculated variable - that is, one whos value is +// calculated by the calcFxn which returns a float. +// NOTE: ALL arguments are required! +Variable::Variable(float (*calcFxn)(), + String varName, String varUnit, + unsigned int decimalResolution, + String UUID, String customVarCode) +{ + _isCalculated = true; + _calcFxn = calcFxn; + parentSensor = NULL; + _varNum = 0; + _varName = varName; + _varUnit = varUnit; + _decimalResolution = decimalResolution; + _defaultVarCode = ""; + _customCode = customVarCode; + _UUID = UUID; + + // When we create the variable, we also want to initialize it with a current + // value of -9999 (ie, a bad result). + _currentValue = -9999; } -bool Variable::setup(void) + +// This notifies the parent sensor that it has an observing variable +// This function should never be called for a calculated variable +void Variable::attachSensor(int varNum, Sensor *parentSense) { - attachSensor(_varNum, parentSensor); - return true; + if (!_isCalculated) + { + MS_DBG(F("Attempting to register "), getVarName()); + MS_DBG(F(" to "), parentSense->getSensorName()); + MS_DBG(F(" attached at "), parentSense->getSensorLocation(), F("... ")); + parentSense->registerVariable(varNum, this); + } } + +// This is the function called by the parent sensor's notifyVariables() function +// This function should never be called for a calculated variable void Variable::onSensorUpdate(Sensor *parentSense) { - _currentValue = parentSense->sensorValues[_varNum]; - MS_DBG(F("... received "), sensorValue, F("\n")); + if (!_isCalculated) + { + _currentValue = parentSense->sensorValues[_varNum]; + MS_DBG(F("... received "), sensorValue, F("\n")); + } } -String Variable::getVarUUID(void) {return _UUID;} + +// This sets up the variable (generally attaching it to its parent) +bool Variable::setup(void) +{ + if (!_isCalculated) attachSensor(_varNum, parentSensor); + return true; +} // This returns the variable's name using http://vocabulary.odm2.org/variablename/ String Variable::getVarName(void){return _varName;} @@ -69,13 +109,29 @@ String Variable::getVarCode(void) else return _defaultVarCode; } +// This returns the variable UUID, if one has been assigned +String Variable::getVarUUID(void) {return _UUID;} + + // This returns the current value of the variable as a float float Variable::getValue(bool updateValue) { - if (updateValue) parentSensor->update(); - return _currentValue; + if (_isCalculated) + { + // NOTE: We cannot "update" the parent sensor's values before doing + // the calculation because we don't know which sensors those are. + // Make sure you update the parent sensors manually for a calculated + // variable!! + return _calcFxn(); + } + else + { + if (updateValue) parentSensor->update(); + return _currentValue; + } } + // This returns the current value of the variable as a string // with the correct number of significant figures String Variable::getValueString(bool updateValue) diff --git a/src/VariableBase.h b/src/VariableBase.h index 0e71c1780..a6c28e8b7 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -20,14 +20,27 @@ class Sensor; // Forward declaration class Variable { public: + // The constructor for a measured variable - that is, one whos values are + // updated by a sensor. Variable(Sensor *parentSense, int varNum, String varName = "Unknown", String varUnit = "Unknown", unsigned int decimalResolution = 0, String defaultVarCode = "Unknown", String UUID = "", String customVarCode = ""); + // The constructor for a measured variable - that is, one whos value is + // calculated by the calcFxn which returns a float. + // NOTE: ALL arguments are required! + Variable(float (*calcFxn)(), + String varName, String varUnit, + unsigned int decimalResolution, + String UUID, String customVarCode); + // These functions tie the variable and sensor together + // They should never be called for a calculated variable + // This notifies the parent sensor that it has an observing variable void attachSensor(int varNum, Sensor *parentSense); + // This is the function called by the parent sensor's notifyVariables() function virtual void onSensorUpdate(Sensor *parentSense); // This sets up the variable (generally attaching it to its parent) @@ -44,7 +57,8 @@ class Variable // This returns the current value of the variable as a float float getValue(bool updateValue = false); - // This returns the current value of the variable as a string with the correct number of significant figures + // This returns the current value of the variable as a string with the + // correct number of significant figures String getValueString(bool updateValue = false); // This is the parent sensor for the variable @@ -54,6 +68,8 @@ class Variable float _currentValue; private: + bool _isCalculated; + float (*_calcFxn)(void); uint8_t _varNum; String _varName; String _varUnit; From 6221d5bab2c584b198f9ec85af75f9556eb0a9f4 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 12:23:01 -0400 Subject: [PATCH 06/54] Added a calculated variable to the single sensor example --- examples/single_sensor/single_sensor.ino | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/examples/single_sensor/single_sensor.ino b/examples/single_sensor/single_sensor.ino index 6f2ef739d..5759eb15e 100644 --- a/examples/single_sensor/single_sensor.ino +++ b/examples/single_sensor/single_sensor.ino @@ -78,6 +78,16 @@ MaxBotixSonar sonar(sonarSerial, SonarPower, SonarTrigger) ; // Create a new instance of the range variable; MaxBotixSonar_Range sonar_range(&sonar); +// Create a function to calculate some value +float add10(void) +{ + return sonar_range.getValue() + 10; +} + + +// Create a calculated variable +Variable calcVar(add10, "Calculated Value", "millimeter", 1, "", "CalcTest"); + // ========================================================================== // Board setup info // ========================================================================== @@ -158,6 +168,8 @@ void loop() // Print the sonar result Serial.print("Current sonar range: "); Serial.println(sonar_range.getValueString()); + Serial.print("Calculated sonar range + 10: "); + Serial.println(calcVar.getValueString()); // Put the sensor back to sleep sonar.sleep(); From 3696e25267e6447b4a11a59461eb2f95ed3264fe Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 12:49:16 -0400 Subject: [PATCH 07/54] Arrays should now deal with calculated variables --- src/LoggerBase.cpp | 2 +- src/VariableArray.cpp | 98 ++++++++++++++++++++++++++++++------------- src/VariableBase.cpp | 20 ++++++--- src/VariableBase.h | 4 +- 4 files changed, 86 insertions(+), 38 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 30090fe44..856bb437d 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -537,7 +537,7 @@ String Logger::generateFileHeader(void) // Create the header rows String dataHeader = ""; // Next line will be the parent sensor names - makeHeaderRowMacro(logIDRowHeader, _variableList[i]->parentSensor->getSensorName()) + makeHeaderRowMacro(logIDRowHeader, _variableList[i]->getParentSensorName()) // Next comes the ODM2 variable name makeHeaderRowMacro(logIDRowHeader, _variableList[i]->getVarName()) // Next comes the ODM2 unit name diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index cb4a4c018..900292141 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -29,18 +29,23 @@ void VariableArray::init(int variableCount, Variable *variableList[]) int VariableArray::getSensorCount(void) { int numSensors = 0; + int numCalc = 0; // Check for unique sensors for (int i = 0; i < _variableCount; i++) { if (isLastVarFromSensor(i)) numSensors++; + if (_variableList[i]->isCalculated) numCalc++; } - MS_DBG(F("There are "), numSensors, F(" unique sensors in the group.\n")); + MS_DBG(F("There are "), numSensors, F(" unique sensors and "), numCalc, + F(" calculated variablesin the group.\n")); return numSensors; } // Public functions for interfacing with a list of sensors // This sets up all of the sensors in the list +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. bool VariableArray::setupSensors(void) { bool success = true; @@ -122,6 +127,8 @@ bool VariableArray::setupSensors(void) // This powers up the sensors // There's no checking or waiting here, just turning on pins +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. void VariableArray::sensorsPowerUp(void) { MS_DBG(F("Powering up sensors...\n")); @@ -143,6 +150,8 @@ void VariableArray::sensorsPowerUp(void) // This wakes/activates the sensors // Before a sensor is "awoken" we have to make sure it's had time to warm up +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. bool VariableArray::sensorsWake(void) { MS_DBG(F("Waking sensors...\n")); @@ -206,6 +215,8 @@ bool VariableArray::sensorsWake(void) // This puts sensors to sleep // We're not waiting for anything to be ready, we're just sending the command // to put it to sleep no matter what its current state is. +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. bool VariableArray::sensorsSleep(void) { MS_DBG(F("Putting sensors to sleep...\n")); @@ -232,6 +243,8 @@ bool VariableArray::sensorsSleep(void) // This cuts power to the sensors // We're not waiting for anything to be ready, we're just cutting power. +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. void VariableArray::sensorsPowerDown(void) { MS_DBG(F("Powering down sensors...\n")); @@ -255,6 +268,8 @@ void VariableArray::sensorsPowerDown(void) // Please note that this does NOT run the update functions, it instead uses // the startSingleMeasurement and addSingleMeasurementResult functions to // take advantage of the ability of sensors to be measuring concurrently. +// NOTE: Calculated variables will always be skipped in this process because +// a calculated variable will never be marked as the last variable from a sensor. bool VariableArray::updateAllSensors(void) { bool success = true; @@ -415,34 +430,48 @@ bool VariableArray::updateAllSensors(void) // This function prints out the results for any connected sensors to a stream +// Calculated variable results will be included void VariableArray::printSensorData(Stream *stream) { for (int i = 0; i < _variableCount; i++) { - stream->print(_variableList[i]->parentSensor->getSensorName()); - stream->print(F(" at ")); - stream->print(_variableList[i]->parentSensor->getSensorLocation()); - // stream->print(F(" with status 0b")); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 7)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 6)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 5)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 4)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 3)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 2)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 1)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 0)); - stream->print(F(" reports ")); - stream->print(_variableList[i]->getVarName()); - stream->print(F(" is ")); - stream->print(_variableList[i]->getValueString()); - stream->print(F(" ")); - stream->print(_variableList[i]->getVarUnit()); - stream->println(); + if (_variableList[i]->isCalculated) + { + stream->print(_variableList[i]->getVarName()); + stream->print(F(" is calculated to be ")); + stream->print(_variableList[i]->getValueString()); + stream->print(F(" ")); + stream->print(_variableList[i]->getVarUnit()); + stream->println(); + } + else + { + stream->print(_variableList[i]->parentSensor->getSensorName()); + stream->print(F(" at ")); + stream->print(_variableList[i]->parentSensor->getSensorLocation()); + // stream->print(F(" with status 0b")); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 7)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 6)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 5)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 4)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 3)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 2)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 1)); + // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 0)); + stream->print(F(" reports ")); + stream->print(_variableList[i]->getVarName()); + stream->print(F(" is ")); + stream->print(_variableList[i]->getValueString()); + stream->print(F(" ")); + stream->print(_variableList[i]->getVarUnit()); + stream->println(); + } } } // This generates a comma separated list of sensor values WITHOUT TIME STAMP +// Calculated variable results will be included String VariableArray::generateSensorDataCSV(void) { String csvString = F(""); @@ -460,25 +489,34 @@ String VariableArray::generateSensorDataCSV(void) } +// Check for unique sensors bool VariableArray::isLastVarFromSensor(int arrayIndex) { - // Check for unique sensors - String sensName = _variableList[arrayIndex]->parentSensor->getSensorName(); - String sensLoc = _variableList[arrayIndex]->parentSensor->getSensorLocation(); - bool unique = true; - for (int j = arrayIndex + 1; j < _variableCount; j++) + // Calculated variables are never the last variable from a sensor, simply + // because the don't come from a sensor at all. + if (_variableList[arrayIndex]->isCalculated) return false; + + else { - if (sensName == _variableList[j]->parentSensor->getSensorName() && - sensLoc == _variableList[j]->parentSensor->getSensorLocation()) + String sensName = _variableList[arrayIndex]->parentSensor->getSensorName(); + String sensLoc = _variableList[arrayIndex]->parentSensor->getSensorLocation(); + bool unique = true; + for (int j = arrayIndex + 1; j < _variableCount; j++) { - unique = false; - break; + if (sensName == _variableList[j]->parentSensor->getSensorName() && + sensLoc == _variableList[j]->parentSensor->getSensorLocation()) + { + unique = false; + break; + } } + return unique; } - return unique; } +// Count the maximum number of readings needed from a single sensor for the +// requested averaging uint8_t VariableArray::countMaxToAverage(void) { int numReps = 0; diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 536b067d0..23432e6a9 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -22,7 +22,7 @@ Variable::Variable(Sensor *parentSense, int varNum, String defaultVarCode, String UUID, String customVarCode) { - _isCalculated = false; + isCalculated = false; _calcFxn = NULL; parentSensor = parentSense; _varNum = varNum; @@ -46,7 +46,7 @@ Variable::Variable(float (*calcFxn)(), unsigned int decimalResolution, String UUID, String customVarCode) { - _isCalculated = true; + isCalculated = true; _calcFxn = calcFxn; parentSensor = NULL; _varNum = 0; @@ -67,7 +67,7 @@ Variable::Variable(float (*calcFxn)(), // This function should never be called for a calculated variable void Variable::attachSensor(int varNum, Sensor *parentSense) { - if (!_isCalculated) + if (!isCalculated) { MS_DBG(F("Attempting to register "), getVarName()); MS_DBG(F(" to "), parentSense->getSensorName()); @@ -81,7 +81,7 @@ void Variable::attachSensor(int varNum, Sensor *parentSense) // This function should never be called for a calculated variable void Variable::onSensorUpdate(Sensor *parentSense) { - if (!_isCalculated) + if (!isCalculated) { _currentValue = parentSense->sensorValues[_varNum]; MS_DBG(F("... received "), sensorValue, F("\n")); @@ -89,10 +89,18 @@ void Variable::onSensorUpdate(Sensor *parentSense) } +// This is a helper - it returns the name of the parent sensor, if applicable +String Variable::getParentSensorName(void) +{ + if (!isCalculated) return parentSensor->getSensorName(); + else return "Calculated"; +} + + // This sets up the variable (generally attaching it to its parent) bool Variable::setup(void) { - if (!_isCalculated) attachSensor(_varNum, parentSensor); + if (!isCalculated) attachSensor(_varNum, parentSensor); return true; } @@ -116,7 +124,7 @@ String Variable::getVarUUID(void) {return _UUID;} // This returns the current value of the variable as a float float Variable::getValue(bool updateValue) { - if (_isCalculated) + if (isCalculated) { // NOTE: We cannot "update" the parent sensor's values before doing // the calculation because we don't know which sensors those are. diff --git a/src/VariableBase.h b/src/VariableBase.h index a6c28e8b7..cb61101fb 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -42,6 +42,8 @@ class Variable void attachSensor(int varNum, Sensor *parentSense); // This is the function called by the parent sensor's notifyVariables() function virtual void onSensorUpdate(Sensor *parentSense); + // This is a helper - it returns the name of the parent sensor, if applicable + String getParentSensorName(void); // This sets up the variable (generally attaching it to its parent) virtual bool setup(void); @@ -63,12 +65,12 @@ class Variable // This is the parent sensor for the variable Sensor *parentSensor; + bool isCalculated; protected: float _currentValue; private: - bool _isCalculated; float (*_calcFxn)(void); uint8_t _varNum; String _varName; From f9a0a341ef509f0ef8438aebc26b1210a346e4a9 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 12:50:49 -0400 Subject: [PATCH 08/54] Fixed single_sensor for Travis --- examples/single_sensor/single_sensor.ino | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/single_sensor/single_sensor.ino b/examples/single_sensor/single_sensor.ino index 5759eb15e..fe1691285 100644 --- a/examples/single_sensor/single_sensor.ino +++ b/examples/single_sensor/single_sensor.ino @@ -48,15 +48,15 @@ const int8_t SonarPower = 22; // excite (power) pin #if defined __AVR__ -// #include // for the stream communication -// SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx - -#include // for the stream communication -NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx -void NeoSWSISR() -{ - NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); -} +#include // for the stream communication +SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx + +// #include // for the stream communication +// NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// void NeoSWSISR() +// { +// NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +// } #endif From d2979c5a5c56ac218e714564cab0aae8281d9511 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 13:49:03 -0400 Subject: [PATCH 09/54] Made calculation in single_sensor less trivial --- examples/ReadMe.md | 2 +- examples/single_sensor/ReadMe.md | 2 +- examples/single_sensor/single_sensor.ino | 22 +++++++++++++--------- 3 files changed, 15 insertions(+), 11 deletions(-) diff --git a/examples/ReadMe.md b/examples/ReadMe.md index c2f18135b..98441569f 100644 --- a/examples/ReadMe.md +++ b/examples/ReadMe.md @@ -19,7 +19,7 @@ To adjust any of these to work with your own sensor arrangements: 14. Program your board! ### single_sensor.ino -This shows making use of the unified set of commands to print data from a MaxBotix ultrasonic range finder to the serial port. +This shows making use of the unified set of commands to print data from a MaxBotix ultrasonic range finder to the serial port. It also shows creating a calculated variable which is the water depth. ### multisensor_print.ino This shows using an array of sensors to easily update all of them and print all results to the serial port. This example calls on at least one of every single sensor available in this library. diff --git a/examples/single_sensor/ReadMe.md b/examples/single_sensor/ReadMe.md index d55f1ce26..2ec3ceffc 100644 --- a/examples/single_sensor/ReadMe.md +++ b/examples/single_sensor/ReadMe.md @@ -1,3 +1,3 @@ # Example using the Modular Sensors Library to Communicate with a Single Sensor -This somewhat trivial example show making use of the unified set of commands to print data from a MaxBotix ultrasonic range finder to the serial port. It is somewhat complicated by showing the defining and selection of a HardwareSerial port for a SAMD21 board and the selection of a SoftwareSerial port for a AVR board. +This somewhat trivial example show making use of the unified set of commands to print data from a MaxBotix ultrasonic range finder to the serial port. It also shows creating a calculated variable which is the water depth. It is somewhat complicated by showing the defining and selection of a HardwareSerial port for a SAMD21 board and the selection of a SoftwareSerial port for a AVR board. diff --git a/examples/single_sensor/single_sensor.ino b/examples/single_sensor/single_sensor.ino index fe1691285..25eb91d4a 100644 --- a/examples/single_sensor/single_sensor.ino +++ b/examples/single_sensor/single_sensor.ino @@ -78,15 +78,19 @@ MaxBotixSonar sonar(sonarSerial, SonarPower, SonarTrigger) ; // Create a new instance of the range variable; MaxBotixSonar_Range sonar_range(&sonar); -// Create a function to calculate some value -float add10(void) +// Create a function to calculate the water depth from the sonar range +// For this example, we'll assume that the sonar is mounted 5m above the stream bottom +float calcDepth(void) { - return sonar_range.getValue() + 10; + float mountHeight = 5000; + float sonarRange = sonar_range.getValue(); + return mountHeight - sonarRange; } - - -// Create a calculated variable -Variable calcVar(add10, "Calculated Value", "millimeter", 1, "", "CalcTest"); +// Create a calculated variable for the water depth +// Variable calcVar(functionName, VariableName, VariableUnit, Resolution, UUID, Code); +// VariableName must be a value from http://vocabulary.odm2.org/variablename/ +// VariableUnit must be a value from http://vocabulary.odm2.org/units/ +Variable waterDepth(calcDepth, "waterDepth", "millimeter", 0, "", "sonarDepth"); // ========================================================================== // Board setup info @@ -168,8 +172,8 @@ void loop() // Print the sonar result Serial.print("Current sonar range: "); Serial.println(sonar_range.getValueString()); - Serial.print("Calculated sonar range + 10: "); - Serial.println(calcVar.getValueString()); + Serial.print("Calculated water depth: "); + Serial.println(waterDepth.getValueString()); // Put the sensor back to sleep sonar.sleep(); From 3a0fa5947637224c785e3a8e691521364ad08ade Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 13:54:21 -0400 Subject: [PATCH 10/54] debugging correction --- src/VariableBase.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 23432e6a9..b91e4555f 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -84,7 +84,7 @@ void Variable::onSensorUpdate(Sensor *parentSense) if (!isCalculated) { _currentValue = parentSense->sensorValues[_varNum]; - MS_DBG(F("... received "), sensorValue, F("\n")); + MS_DBG(F("... received "), _currentValue, F("\n")); } } From 1574b9081f654671ee5e94380d7ba5004beb8093 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 14:06:29 -0400 Subject: [PATCH 11/54] Added helper functions for parent sensors of variables Needed for the calculated variables in arrays --- src/VariableArray.cpp | 73 ++++++++++++++++++++++++------------------- src/VariableBase.cpp | 10 ++++++ src/VariableBase.h | 4 +++ 3 files changed, 54 insertions(+), 33 deletions(-) diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index 900292141..979dfb74b 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -67,9 +67,9 @@ bool VariableArray::setupSensors(void) { if (bitRead(_variableList[i]->parentSensor->getStatus(), 1) == 1) // already set up { - MS_DBG(F(" ... "), _variableList[i]->parentSensor->getSensorName()); + MS_DBG(F(" ... "), _variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" was already set up!\n")); nSensorsSetup++; @@ -93,9 +93,9 @@ bool VariableArray::setupSensors(void) if (_variableList[i]->parentSensor->isWarmedUp()) // is warmed up { MS_DBG(F(" ... Set up of ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" ...\n")); sensorSuccess = _variableList[i]->parentSensor->setup(); // set it up @@ -137,9 +137,9 @@ void VariableArray::sensorsPowerUp(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... Powering up ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG('\n'); _variableList[i]->parentSensor->powerUp(); @@ -165,9 +165,9 @@ bool VariableArray::sensorsWake(void) { if (bitRead(_variableList[i]->parentSensor->getStatus(), 3) == 1) // already awake { - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" was already awake.\n")); nSensorsAwake++; } @@ -189,9 +189,9 @@ bool VariableArray::sensorsWake(void) if (_variableList[i]->parentSensor->isWarmedUp()) // already warmed up { MS_DBG(F(" ... Wake up of ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" ...\n")); // Make a single attempt to wake the sensor after it is warmed up @@ -226,9 +226,9 @@ bool VariableArray::sensorsSleep(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); bool sensorSuccess = _variableList[i]->parentSensor->sleep(); success &= sensorSuccess; @@ -253,9 +253,9 @@ void VariableArray::sensorsPowerDown(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... powering down ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG('\n'); _variableList[i]->parentSensor->powerDown(); @@ -297,9 +297,9 @@ bool VariableArray::updateAllSensors(void) { if (bitRead(_variableList[i]->parentSensor->getStatus(), 3) == 0) // NOT awake/activated { - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" isn't awake/active! No readings will be taken!\n")); // Set the number of readings already equal to whatever total @@ -324,9 +324,9 @@ bool VariableArray::updateAllSensors(void) // _variableList[i]->parentSensor->updateStatusBits(true); // MS_DBG(i); // MS_DBG(F(" - ")); - // MS_DBG(_variableList[i]->parentSensor->getSensorName()); + // MS_DBG(_variableList[i]->getParentSensorName()); // MS_DBG(F(" at ")); - // MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + // MS_DBG(_variableList[i]->getParentSensorLocation()); // MS_DBG(F(" - millis: ")); // MS_DBG(millis()); // MS_DBG(F(" - status: 0b")); @@ -359,9 +359,9 @@ bool VariableArray::updateAllSensors(void) MS_DBG(F("- Starting reading ")); MS_DBG(nMeasurementsCompleted[i]+1); MS_DBG(F(" on ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" -\n")); bool sensorSuccess_start = _variableList[i]->parentSensor->startSingleMeasurement(); @@ -379,9 +379,9 @@ bool VariableArray::updateAllSensors(void) MS_DBG(F("-- Collected result of reading ")); MS_DBG(nMeasurementsCompleted[i]+1); MS_DBG(F(" from ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" --\n")); bool sensorSuccess_result = _variableList[i]->parentSensor->addSingleMeasurementResult(); @@ -398,9 +398,9 @@ bool VariableArray::updateAllSensors(void) if (nMeasurementsCompleted[i] == _variableList[i]->parentSensor->getNumberMeasurementsToAverage()) { MS_DBG(F("--- Finished all readings from ")); - MS_DBG(_variableList[i]->parentSensor->getSensorName()); + MS_DBG(_variableList[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->parentSensor->getSensorLocation()); + MS_DBG(_variableList[i]->getParentSensorLocation()); MS_DBG(F(" ---\n")); nSensorsCompleted++; @@ -416,11 +416,11 @@ bool VariableArray::updateAllSensors(void) if (isLastVarFromSensor(i)) { // MS_DBG(F("--- Averaging results from ")); - // MS_DBG(_variableList[i]->parentSensor->getSensorName()); + // MS_DBG(_variableList[i]->getParentSensorName()); _variableList[i]->parentSensor->averageMeasurements(); // MS_DBG(F(" ---\n")); // MS_DBG(F("--- Notifying variables from ")); - // MS_DBG(_variableList[i]->parentSensor->getSensorName()); + // MS_DBG(_variableList[i]->getParentSensorName()); _variableList[i]->parentSensor->notifyVariables(); // MS_DBG(F(" ---\n")); } @@ -446,9 +446,9 @@ void VariableArray::printSensorData(Stream *stream) } else { - stream->print(_variableList[i]->parentSensor->getSensorName()); + stream->print(_variableList[i]->getParentSensorName()); stream->print(F(" at ")); - stream->print(_variableList[i]->parentSensor->getSensorLocation()); + stream->print(_variableList[i]->getParentSensorLocation()); // stream->print(F(" with status 0b")); // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 7)); // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 6)); @@ -494,22 +494,29 @@ bool VariableArray::isLastVarFromSensor(int arrayIndex) { // Calculated variables are never the last variable from a sensor, simply // because the don't come from a sensor at all. - if (_variableList[arrayIndex]->isCalculated) return false; + MS_DBG(F("Checking if "), arrayIndex, F(" is the last variable from a sensor...")); + if (_variableList[arrayIndex]->isCalculated) + { + MS_DBG(F(" ... Nope, it's calculated!\n")); + return false; + } else { - String sensName = _variableList[arrayIndex]->parentSensor->getSensorName(); - String sensLoc = _variableList[arrayIndex]->parentSensor->getSensorLocation(); + String sensName = _variableList[arrayIndex]->getParentSensorName(); + String sensLoc = _variableList[arrayIndex]->getParentSensorLocation(); bool unique = true; for (int j = arrayIndex + 1; j < _variableCount; j++) { - if (sensName == _variableList[j]->parentSensor->getSensorName() && - sensLoc == _variableList[j]->parentSensor->getSensorLocation()) + if (sensName == _variableList[j]->getParentSensorName() && + sensLoc == _variableList[j]->getParentSensorLocation()) { unique = false; + MS_DBG(F(" ... Nope, there are others after it!\n")); break; } } + if (unique) MS_DBG(F(" ... Yes, it is!\n")); return unique; } } diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index b91e4555f..134fc5fe9 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -90,6 +90,16 @@ void Variable::onSensorUpdate(Sensor *parentSense) // This is a helper - it returns the name of the parent sensor, if applicable +// This is needed for dealing with variables in arrays +String Variable::getParentSensorLocation(void) +{ + if (!isCalculated) return parentSensor->getSensorLocation(); + else return "Calculated"; +} + + +// This is a helper - it returns the name of the parent sensor, if applicable +// This is needed for dealing with variables in arrays String Variable::getParentSensorName(void) { if (!isCalculated) return parentSensor->getSensorName(); diff --git a/src/VariableBase.h b/src/VariableBase.h index cb61101fb..582185fd2 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -43,7 +43,11 @@ class Variable // This is the function called by the parent sensor's notifyVariables() function virtual void onSensorUpdate(Sensor *parentSense); // This is a helper - it returns the name of the parent sensor, if applicable + // This is needed for dealing with variables in arrays String getParentSensorName(void); + // This is needed for dealing with variables in arrays + // This is a helper - it returns the "location" of the parent sensor, if applicable + String getParentSensorLocation(void); // This sets up the variable (generally attaching it to its parent) virtual bool setup(void); From c6cbd3d53129be48fd86e222ceecef623b6c6c35 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 14:33:18 -0400 Subject: [PATCH 12/54] Debugging changes --- src/VariableArray.cpp | 10 ++++++---- src/VariableBase.cpp | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index 979dfb74b..8ea78375a 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -492,12 +492,14 @@ String VariableArray::generateSensorDataCSV(void) // Check for unique sensors bool VariableArray::isLastVarFromSensor(int arrayIndex) { + // MS_DBG(F("Checking if "), _variableList[arrayIndex]->getVarName(), F(" ("), + // arrayIndex, F(") is the last variable from a sensor...")); + // Calculated variables are never the last variable from a sensor, simply // because the don't come from a sensor at all. - MS_DBG(F("Checking if "), arrayIndex, F(" is the last variable from a sensor...")); if (_variableList[arrayIndex]->isCalculated) { - MS_DBG(F(" ... Nope, it's calculated!\n")); + // MS_DBG(F(" ... Nope, it's calculated!\n")); return false; } @@ -512,11 +514,11 @@ bool VariableArray::isLastVarFromSensor(int arrayIndex) sensLoc == _variableList[j]->getParentSensorLocation()) { unique = false; - MS_DBG(F(" ... Nope, there are others after it!\n")); + // MS_DBG(F(" ... Nope, there are others after it!\n")); break; } } - if (unique) MS_DBG(F(" ... Yes, it is!\n")); + // if (unique) MS_DBG(F(" ... Yes, it is!\n")); return unique; } } diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 134fc5fe9..582b26d8f 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -71,7 +71,7 @@ void Variable::attachSensor(int varNum, Sensor *parentSense) { MS_DBG(F("Attempting to register "), getVarName()); MS_DBG(F(" to "), parentSense->getSensorName()); - MS_DBG(F(" attached at "), parentSense->getSensorLocation(), F("... ")); + MS_DBG(F(" attached at "), parentSense->getSensorLocation(), F("... \n")); parentSense->registerVariable(varNum, this); } } From bc67a8792d96581baec464e6bde9f8aecf05f64b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 14:39:58 -0400 Subject: [PATCH 13/54] baro/density correction example now uses calculated variables --- examples/ReadMe.md | 6 +- examples/baro_rho_correction/ReadMe.md | 2 +- .../baro_rho_correction.ino | 331 ++++++------------ 3 files changed, 103 insertions(+), 236 deletions(-) diff --git a/examples/ReadMe.md b/examples/ReadMe.md index 98441569f..aacb278a1 100644 --- a/examples/ReadMe.md +++ b/examples/ReadMe.md @@ -39,11 +39,11 @@ This is a simplified version of logging_to_EnviroDIY.ino using just the sensors ### DWRI_NoCellular.ino This is uses just the sensors and equipment standard to the DWRI Citizen Science grant for circumstances where there is no cellular signal. +### baro_rho_correction.ino +This example demonstrates how to work with calculated variables. + ### double_logger.ino This is a more complicated example using two different logger instances to log data at two different intervals, in this case, an AM3215 logging every minute, while checking the battery voltage only every 5 minutes. This showcases both how to use two different logging instances and how to use some of the functions to set up your own logging loop rather than using the log() function. -### baro_rho_correction.ino -Like the double_logger example, this showcases how to set up your own logging loop rather than using the log() function. In this case, though, there is only a single logger, but we are adding some extra calculated variables to the final output. - ### data_saving.ino This is another double logger example, but in this case, both loggers are going at the same interval and the only difference between the loggers is the list of variables. There are two sets of variables, all coming from Yosemitech sensors. Because each sensor outputs temperature and we don't want to waste cellular data sending out multiple nearly identical temperature values, we have one logger that logs every possible variable result to the SD card and another logger that sends only unique results to the EnviroDIY data portal. diff --git a/examples/baro_rho_correction/ReadMe.md b/examples/baro_rho_correction/ReadMe.md index d4f987a14..184d2c053 100644 --- a/examples/baro_rho_correction/ReadMe.md +++ b/examples/baro_rho_correction/ReadMe.md @@ -1,3 +1,3 @@ # Example using the Modular Sensors Library to Calculate Results based on Measured Values and Send Both Measured and Calculated Values to the EnviroDIY Data Portal -Like the double_logger example, this showcases how to set up your own logging loop rather than using the log() function. In this case, though, there is only a single logger, but we are adding some extra calculated variables to the final output. +This example demonstrates how to work with calculated variables. diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index e3fe88dcd..22508fdcf 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -19,8 +19,8 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. // #define TINY_GSM_MODEM_A6 // Select for a AI-Thinker A6 or A7 chip // #define TINY_GSM_MODEM_M590 // Select for a Neoway M590 // #define TINY_GSM_MODEM_UBLOX // Select for most u-blox cellular modems -#define TINY_GSM_MODEM_ESP8266 // Select for an ESP8266 using the DEFAULT AT COMMAND FIRMWARE -// #define TINY_GSM_MODEM_XBEE // Select for Digi brand WiFi or Cellular XBee's +// #define TINY_GSM_MODEM_ESP8266 // Select for an ESP8266 using the DEFAULT AT COMMAND FIRMWARE +#define TINY_GSM_MODEM_XBEE // Select for Digi brand WiFi or Cellular XBee's // ========================================================================== // Include the base required libraries @@ -162,7 +162,6 @@ MaximDS18 ds18_u(OneWirePower, OneWireBus); Variable *ds18Temp = new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-1234567890ab"); - // ========================================================================== // MeaSpecMS5803 (Pressure, Temperature) // ========================================================================== @@ -171,16 +170,100 @@ Variable *ds18Temp = new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-123456 const uint8_t MS5803i2c_addr = 0x76; // The MS5803 can be addressed either as 0x76 (default) or 0x77 const int MS5803maxPressure = 14; // The maximum pressure measurable by the specific MS5803 model const uint8_t MS5803ReadingsToAvg = 1; -// Create and return the MeaSpec MS5803 sensor object +// Create and return the MeaSpec MS5803 pressure and temperature sensor object MeaSpecMS5803 ms5803(I2CPower, MS5803i2c_addr, MS5803maxPressure, MS5803ReadingsToAvg); // Create the temperature and pressure variable objects for the MS5803 and return variable pointers to them Variable *msTemp = new MeaSpecMS5803_Temp(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"); Variable *msPress = new MeaSpecMS5803_Pressure(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"); +// ========================================================================== +// Calculated Variables +// ========================================================================== + +// Create the function to calculate the water pressure +// Water pressure = pressure from MS5803 (water+baro) - pressure from BME280 (baro) +// The MS5803 reports pressure in millibar, the BME280 in pascal +// 1 pascal = 0.01 mbar +float calculateWaterPressure(void) +{ + float waterPressure = msPress->getValue() - (bPress->getValue())*0.01; + // Serial.print(F("Water pressure is ")); // for debugging + // Serial.println(waterPressure); // for debugging + return waterPressure; +} +// Properties of the calculated water pressure variable +String waterPresureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ +String waterPresureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ +int waterPresureVarResolution = 3; +String waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; +String waterPresureVarCode = "CorrectedPressure"; +// Create the calculated water pressure variable objects and return a variable pointer to it +Variable *calcWaterPress = new Variable(calculateWaterPressure, waterPresureVarName, + waterPresureVarUnit, waterPresureVarResolution, + waterPressureUUID, waterPresureVarCode); + +// Create the function to calculate the "raw" water depth +// For this, we're using the conversion between mbar and mm pure water at 4°C +// This calculation gives a final result in mm of water +float calculateWaterDepthRaw(void) +{ + float waterDepth = calculateWaterPressure()*10.1972; + // Serial.print(F("'Raw' water depth is ")); // for debugging + // Serial.println(waterDepth); // for debugging + return waterDepth; +} +// Properties of the calculated water depth variable +String waterDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ +String waterDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ +int waterDepthVarResolution = 3; +String waterDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; +String waterDepthVarCode = "CalcDepth"; +// Create the calculated raw water depth variable objects and return a variable pointer to it +Variable *calcRawDepth = new Variable(calculateWaterDepthRaw, waterDepthVarName, + waterDepthVarUnit, waterDepthVarResolution, + waterDepthUUID, waterDepthVarCode); + +// Create the function to calculate the water depth after correcting water density for temperature +// This calculation gives a final result in mm of water +float calculateWaterDepthTempCorrected(void) +{ + const float gravitationalConstant = 9.80665; // m/s2, meters per second squared + // First get water pressure in Pa for the calculation: 1 mbar = 100 Pa + float waterPressurePa = 100 * calculateWaterPressure(); + float waterTempertureC = msTemp->getValue(); + // Converting water depth for the changes of pressure with depth + // Water density (kg/m3) from equation 6 from JonesHarris1992-NIST-DensityWater.pdf + float waterDensity = + 999.84847 + + 6.337563e-2 * waterTempertureC + - 8.523829e-3 * pow(waterTempertureC,2) + + 6.943248e-5 * pow(waterTempertureC,3) + - 3.821216e-7 * pow(waterTempertureC,4) + ; + // This calculation gives a final result in mm of water + // from P = rho * g * h + float rhoDepth = 1000 * waterPressurePa/(waterDensity * gravitationalConstant); + // Serial.print(F("Temperature corrected water depth is ")); // for debugging + // Serial.println(rhoDepth); // for debugging + return rhoDepth; +} +// Properties of the calculated temperature corrected water depth variable +String rhoDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ +String rhoDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ +int rhoDepthVarResolution = 3; +String rhoDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; +String rhoDepthVarCode = "DensityDepth"; +// Create the temperature corrected water depth variable objects and return a variable pointer to it +Variable *calcCorrDepth = new Variable(calculateWaterDepthTempCorrected, rhoDepthVarName, + rhoDepthVarUnit, rhoDepthVarResolution, + rhoDepthUUID, rhoDepthVarCode); + + // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// NOTE: Since we've created all of the variable pointers above, we can just +// reference them by name here. Variable *variableList[] = { mayflyBatt, mayflyRAM, @@ -192,6 +275,9 @@ Variable *variableList[] = { msTemp, msPress, ds18Temp, + calcWaterPress, + calcRawDepth, + calcCorrDepth, modemRSSI, modemSinalPct }; @@ -206,34 +292,6 @@ const char *registrationToken = "12345678-abcd-1234-efgh-1234567890ab"; // Dev const char *samplingFeature = "12345678-abcd-1234-efgh-1234567890ab"; // Sampling feature UUID -// ========================================================================== -// Extra information and tokens for calculted variables -// ========================================================================== -const char *waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; -const char *waterPresureVarName = "pressureGauge"; -const char *waterPresureVarUnit = "Millibar"; -const char *waterPresureVarCode = "CorrectedPressure"; -const char *waterDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; -const char *waterDepthVarName = "waterDepth"; -const char *waterDepthVarUnit = "millimeter"; -const char *waterDepthVarCode = "CalcDepth"; -const char *rhoDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; -const char *rhoDepthVarName = "rhoDepth"; -const char *rhoDepthVarUnit = "millimeter"; -const char *rhoDepthVarCode = "DensityDepth"; - - -// ========================================================================== -// Initialize variables for density correction -// ========================================================================== -float waterPressureBar = -9999.0; -float waterPressurePa = -9999.0; -float waterTempertureC = -9999.0; -float waterDensity = -9999.0; -float rhoDepth = -9999.0; -const float gravitationalConstant = 9.80665; // m/s2, meters per second squared - - // ========================================================================== // Working Functions // ========================================================================== @@ -287,14 +345,6 @@ void setup() loggingInterval, LoggerID); EnviroDIYLogger.setAlertPin(greenLED); - // Begin the real time clock - rtc.begin(); - delay(100); - - // Print out the current time - Serial.print(F("Current RTC time is: ")); - Serial.println(Logger::formatDateTime_ISO8601(Logger::getNowEpoch())); - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -307,71 +357,18 @@ void setup() // Attach the modem to the logger EnviroDIYLogger.attachModem(&modem); - // Immediately turn on the modem - EnviroDIYLogger._logModem->modemPowerUp(); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - // Set up the sensors - EnviroDIYLogger.setupSensors(); - - // Sync the clock with NIST - Serial.print(F("Attempting to synchronize RTC with NIST\n")); - // Connect to the network - if (EnviroDIYLogger._logModem->connectInternet()) - { - EnviroDIYLogger.syncRTClock(EnviroDIYLogger._logModem->getNISTTime()); - // Disconnect from the network - EnviroDIYLogger._logModem->disconnectInternet(); - } - // Turn off the modem - EnviroDIYLogger._logModem->modemPowerDown(); - - // Generate a logger file name from the LoggerID and the date/time on the RTC - // This will start a new file every time the logger is reset - EnviroDIYLogger.setFileName(); - - // Set up the log file and add a header to it with all of the information - // for the sensors and variables in the variable array - EnviroDIYLogger.setupLogFile(); - - // Now we're going to add another set of rows to the file header with - // just the information for the calculated variable - // We could make a "prettier" header by adding commas and values onto the - // end of each line of the multi-line header generated by the - // generateFileHeader() function, but that would take a bunch of really - // annoying string subscripting and re-combining (or just rewriting that - // whole generateFileHeader function, which is already a long annoying - // string concatenation function) so instead we're just creating another set - // of header rows for the csv with no values in the first spaces where - // header values exist and then starting the new header information shifted - // over by that many columns/commas - String extraHeaderSpacer = ""; - for (uint8_t i=0; i <= variableCount; i++) extraHeaderSpacer += ','; - // the first row is the variable UUID's, we have two: - // for calculated pressure and calculated depth - EnviroDIYLogger.logToSD(extraHeaderSpacer + String(waterPressureUUID) + - F(", ") + String(waterDepthUUID) + F(", ") + - String(rhoDepthUUID)); - // the next row is the sensor name, which is blank, so we'll put in a blank row - EnviroDIYLogger.logToSD(extraHeaderSpacer + F(", ")); - // the third row is the variable name - EnviroDIYLogger.logToSD(extraHeaderSpacer + String(waterPresureVarName) + - F(", ") + String(waterDepthVarName) + F(", ") + - String(rhoDepthVarName)); - // the fourth row is the variable unit name - EnviroDIYLogger.logToSD(extraHeaderSpacer + String(waterPresureVarUnit) + - F(", ") + String(waterDepthVarUnit) + F(", ") + - String(rhoDepthVarUnit)); - // the last row is the variable code - EnviroDIYLogger.logToSD(extraHeaderSpacer + String(waterPresureVarCode) + - F(", ") + String(waterDepthVarCode) + F(", ") + - String(rhoDepthVarCode)); - - // Setup the logger sleep mode - EnviroDIYLogger.setupSleep(); + // Set up the connection with DreamHost + #ifdef DreamHostPortalRX + EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); + #endif + + // Begin the logger + EnviroDIYLogger.begin(); // Hold up for 10-seconds to allow immediate entry into sensor testing mode // EnviroDIYLogger.checkForTestingMode(buttonPin); @@ -383,9 +380,6 @@ void setup() Serial.print(buttonPin); Serial.println(F(" at any time to enter sensor testing mode.")); - Serial.print(F("Logger setup finished!\n")); - Serial.print(F("------------------------------------------\n\n")); - // Blink the LEDs really fast to show start-up is done greenredflash(6, 25); @@ -397,135 +391,8 @@ void setup() // ========================================================================== // Main loop function // ========================================================================== - -// Because of the way the sleep mode is set up, the processor will wake up -// and start the loop every minute exactly on the minute. void loop() { - // Assuming we were woken up by the clock, check if the current time is an - // even interval of the logging interval - if (EnviroDIYLogger.checkInterval()) - { - // Print a line to show new reading - Serial.print(F("------------------------------------------\n")); - // Turn on the LED to show we're taking a reading - digitalWrite(greenLED, HIGH); - - // Turn on the modem to let it start searching for the network - EnviroDIYLogger._logModem->modemPowerUp(); - - // Send power to all of the sensors - Serial.print(F("Powering sensors...\n")); - EnviroDIYLogger.sensorsPowerUp(); - // Wake up all of the sensors - Serial.print(F("Waking sensors...\n")); - EnviroDIYLogger.sensorsWake(); - // Update the values from all attached sensors - Serial.print(F("Updating sensor values...\n")); - EnviroDIYLogger.updateAllSensors(); - // Put sensors to sleep - Serial.print(F("Putting sensors back to sleep...\n")); - EnviroDIYLogger.sensorsSleep(); - // Cut sensor power - Serial.print(F("Cutting sensor power...\n")); - EnviroDIYLogger.sensorsPowerDown(); - - // Generate a csv with the sensor-recorded variables - String csvRaw = EnviroDIYLogger.generateSensorDataCSV(); - - // Generate a json with the sensor-recorded variables - String jsonRaw = EnviroDIYLogger.generateSensorDataJSON(); - - // Calculate the water pressure after barometic correction - // As long as the seensor updates took less than two minutes, these - // getValue() functions will return the values from the last update - // that happened in the updateAllSensors() function - // The MS5803 reports pressure in millibar, the BME280 in pascal - // 1 pascal = 0.01 mbar - // This calculation gives a final result in mbar - Serial.print(F("Calculating water pressure...\n")); - float waterPressure = msPress->getValue() - (bPress->getValue())*0.01; - float waterTempertureC = msTemp->getValue(); - // Now calculate the depth of the water - // For this, we're using the conversion between mbar and mm pure water at 4°C - // This calculation gives a final result in mm of water - float waterDepth = waterPressure*10.1972; - // Converting water depth for the changes of pressure with depth - // First get water pressure in Pa for the calculation: 1 mbar = 100 Pa - waterPressurePa = 100 * waterPressure; - // Water density (kg/m3) from equation 6 from JonesHarris1992-NIST-DensityWater.pdf - waterDensity = + 999.84847 - + 6.337563e-2 * waterTempertureC - - 8.523829e-3 * pow(waterTempertureC,2) - + 6.943248e-5 * pow(waterTempertureC,3) - - 3.821216e-7 * pow(waterTempertureC,4) - ; - // This calculation gives a final result in mm of water - rhoDepth = 1000 * waterPressurePa/(waterDensity * gravitationalConstant); // from P = rho * g * h - - - // Add the water pressure and depth to the csv string - String csvToGo = csvRaw + ","; - csvToGo += String(waterPressure); - csvToGo += ","; - csvToGo += String(waterDepth); - csvToGo += ","; - csvToGo += String(rhoDepth); - - // Add the total water pressure to the raw json - // Figure out how long the original json is - int jsonLength = jsonRaw.length(); - // Crop off the last ' }' from the json - String jsonToGo = jsonRaw.substring(0,jsonLength-1); - // add the UUID for the water pressure - jsonToGo += F(", \""); - jsonToGo += String(waterPressureUUID); - jsonToGo += F("\": "); - // add the water pressure value - jsonToGo += String(waterPressure); - // add the UUID for the water depth - jsonToGo += F(", \""); - jsonToGo += String(waterDepthUUID); - jsonToGo += F("\": "); - // add the water depth value - jsonToGo += String(waterDepth); - // add the UUID for the density corrected water depth - jsonToGo += F(", \""); - jsonToGo += String(rhoDepthUUID); - jsonToGo += F("\": "); - // add the density corrected water depth value - jsonToGo += String(rhoDepth); - // re-add the last '}' - jsonToGo += F("}"); - - // Connect to the network - Serial.print(F("Connecting to the internet...\n")); - if (EnviroDIYLogger._logModem->connectInternet()) - { - // Post the data to the WebSDL - EnviroDIYLogger.postDataEnviroDIY(jsonToGo); - - // Disconnect from the network - EnviroDIYLogger._logModem->disconnectInternet(); - } - // Turn the modem off - EnviroDIYLogger._logModem->modemPowerDown(); - - // Create a csv data record and save it to the log file - EnviroDIYLogger.logToSD(csvToGo); - - // Turn off the LED - digitalWrite(greenLED, LOW); - // Print a line to show reading ended - Serial.print(F("------------------------------------------\n\n")); - } - - // Check if it was instead the testing interrupt that woke us up - // NOTE: This testing mode will *NOT* show the values from any of the extra - // calculated variables added in the loop. It will only show the variables - // listed in the variableList which is fed to the EnviroDIYLogger. - if (Logger::startTesting) EnviroDIYLogger.testingMode(); - - // Sleep - EnviroDIYLogger.systemSleep(); + // Log the data + EnviroDIYLogger.log(); } From eb683574d64a56f1cab7868d4d5d171c5e589b8d Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 15:02:30 -0400 Subject: [PATCH 14/54] Updated ReadMe, bumped version --- README.md | 48 +++++++++++-------- examples/DRWI_CitSci/platformio.ini | 2 +- examples/DRWI_NoCellular/platformio.ini | 2 +- examples/baro_rho_correction/platformio.ini | 2 +- examples/data_saving/platformio.ini | 2 +- examples/double_logger/platformio.ini | 2 +- examples/logging_to_EnviroDIY/platformio.ini | 2 +- .../logging_to_EnviroDIY_Zero/platformio.ini | 2 +- examples/multisensor_print/platformio.ini | 2 +- examples/simple_logging/platformio.ini | 2 +- examples/single_sensor/platformio.ini | 2 +- library.json | 2 +- library.properties | 2 +- src/VariableBase.cpp | 4 +- src/VariableBase.h | 4 +- 15 files changed, 43 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index a9f0a7a1b..6206aefa8 100644 --- a/README.md +++ b/README.md @@ -71,7 +71,7 @@ Within this library, a sensor, a variable, and a logger mean very specific thing **Sensor** - A sensor is some sort of device that is capable of taking one or more measurements using some sort of method. Most often we can think of these as probes or other instruments that can give back information about the world around them. Sensors can usually be given power or have that power cut. They may be awoken or activated and then returned to a sleeping/low power use state. The may be able to be asked to begin a single reading. They _**must**_ be capable of returning the value of their readings to a logger of some type. -**Variable** - A variable is a single measurement value taken by a sensor. It is characterized by a name (what it is a measurement of), a unit of measurement, and a resolution. The [names](http://vocabulary.odm2.org/variablename/) and [units](http://vocabulary.odm2.org/units/) of measurements for all variables come from the controlled vocabularies developed for the ODM2 data system. (http://vocabulary.odm2.org/) The resolution is determined by the method used to take the measurement by the sensor. A variable may also be assigned a universally unique identifier (UUID) and a unique variable code. Many sensors are capable of measuring multiple variables at a single time. For example, a Decagon CTD-10 is a _sensor_. It is able to measure 3 _variables_: specific conductance, temperature, and water depth. The variable named "specificConductance" has _units_ of microsiemens per centimeter (µS/cm) and a _resolution_ of 1 µS/cm. Each variable is explicitly tied to the "parent" sensor that "notifies" the variable when a new value has been measured. +**Variable** - A variable is a result value taken by a sensor _or_ calculated from the results of one or more sensors. It is characterized by a name (what it is a measurement of), a unit of measurement, and a resolution. The [names](http://vocabulary.odm2.org/variablename/) and [units](http://vocabulary.odm2.org/units/) of measurements for all variables come from the controlled vocabularies developed for the ODM2 data system. (http://vocabulary.odm2.org/) The resolution is determined by the method used to take the measurement by the sensor. A variable may also be assigned a universally unique identifier (UUID) and a unique variable code. Many sensors are capable of measuring multiple variables at a single time. For example, a Decagon CTD-10 is a _sensor_. It is able to measure 3 _variables_: specific conductance, temperature, and water depth. The variable named "specificConductance" has _units_ of microsiemens per centimeter (µS/cm) and a _resolution_ of 1 µS/cm. Each measured variable is explicitly tied to the "parent" sensor that "notifies" the variable when a new value has been measured. Each calculated variable has a parent function returning a float which is the value for that variable. **Logger** - A logger is a device that can control all functions of the sensors that are attached to it and save the values of all variables measured by those sensors to an attached SD card. In this library, all loggers are Arduino-style small processor circuit boards. @@ -161,16 +161,20 @@ These functions are also available for each sensor, but should be used with caut - **waitForMeasurementCompletion()** - Delays until time is passed for measurement completion. ### Functions for Each Variable -- **Constructor** - Every variable requires a pointer to its parent sensor as part of the constructor. Every variable also has two optional string entries, for a universally unique identifier (UUID or GUID) and a custom variable code. _The UUID must always be listed first!_ In cases where you would like a custom variable code, but do not have a UUID, you **must** enter '""' as your UUID. -- **getVarName()** - This returns the variable's name ,using http://vocabulary.odm2.org/variablename/, as a String. +- **Constructor** - There are two forms of the constructor, one for measured variables (ie, ones whose values come directly from a senor) and another for calculated variables (ie, ones whose values are calculated from other vales). + - For _measured_ variables, the base variable constructor should not be used, but instead the constructor for the specific type of variable tied to a sensor should be used. (That is, use the constructor for the MaxBotixSonar_Range variable sub-object, not the raw variable constructor.) The sensor-measured variable constructors require a pointer to its parent sensor as the first argument of the constructor. There are also two optional string entries, for a universally unique identifier (UUID or GUID) and a custom variable code. _The UUID must always be listed first!_ In cases where you would like a custom variable code, but do not have a UUID, you **must** enter '""' as your UUID. + - For _calculated_ variables, you use the base variable object constructor. The constructor requires a function which returns a float as its first argument, followed by Strings from the variable's name and unit. Both of these strings should be values from the [ODM2 controlled vocabularies](http://vocabulary.odm2.org/). Next an integer variable resolution is required. Then two Strings for the variable UUID and variable code. _All arguments are required in the calculated variable constructor!_ +- **getVarName()** - This returns the variable's name, using http://vocabulary.odm2.org/variablename/, as a String. - **getVarUnit()** - This returns the variable's unit, using http://vocabulary.odm2.org/units/, as a String. - **getVarCode()** - This returns a String with a customized code for the variable, if one is given, and a default if not - **getVarUUID()** - This returns the universally unique identifier of a variables, if one is assigned, as a String - **setup()** - This "sets up" the variable - attaching it to its parent sensor. This must always be called for each sensor within the "setup" loop of your Arduino program _after_ calling the sensor setup. -- **getValue(bool updateValue)** - This returns the current value of the variable as a float. By default, it does not ask the parent sensor for a new value, but simply returns the last value a parent sensor notified it of, no matter the age of the value. If you would like to ask the sensor to measure a new value and for that new value to be returned, set the boolean flag as true. +- **getValue(bool updateValue)** - This returns the current value of the variable as a float. By default, it does not ask the parent sensor for a new value, but simply returns the last value a parent sensor notified it of, no matter the age of the value. If you would like to ask the sensor to measure a new value and for that new value to be returned, set the boolean flag as true. Calculated variables will never ask any sensors for updates. - **getValueString(bool updateValue)** - This is identical to getValue, except that it returns a string with the proper precision available from the sensor. -- **attachSensor(int varNum, Sensor \*parentSense)** - The compliment to a sensor's registerVariable() function. This attaches a variable object to the sensor that is giving the value to the variable. The variable is generally responsible for calling this function! -- **onSensorUpdate()** - This is the variable's response to the sensor's notifyVariables() function. It accepts the new value from the sensor. This is generally called by the sensor. +- **attachSensor(int varNum, Sensor \*parentSense)** - The compliment to a sensor's registerVariable() function. This attaches a variable object to the sensor that is giving the value to the variable. The variable is generally responsible for calling this function! This should never be called for a calculated variable. +- **onSensorUpdate()** - This is the variable's response to the sensor's notifyVariables() function. It accepts the new value from the sensor. This is generally called by the sensor. This should never be called for a calculated variable. +- - **getParentSensorName()** - This is a helper - it returns the name of the parent sensor, if applicable +- - **getParentSensorLocation()** - This is a helper - it returns the "location" of the parent sensor, if applicable ### Examples Using Individual Sensor and Variable Functions To access and get values from a sensor, you must create an instance of the sensor class you are interested in using its constructor. Each variable has different parameters that you must specify; these are described below within the section for each sensor. You must then create a new instance for each _variable_, and reference a pointer to the parent sensor in the constructor. Many variables can (and should) call the same parent sensor. The variables are specific to the individual sensor because each sensor collects data and returns data in a unique way. The constructors are all best called outside of the "setup()" or "loop()" functions. The setup functions are then called (sensor, then variables) in the main "setup()" function and the update() and getValues() are called in the loop(). A very simple program to get data from a Decagon CTD might be something like: @@ -211,13 +215,13 @@ loop() } ``` -The "[single_sensor](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/single_sensor)" example in the examples folder shows the same functionality for a MaxBotix Ultrasonic Range Finder. +The "[single_sensor](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/single_sensor)" example in the examples folder shows the same functionality for a MaxBotix Ultrasonic Range Finder. This example also includes using a calculated variable to output a water depth calculated from the sonar range. ## Grouped Sensor Functions Having a unified set of functions to access many sensors allows us to quickly poll through a list of sensors to get all results quickly. To this end, "VariableArray.h" adds the class "VariableArray" with functions to use on an array of pointers to variable objects. ### Functions Available for a VariableArray Object: -- **init(int variableCount, Variable variableList[])** - This initializes the variable array. This must be called in the setup() function. Note that the objects in the variable list must be pointers, not the variable objects themselves. +- **init(int variableCount, Variable variableList[])** - This initializes the variable array. This must be called in the setup() function. Note that the objects in the variable list must be pointers, not the variable objects themselves. The pointers may be to calculated or measured variable objects. - **getVariableCount()** - Simply returns the number of variables. - **getSensorCount()** - Returns the number of independent sensors. This will often be different from the number of variables because many sensors can return multiple variables. - **setupSensors()** - This sets up all of the variables in the array and their respective sensors by running all of their setup() functions. If a sensor doesn't respond to its setup command, the command is called 5 times in attempt to make a connection. If all sensors are set up successfully, returns true. @@ -231,18 +235,7 @@ Having a unified set of functions to access many sensors allows us to quickly po ### VariableArray Examples: -To use the VariableArray module, you must first create the array of pointers. This should be done outside of the setup() or loop() functions. Remember that you must create a new instance for each variable and each sensor. The sensor functions for sensors within a variable array take advantage of all of the timestamps and status bits within the sensor object to minimize the amount of time that all sensors are powered and the processor is awake. That is, the first sensor to be warmed up will be set up or activated first; the first sensor to stabilize will be asked for values first. The order of the variables within the array should not matter, though for code readability, I strongly suggest putting all the variables attached to a single sensor next to each other in the array. - -Following the example from above, with a Decagon CTD, you would create an array with the three CTD variables like this: - -```cpp -// Create a new VariableArray object -VariableArray myVars; -// Create the array of variables named "variableList" using the pre-created variable objects -Variable \*variableList[] = {\*cond, \*temp, \*depth}; -// Optionally, count the number of variables in the array (in this case, it's 3) -int variableCount = sizeof(variableList) / sizeof(variableList[0]); -``` +To use the VariableArray module, you must first create the array of pointers. This should be done outside of the setup() or loop() functions. Remember that you must create a new instance for each variable and each sensor. The sensor functions for sensors within a variable array take advantage of all of the timestamps and status bits within the sensor object to minimize the amount of time that all sensors are powered and the processor is awake. That is, the first sensor to be warmed up will be set up or activated first; the first sensor to stabilize will be asked for values first. All calculations for any calculated variables happen after all the sensor updating has finished. The order of the variables within the array should not matter, though for code readability, I strongly suggest putting all the variables attached to a single sensor next to each other in the array. The asterisk must be put in front of the variable name to indicate that it is a pointer to your variable object. With many variables, it is easier to create the object and the pointer to it all at once in the variable array. This can be done using the "new" keyword like so: @@ -265,20 +258,33 @@ int variableCount = sizeof(variableList) / sizeof(variableList[0]); You can also create and name variable pointer objects outside of the array and then reference those pointers inside of the array like so: ```cpp -// Create variable object and return pointers to them +// Create measured variable objects and return pointers to them Variable *var1 = new sensor1_var1(&parentSensor1, "UUID", "customVarCode1"); Variable *var2 = new sensor1_var2(&parentSensor1, "UUID", "customVarCode1"); Variable *var3 = new sensor2_var1(&parentSensor2, "UUID", "customVarCode1"); +// Create a calculated measured variable object and return a pointer to it +float calculationFunction(void) +{ + return var1->getValue() + 10; +} +Variable *calcVar4 = new Variable(calculationFunction, "varName", + "varUnit", varResolution, + "UUID", "varCode"); + +// Continue creating variables.. Variable *varX = new sensorX_varX(&parentSensor2, "UUID", "customVarCode1"); + // Create a new VariableArray object VariableArray myVars; + // Create new variable objects in an array named "variableList" using the "new" keyword // UUID's and customVarCodes are optional Variable \*variableList[] = { var1, var2, var3, + var4, ... varX }; diff --git a/examples/DRWI_CitSci/platformio.ini b/examples/DRWI_CitSci/platformio.ini index ed8b1d7e4..f528942b2 100644 --- a/examples/DRWI_CitSci/platformio.ini +++ b/examples/DRWI_CitSci/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/DRWI_NoCellular/platformio.ini b/examples/DRWI_NoCellular/platformio.ini index 49f8ba285..374af4969 100644 --- a/examples/DRWI_NoCellular/platformio.ini +++ b/examples/DRWI_NoCellular/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/baro_rho_correction/platformio.ini b/examples/baro_rho_correction/platformio.ini index 098134fd0..58b6891b3 100644 --- a/examples/baro_rho_correction/platformio.ini +++ b/examples/baro_rho_correction/platformio.ini @@ -19,6 +19,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/data_saving/platformio.ini b/examples/data_saving/platformio.ini index 07ba525c6..8ad78cbd0 100644 --- a/examples/data_saving/platformio.ini +++ b/examples/data_saving/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/double_logger/platformio.ini b/examples/double_logger/platformio.ini index 85e4a7ff0..9929cfa77 100644 --- a/examples/double_logger/platformio.ini +++ b/examples/double_logger/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/logging_to_EnviroDIY/platformio.ini b/examples/logging_to_EnviroDIY/platformio.ini index f8def144a..1bfa827cb 100644 --- a/examples/logging_to_EnviroDIY/platformio.ini +++ b/examples/logging_to_EnviroDIY/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/logging_to_EnviroDIY_Zero/platformio.ini b/examples/logging_to_EnviroDIY_Zero/platformio.ini index 3e5ea3686..053f2da7d 100644 --- a/examples/logging_to_EnviroDIY_Zero/platformio.ini +++ b/examples/logging_to_EnviroDIY_Zero/platformio.ini @@ -18,5 +18,5 @@ framework = arduino lib_ldf_mode = deep lib_ignore = SoftwareSerial_ExtInts, AltSoftSerial lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 RTCZero diff --git a/examples/multisensor_print/platformio.ini b/examples/multisensor_print/platformio.ini index c016437ce..b693096c1 100644 --- a/examples/multisensor_print/platformio.ini +++ b/examples/multisensor_print/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/simple_logging/platformio.ini b/examples/simple_logging/platformio.ini index 1b7832563..8950ccf2d 100644 --- a/examples/simple_logging/platformio.ini +++ b/examples/simple_logging/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/single_sensor/platformio.ini b/examples/single_sensor/platformio.ini index 4be9a7f9b..c12f50055 100644 --- a/examples/single_sensor/platformio.ini +++ b/examples/single_sensor/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.11.6 + EnviroDIY_ModularSensors@>=0.12.0 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/library.json b/library.json index a03573ea2..97d66f9af 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "EnviroDIY_ModularSensors", - "version": "0.11.7", + "version": "0.12.0", "description": "A library that allows access to multiple sensors through a unified interface. This allows the user to simply access many sensors to log the data or send the data to data repositories like the EnviroDIY data portal.", "keywords": "modular, sensor, sensors, datalogger, logger, low power, sleeping, EnviroDIY, ModularSensors, Mayfly, WikiWatershed", "platforms": "atmelavr, atmelsam", diff --git a/library.properties b/library.properties index a0ed99256..01058c1d8 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=EnviroDIY_ModularSensors -version=0.11.7 +version=0.12.0 author=Sara Damiano , Shannon Hicks maintainer=Sara Damiano sentence=A library that allows access to multiple sensors through a unified interface. diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 582b26d8f..2cb99d49a 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -14,7 +14,7 @@ // The class and functions for interfacing with a specific variable. // ============================================================================ -// The constructor for a measured variable - that is, one whos values are +// The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable::Variable(Sensor *parentSense, int varNum, String varName, String varUnit, @@ -38,7 +38,7 @@ Variable::Variable(Sensor *parentSense, int varNum, _currentValue = -9999; } -// The constructor for a calculated variable - that is, one whos value is +// The constructor for a calculated variable - that is, one whose value is // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable::Variable(float (*calcFxn)(), diff --git a/src/VariableBase.h b/src/VariableBase.h index 582185fd2..35934bfa6 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -20,7 +20,7 @@ class Sensor; // Forward declaration class Variable { public: - // The constructor for a measured variable - that is, one whos values are + // The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable(Sensor *parentSense, int varNum, String varName = "Unknown", String varUnit = "Unknown", @@ -28,7 +28,7 @@ class Variable String defaultVarCode = "Unknown", String UUID = "", String customVarCode = ""); - // The constructor for a measured variable - that is, one whos value is + // The constructor for a measured variable - that is, one whose value is // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable(float (*calcFxn)(), From 0f45d0e76cd122ad5650dbb88e153a84fb0f3e35 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 15:26:47 -0400 Subject: [PATCH 15/54] Made sure calculations will return -9999 if inputs are -9999 This will always be dependent on the user implementing the -9999 return in their calculation function. --- examples/baro_rho_correction/baro_rho_correction.ino | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index 22508fdcf..82f017baa 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -187,7 +187,11 @@ Variable *msPress = new MeaSpecMS5803_Pressure(&ms5803, "12345678-abcd-1234-efgh // 1 pascal = 0.01 mbar float calculateWaterPressure(void) { - float waterPressure = msPress->getValue() - (bPress->getValue())*0.01; + float totalPressureFromMS5803 = msPress->getValue(); + float baroPressureFromBME280 = bPress->getValue(); + float waterPressure = totalPressureFromMS5803 - (baroPressureFromBME280)*0.01; + if (totalPressureFromMS5803 = -9999 || baroPressureFromBME280 == -9999) + waterPressure = -9999; // Serial.print(F("Water pressure is ")); // for debugging // Serial.println(waterPressure); // for debugging return waterPressure; @@ -209,6 +213,7 @@ Variable *calcWaterPress = new Variable(calculateWaterPressure, waterPresureVarN float calculateWaterDepthRaw(void) { float waterDepth = calculateWaterPressure()*10.1972; + if (calculateWaterPressure() == -9999) waterDepth = -9999; // Serial.print(F("'Raw' water depth is ")); // for debugging // Serial.println(waterDepth); // for debugging return waterDepth; @@ -243,6 +248,8 @@ float calculateWaterDepthTempCorrected(void) // This calculation gives a final result in mm of water // from P = rho * g * h float rhoDepth = 1000 * waterPressurePa/(waterDensity * gravitationalConstant); + if (calculateWaterPressure() == -9999 || waterTempertureC == -9999) + rhoDepth = -9999; // Serial.print(F("Temperature corrected water depth is ")); // for debugging // Serial.println(rhoDepth); // for debugging return rhoDepth; From 5d6112a351ae085677b4fc43d6a3aa1458531699 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 15:27:48 -0400 Subject: [PATCH 16/54] Added sanity check to MS5803 --- src/MeaSpecMS5803.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/MeaSpecMS5803.cpp b/src/MeaSpecMS5803.cpp index 656a544b5..af17f46cf 100644 --- a/src/MeaSpecMS5803.cpp +++ b/src/MeaSpecMS5803.cpp @@ -79,6 +79,11 @@ bool MeaSpecMS5803::addSingleMeasurementResult(void) if (isnan(temp)) temp = -9999; if (isnan(press)) press = -9999; + if (temp < -50 || temp > 95) // Range is -40°C to +85°C + { + temp = -9999; + press = -9999; + } MS_DBG(F("Temperature: "), temp); MS_DBG(F("Pressure: "), press); From e2465d0ac39c180642532baaf21b2613a075c50b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Tue, 22 May 2018 15:41:36 -0400 Subject: [PATCH 17/54] Moved variable array init to constructor Not sure why I thought this could not be done. --- src/VariableArray.cpp | 7 +++---- src/VariableArray.h | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index 8ea78375a..e42f74194 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -10,17 +10,16 @@ #include "VariableArray.h" -// Initialization - cannot do this in constructor arduino has issues creating -// instances of classes with non-empty constructors -void VariableArray::init(int variableCount, Variable *variableList[]) +// Constructor +VariableArray::VariableArray(int variableCount, Variable *variableList[]) { - MS_DBG(F("Initializing variable array with "), variableCount, F(" variables...\n")); _variableCount = variableCount; _variableList = variableList; _maxSamplestoAverage = countMaxToAverage(); _sensorCount = getSensorCount(); + MS_DBG(F("Initializing variable array with "), variableCount, F(" variables...\n")); MS_DBG(F(" ... Success!\n")); } diff --git a/src/VariableArray.h b/src/VariableArray.h index 78d3fe666..a68218eff 100644 --- a/src/VariableArray.h +++ b/src/VariableArray.h @@ -24,7 +24,7 @@ class VariableArray public: // Initialization - cannot do this in constructor arduino has issues creating // instances of classes with non-empty constructors - virtual void init(int variableCount, Variable *variableList[]); + VariableArray(int variableCount, Variable *variableList[]); // Functions to return information about the list From 27e3cb531162ed6971a41f3c38f5920d356089e9 Mon Sep 17 00:00:00 2001 From: Anthony Aufdenkampe Date: Tue, 22 May 2018 16:06:56 -0500 Subject: [PATCH 18/54] BME280 stabilization time update based on results from bme280timeTest.ino. See https://docs.google.com/spreadsheets/d/1nh95sV7RreeaHTInxipFUqsnYnVjkwiUVIucD7rIk4E/edit#gid=1494267475 --- .../bme280timingTest/bme280timingTest.ino | 90 +++++++++++++++++++ src/BoschBME280.h | 4 +- 2 files changed, 92 insertions(+), 2 deletions(-) create mode 100644 sensor_tests/bme280timingTest/bme280timingTest.ino diff --git a/sensor_tests/bme280timingTest/bme280timingTest.ino b/sensor_tests/bme280timingTest/bme280timingTest.ino new file mode 100644 index 000000000..120f9485b --- /dev/null +++ b/sensor_tests/bme280timingTest/bme280timingTest.ino @@ -0,0 +1,90 @@ +/*************************************************************************** + This is a library for the BME280 humidity, temperature & pressure sensor + + Designed specifically to work with the Adafruit BME280 Breakout + ----> http://www.adafruit.com/products/2650 + + These sensors use I2C or SPI to communicate, 2 or 4 pins are required + to interface. The device's I2C address is either 0x76 or 0x77. + + Adafruit invests time and resources providing this open source code, + please support Adafruit andopen-source hardware by purchasing products + from Adafruit! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include +#include +#include +#include + +// #define BME_SCK 13 +// #define BME_MISO 12 +// #define BME_MOSI 11 +// #define BME_CS 10 + +uint8_t BMEi2c_addr = 0x76; // The BME280 can be addressed either as 0x76 or 0x77 +const int8_t I2CPower = 22; // Pin to switch power on and off (-1 if unconnected) + + + +#define SEALEVELPRESSURE_HPA (1013.25) + +Adafruit_BME280 bme; // I2C +//Adafruit_BME280 bme(BME_CS); // hardware SPI +//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI + +unsigned long delayTime; + +void setup() { + Serial.begin(57600); + Serial.println(F("BME280 test")); + + // Turn on switched power + pinMode(I2CPower, OUTPUT); + digitalWrite(I2CPower, HIGH); + + bool status; + + // default settings + // (you can also pass in a Wire library object like &Wire2) + status = bme.begin(BMEi2c_addr); + if (!status) { + Serial.println("Could not find a valid BME280 sensor, check wiring!"); + while (1); + } + + Serial.println("-- Timing Test --"); + delayTime = 1100; + + Serial.println(); + + // Print table headers + Serial.println(" Time, Temp, Humid, Press, Alt"); + Serial.println(" ms, *C, %, Pa, m"); + +} + + +void loop() { + + for (int i=0; i <= 30; i++) + { + Serial.print(" "); + Serial.print(millis()); + Serial.print(", "); + Serial.print(bme.readTemperature()); + Serial.print(", "); + Serial.print(bme.readHumidity()); + Serial.print(", "); + Serial.print(bme.readPressure()); + Serial.print(", "); + Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA)); + Serial.println(); + delay(delayTime); + } + + delay(100000); +} diff --git a/src/BoschBME280.h b/src/BoschBME280.h index 949b1275e..0f19b14a9 100644 --- a/src/BoschBME280.h +++ b/src/BoschBME280.h @@ -45,8 +45,8 @@ #define BME280_NUM_VARIABLES 4 #define BME280_WARM_UP_TIME_MS 100 -#define BME280_STABILIZATION_TIME_MS 0 -#define BME280_MEASUREMENT_TIME_MS 1000 +#define BME280_STABILIZATION_TIME_MS 4000 // 0.5 s for good numbers, but optimal at 4 s based on tests using bme280timingTest.ino +#define BME280_MEASUREMENT_TIME_MS 1100 // 1.0 s according to datasheet, but slightly better stdev when 1.1 s #define BME280_TEMP_RESOLUTION 2 #define BME280_TEMP_VAR_NUM 0 From e7958c3bb5f9207c5d4ae8d8e619a8e82bb78e4d Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 10:20:10 -0400 Subject: [PATCH 19/54] Don't need so many print fxns in VariableArray --- src/VariableArray.cpp | 86 +++++++++++++++++++++++++++++++------------ src/VariableArray.h | 27 +++++++++++++- 2 files changed, 88 insertions(+), 25 deletions(-) diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index e42f74194..cb90ba64b 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -18,9 +18,20 @@ VariableArray::VariableArray(int variableCount, Variable *variableList[]) _maxSamplestoAverage = countMaxToAverage(); _sensorCount = getSensorCount(); +} - MS_DBG(F("Initializing variable array with "), variableCount, F(" variables...\n")); - MS_DBG(F(" ... Success!\n")); +// This counts and returns the number of calculated variables +int VariableArray::getCalculatedVariableCount(void) +{ + int numCalc = 0; + // Check for unique sensors + for (int i = 0; i < _variableCount; i++) + { + if (_variableList[i]->isCalculated) numCalc++; + } + MS_DBG(F("There are "), numCalc, + F(" calculated variables in the group.\n")); + return numCalc; } @@ -28,15 +39,12 @@ VariableArray::VariableArray(int variableCount, Variable *variableList[]) int VariableArray::getSensorCount(void) { int numSensors = 0; - int numCalc = 0; // Check for unique sensors for (int i = 0; i < _variableCount; i++) { if (isLastVarFromSensor(i)) numSensors++; - if (_variableList[i]->isCalculated) numCalc++; } - MS_DBG(F("There are "), numSensors, F(" unique sensors and "), numCalc, - F(" calculated variablesin the group.\n")); + MS_DBG(F("There are "), numSensors, F(" unique sensors in the group.\n")); return numSensors; } @@ -469,24 +477,56 @@ void VariableArray::printSensorData(Stream *stream) } -// This generates a comma separated list of sensor values WITHOUT TIME STAMP -// Calculated variable results will be included -String VariableArray::generateSensorDataCSV(void) -{ - String csvString = F(""); - - for (uint8_t i = 0; i < _variableCount; i++) - { - csvString += _variableList[i]->getValueString(); - if (i + 1 != _variableCount) - { - csvString += F(","); - } +// These generate some helpful comma-separated lists of variable information +// This is a PRE-PROCESSOR MACRO to speed up generating header rows +// Again, THIS IS NOT A FUNCTION, it is a pre-processor macro +#define makeVarListCSV(function) \ + { \ + String csvString = ""; \ + for (uint8_t i = 0; i < _variableCount; i++) \ + { \ + csvString += _variableList[i]->function; \ + if (i + 1 != _variableCount) \ + { \ + csvString += F(","); \ + } \ + } \ + return csvString; \ } - - return csvString; -} - +// This generates a comma separated list of sensor values WITHOUT TIME STAMP +String VariableArray::generateSensorDataCSV(void){makeVarListCSV(getValueString())}; +// This generates a comma separated list of parent sensor names +// String VariableArray::listParentSensorNames(void){makeVarListCSV(getParentSensorName())}; +// This generates a comma separated list of variable names +// String VariableArray::listVariableNames(void){makeVarListCSV(getVarName())}; +// This generates a comma separated list of variable units +// String VariableArray::listVariableUnits(void){makeVarListCSV(getVarUnit())}; +// This generates a comma separated list of variable codes +// String VariableArray::listVariableCodes(void){makeVarListCSV(getVarCode())}; +// This generates a comma separated list of variable UUID's +// String VariableArray::listVariableUUIDs(void){makeVarListCSV(getVarUUID())}; + + +// These generate some helpful comma-separated lists of variable information +// This is a PRE-PROCESSOR MACRO to speed up generating header rows +// Again, THIS IS NOT A FUNCTION, it is a pre-processor macro +// #define streamVarListCSV(function) \ +// { \ +// for (uint8_t i = 0; i < _variableCount; i++) \ +// { \ +// stream->print(_variableList[i]->function); \ +// if (i + 1 != _variableCount) \ +// { \ +// stream->print(','); \ +// } \ +// } \ +// } +// void VariableArray::streamSensorDataCSV(Stream *stream){streamVarListCSV(getValueString())}; +// void VariableArray::streamParentSensorNames(Stream *stream){streamVarListCSV(getParentSensorName())}; +// void VariableArray::streamVariableNames(Stream *stream){streamVarListCSV(getVarName())}; +// void VariableArray::streamVariableUnits(Stream *stream){streamVarListCSV(getVarUnit())}; +// void VariableArray::streamVariableCodes(Stream *stream){streamVarListCSV(getVarCode())}; +// void VariableArray::streamVariableUUIDs(Stream *stream){streamVarListCSV(getVarUUID())}; // Check for unique sensors bool VariableArray::isLastVarFromSensor(int arrayIndex) diff --git a/src/VariableArray.h b/src/VariableArray.h index a68218eff..a0e1ec3da 100644 --- a/src/VariableArray.h +++ b/src/VariableArray.h @@ -28,9 +28,12 @@ class VariableArray // Functions to return information about the list - // This just returns the number of variables + // This just returns the number of variables (as input in the constructor) int getVariableCount(void){return _variableCount;} + // This counts and returns the number of calculated variables + int getCalculatedVariableCount(void); + // This counts and returns the number of sensors int getSensorCount(void); @@ -56,18 +59,38 @@ class VariableArray // This function prints out the results for any connected sensors to a stream void printSensorData(Stream *stream = &Serial); + // These generate some helpful comma-separated lists of variable information // This generates a comma separated list of sensor values WITHOUT TIME STAMP String generateSensorDataCSV(void); + // This generates a comma separated list of parent sensor names + // String listParentSensorNames(void); + // This generates a comma separated list of variable names + // String listVariableNames(void); + // This generates a comma separated list of variable units + // String listVariableUnits(void); + // This generates a comma separated list of variable codes + // String listVariableCodes(void); + // This generates a comma separated list of variable UUID's + // String listVariableUUIDs(void); + // These are identical to the above, except they directly send the data to + // an arduino stream to avoid passing around long strings. + // void streamSensorDataCSV(Stream *stream); + // void streamParentSensorNames(Stream *stream); + // void streamVariableNames(Stream *stream); + // void streamVariableUnits(Stream *stream); + // void streamVariableCodes(Stream *stream); + // void streamVariableUUIDs(Stream *stream); protected: + Variable **_variableList; uint8_t _variableCount; uint8_t _sensorCount; - Variable **_variableList; uint8_t _maxSamplestoAverage; private: bool isLastVarFromSensor(int arrayIndex); uint8_t countMaxToAverage(void); + friend class Logger; }; #endif From 543c2dd50624e3211885576f00a4a385e040f143 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 14:14:01 -0400 Subject: [PATCH 20/54] Renamed internal array and made public --- src/VariableArray.cpp | 176 +++++++++++++++++++++--------------------- src/VariableArray.h | 5 +- 2 files changed, 91 insertions(+), 90 deletions(-) diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index cb90ba64b..986862104 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -14,7 +14,7 @@ VariableArray::VariableArray(int variableCount, Variable *variableList[]) { _variableCount = variableCount; - _variableList = variableList; + arrayOfVars = variableList; _maxSamplestoAverage = countMaxToAverage(); _sensorCount = getSensorCount(); @@ -27,7 +27,7 @@ int VariableArray::getCalculatedVariableCount(void) // Check for unique sensors for (int i = 0; i < _variableCount; i++) { - if (_variableList[i]->isCalculated) numCalc++; + if (arrayOfVars[i]->isCalculated) numCalc++; } MS_DBG(F("There are "), numCalc, F(" calculated variables in the group.\n")); @@ -72,11 +72,11 @@ bool VariableArray::setupSensors(void) { if (isLastVarFromSensor(i)) // Skip non-unique sensors { - if (bitRead(_variableList[i]->parentSensor->getStatus(), 1) == 1) // already set up + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 1) == 1) // already set up { - MS_DBG(F(" ... "), _variableList[i]->getParentSensorName()); + MS_DBG(F(" ... "), arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" was already set up!\n")); nSensorsSetup++; @@ -95,17 +95,17 @@ bool VariableArray::setupSensors(void) bool sensorSuccess = false; if (isLastVarFromSensor(i)) // Skip non-unique sensors { - if (bitRead(_variableList[i]->parentSensor->getStatus(), 1) == 0) // not yet set up + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 1) == 0) // not yet set up { - if (_variableList[i]->parentSensor->isWarmedUp()) // is warmed up + if (arrayOfVars[i]->parentSensor->isWarmedUp()) // is warmed up { MS_DBG(F(" ... Set up of ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" ...\n")); - sensorSuccess = _variableList[i]->parentSensor->setup(); // set it up + sensorSuccess = arrayOfVars[i]->parentSensor->setup(); // set it up success &= sensorSuccess; nSensorsSetup++; @@ -123,7 +123,7 @@ bool VariableArray::setupSensors(void) // Now attach all of the variables to their parents MS_DBG(F("Attaching variables to their parent sensors.\n")); for (int i = 0; i < _variableCount; i++){ - success &= _variableList[i]->setup(); + success &= arrayOfVars[i]->setup(); } if (success) @@ -144,12 +144,12 @@ void VariableArray::sensorsPowerUp(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... Powering up ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG('\n'); - _variableList[i]->parentSensor->powerUp(); + arrayOfVars[i]->parentSensor->powerUp(); } } } @@ -170,11 +170,11 @@ bool VariableArray::sensorsWake(void) { if (isLastVarFromSensor(i)) // Skip non-unique sensors { - if (bitRead(_variableList[i]->parentSensor->getStatus(), 3) == 1) // already awake + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 3) == 1) // already awake { - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" was already awake.\n")); nSensorsAwake++; } @@ -191,18 +191,18 @@ bool VariableArray::sensorsWake(void) { if (isLastVarFromSensor(i)) // Skip non-unique sensors { - if (bitRead(_variableList[i]->parentSensor->getStatus(), 3) == 0) // NOT yet awake + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 3) == 0) // NOT yet awake { - if (_variableList[i]->parentSensor->isWarmedUp()) // already warmed up + if (arrayOfVars[i]->parentSensor->isWarmedUp()) // already warmed up { MS_DBG(F(" ... Wake up of ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" ...\n")); // Make a single attempt to wake the sensor after it is warmed up - bool sensorSuccess = _variableList[i]->parentSensor->wake(); + bool sensorSuccess = arrayOfVars[i]->parentSensor->wake(); success &= sensorSuccess; // We increment up the number of sensors awake/active, even // if the wake up command failed! @@ -233,11 +233,11 @@ bool VariableArray::sensorsSleep(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); - bool sensorSuccess = _variableList[i]->parentSensor->sleep(); + bool sensorSuccess = arrayOfVars[i]->parentSensor->sleep(); success &= sensorSuccess; if (sensorSuccess) MS_DBG(F(" successfully put to sleep.\n")); @@ -260,12 +260,12 @@ void VariableArray::sensorsPowerDown(void) if (isLastVarFromSensor(i)) // Skip non-unique sensors { MS_DBG(F(" ... powering down ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG('\n'); - _variableList[i]->parentSensor->powerDown(); + arrayOfVars[i]->parentSensor->powerDown(); } } } @@ -287,7 +287,7 @@ bool VariableArray::updateAllSensors(void) { if (isLastVarFromSensor(i)) { - _variableList[i]->parentSensor->clearValues(); + arrayOfVars[i]->parentSensor->clearValues(); } } @@ -302,16 +302,16 @@ bool VariableArray::updateAllSensors(void) { if (isLastVarFromSensor(i)) // Skip non-unique sensors { - if (bitRead(_variableList[i]->parentSensor->getStatus(), 3) == 0) // NOT awake/activated + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 3) == 0) // NOT awake/activated { - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" isn't awake/active! No readings will be taken!\n")); // Set the number of readings already equal to whatever total // number requested to ensure the sensor is skipped in further loops. - nMeasurementsCompleted[i] = _variableList[i]->parentSensor->getNumberMeasurementsToAverage(); + nMeasurementsCompleted[i] = arrayOfVars[i]->parentSensor->getNumberMeasurementsToAverage(); // Bump up the finished count. nSensorsCompleted++; } @@ -326,25 +326,25 @@ bool VariableArray::updateAllSensors(void) // Leave this whole section commented out unless you want excessive // printouts (ie, thousands of lines) of the timing information!! // if (isLastVarFromSensor(i) and - // _variableList[i]->parentSensor->getNumberMeasurementsToAverage() > nMeasurementsCompleted[i]) + // arrayOfVars[i]->parentSensor->getNumberMeasurementsToAverage() > nMeasurementsCompleted[i]) // { - // _variableList[i]->parentSensor->updateStatusBits(true); + // arrayOfVars[i]->parentSensor->updateStatusBits(true); // MS_DBG(i); // MS_DBG(F(" - ")); - // MS_DBG(_variableList[i]->getParentSensorName()); + // MS_DBG(arrayOfVars[i]->getParentSensorName()); // MS_DBG(F(" at ")); - // MS_DBG(_variableList[i]->getParentSensorLocation()); + // MS_DBG(arrayOfVars[i]->getParentSensorLocation()); // MS_DBG(F(" - millis: ")); // MS_DBG(millis()); // MS_DBG(F(" - status: 0b")); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 7)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 6)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 5)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 4)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 3)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 2)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 1)); - // MS_DBG(bitRead(_variableList[i]->parentSensor->getStatus(), 0)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 7)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 6)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 5)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 4)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 3)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 2)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 1)); + // MS_DBG(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 0)); // MS_DBG(F(" - measurement #")); // MS_DBG(nMeasurementsCompleted[i] + 1); // MS_DBG('\n'); @@ -353,25 +353,25 @@ bool VariableArray::updateAllSensors(void) // Only do checks on sensors that still have readings to finish if (isLastVarFromSensor(i) and - _variableList[i]->parentSensor->getNumberMeasurementsToAverage() > nMeasurementsCompleted[i]) + arrayOfVars[i]->parentSensor->getNumberMeasurementsToAverage() > nMeasurementsCompleted[i]) { // first, make sure the sensor is stable - if ( _variableList[i]->parentSensor->isStable()) + if ( arrayOfVars[i]->parentSensor->isStable()) { // now, if the sensor is not currently measuring... - if (bitRead(_variableList[i]->parentSensor->getStatus(), 5) == 0) // NOT currently measuring + if (bitRead(arrayOfVars[i]->parentSensor->getStatus(), 5) == 0) // NOT currently measuring { // Start a reading MS_DBG(F("- Starting reading ")); MS_DBG(nMeasurementsCompleted[i]+1); MS_DBG(F(" on ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" -\n")); - bool sensorSuccess_start = _variableList[i]->parentSensor->startSingleMeasurement(); + bool sensorSuccess_start = arrayOfVars[i]->parentSensor->startSingleMeasurement(); success &= sensorSuccess_start; if (sensorSuccess_start) MS_DBG(F("- Success -\n")); @@ -380,18 +380,18 @@ bool VariableArray::updateAllSensors(void) // otherwise, it is currently measuring so... // if a measurement is finished, get the result and tick up the number of finished readings - if(_variableList[i]->parentSensor->isMeasurementComplete()) + if(arrayOfVars[i]->parentSensor->isMeasurementComplete()) { // Get the value MS_DBG(F("-- Collected result of reading ")); MS_DBG(nMeasurementsCompleted[i]+1); MS_DBG(F(" from ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" --\n")); - bool sensorSuccess_result = _variableList[i]->parentSensor->addSingleMeasurementResult(); + bool sensorSuccess_result = arrayOfVars[i]->parentSensor->addSingleMeasurementResult(); success &= sensorSuccess_result; nMeasurementsCompleted[i] += 1; // increment the number of measurements that sensor has completed @@ -402,12 +402,12 @@ bool VariableArray::updateAllSensors(void) } // if all the readings are done, mark the whole sensor as done - if (nMeasurementsCompleted[i] == _variableList[i]->parentSensor->getNumberMeasurementsToAverage()) + if (nMeasurementsCompleted[i] == arrayOfVars[i]->parentSensor->getNumberMeasurementsToAverage()) { MS_DBG(F("--- Finished all readings from ")); - MS_DBG(_variableList[i]->getParentSensorName()); + MS_DBG(arrayOfVars[i]->getParentSensorName()); MS_DBG(F(" at ")); - MS_DBG(_variableList[i]->getParentSensorLocation()); + MS_DBG(arrayOfVars[i]->getParentSensorLocation()); MS_DBG(F(" ---\n")); nSensorsCompleted++; @@ -423,12 +423,12 @@ bool VariableArray::updateAllSensors(void) if (isLastVarFromSensor(i)) { // MS_DBG(F("--- Averaging results from ")); - // MS_DBG(_variableList[i]->getParentSensorName()); - _variableList[i]->parentSensor->averageMeasurements(); + // MS_DBG(arrayOfVars[i]->getParentSensorName()); + arrayOfVars[i]->parentSensor->averageMeasurements(); // MS_DBG(F(" ---\n")); // MS_DBG(F("--- Notifying variables from ")); - // MS_DBG(_variableList[i]->getParentSensorName()); - _variableList[i]->parentSensor->notifyVariables(); + // MS_DBG(arrayOfVars[i]->getParentSensorName()); + arrayOfVars[i]->parentSensor->notifyVariables(); // MS_DBG(F(" ---\n")); } } @@ -442,35 +442,35 @@ void VariableArray::printSensorData(Stream *stream) { for (int i = 0; i < _variableCount; i++) { - if (_variableList[i]->isCalculated) + if (arrayOfVars[i]->isCalculated) { - stream->print(_variableList[i]->getVarName()); + stream->print(arrayOfVars[i]->getVarName()); stream->print(F(" is calculated to be ")); - stream->print(_variableList[i]->getValueString()); + stream->print(arrayOfVars[i]->getValueString()); stream->print(F(" ")); - stream->print(_variableList[i]->getVarUnit()); + stream->print(arrayOfVars[i]->getVarUnit()); stream->println(); } else { - stream->print(_variableList[i]->getParentSensorName()); + stream->print(arrayOfVars[i]->getParentSensorName()); stream->print(F(" at ")); - stream->print(_variableList[i]->getParentSensorLocation()); + stream->print(arrayOfVars[i]->getParentSensorLocation()); // stream->print(F(" with status 0b")); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 7)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 6)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 5)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 4)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 3)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 2)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 1)); - // stream->print(bitRead(_variableList[i]->parentSensor->getStatus(), 0)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 7)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 6)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 5)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 4)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 3)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 2)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 1)); + // stream->print(bitRead(arrayOfVars[i]->parentSensor->getStatus(), 0)); stream->print(F(" reports ")); - stream->print(_variableList[i]->getVarName()); + stream->print(arrayOfVars[i]->getVarName()); stream->print(F(" is ")); - stream->print(_variableList[i]->getValueString()); + stream->print(arrayOfVars[i]->getValueString()); stream->print(F(" ")); - stream->print(_variableList[i]->getVarUnit()); + stream->print(arrayOfVars[i]->getVarUnit()); stream->println(); } } @@ -485,7 +485,7 @@ void VariableArray::printSensorData(Stream *stream) String csvString = ""; \ for (uint8_t i = 0; i < _variableCount; i++) \ { \ - csvString += _variableList[i]->function; \ + csvString += arrayOfVars[i]->function; \ if (i + 1 != _variableCount) \ { \ csvString += F(","); \ @@ -514,7 +514,7 @@ String VariableArray::generateSensorDataCSV(void){makeVarListCSV(getValueString( // { \ // for (uint8_t i = 0; i < _variableCount; i++) \ // { \ -// stream->print(_variableList[i]->function); \ +// stream->print(arrayOfVars[i]->function); \ // if (i + 1 != _variableCount) \ // { \ // stream->print(','); \ @@ -531,12 +531,12 @@ String VariableArray::generateSensorDataCSV(void){makeVarListCSV(getValueString( // Check for unique sensors bool VariableArray::isLastVarFromSensor(int arrayIndex) { - // MS_DBG(F("Checking if "), _variableList[arrayIndex]->getVarName(), F(" ("), + // MS_DBG(F("Checking if "), arrayOfVars[arrayIndex]->getVarName(), F(" ("), // arrayIndex, F(") is the last variable from a sensor...")); // Calculated variables are never the last variable from a sensor, simply // because the don't come from a sensor at all. - if (_variableList[arrayIndex]->isCalculated) + if (arrayOfVars[arrayIndex]->isCalculated) { // MS_DBG(F(" ... Nope, it's calculated!\n")); return false; @@ -544,13 +544,13 @@ bool VariableArray::isLastVarFromSensor(int arrayIndex) else { - String sensName = _variableList[arrayIndex]->getParentSensorName(); - String sensLoc = _variableList[arrayIndex]->getParentSensorLocation(); + String sensName = arrayOfVars[arrayIndex]->getParentSensorName(); + String sensLoc = arrayOfVars[arrayIndex]->getParentSensorLocation(); bool unique = true; for (int j = arrayIndex + 1; j < _variableCount; j++) { - if (sensName == _variableList[j]->getParentSensorName() && - sensLoc == _variableList[j]->getParentSensorLocation()) + if (sensName == arrayOfVars[j]->getParentSensorName() && + sensLoc == arrayOfVars[j]->getParentSensorLocation()) { unique = false; // MS_DBG(F(" ... Nope, there are others after it!\n")); @@ -572,7 +572,7 @@ uint8_t VariableArray::countMaxToAverage(void) { if (isLastVarFromSensor(i)) // Skip non-unique sensors { - numReps = max(numReps, _variableList[i]->parentSensor->getNumberMeasurementsToAverage()); + numReps = max(numReps, arrayOfVars[i]->parentSensor->getNumberMeasurementsToAverage()); } } MS_DBG(F("The largest number of measurements to average will be "), numReps, F(".\n")); diff --git a/src/VariableArray.h b/src/VariableArray.h index a0e1ec3da..00f4c8712 100644 --- a/src/VariableArray.h +++ b/src/VariableArray.h @@ -26,6 +26,9 @@ class VariableArray // instances of classes with non-empty constructors VariableArray(int variableCount, Variable *variableList[]); + // Leave the internal variable list public + Variable **arrayOfVars; + // Functions to return information about the list // This just returns the number of variables (as input in the constructor) @@ -82,7 +85,6 @@ class VariableArray // void streamVariableUUIDs(Stream *stream); protected: - Variable **_variableList; uint8_t _variableCount; uint8_t _sensorCount; uint8_t _maxSamplestoAverage; @@ -90,7 +92,6 @@ class VariableArray private: bool isLastVarFromSensor(int arrayIndex); uint8_t countMaxToAverage(void); - friend class Logger; }; #endif From cf2732f811cbbee6a6b69609ce7c382f542439dc Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 14:17:18 -0400 Subject: [PATCH 21/54] A logger is NO LONGER a subclass of variable array but instead contains a variable array object as an internal member Also made the former init function into a constructor --- src/LoggerBase.cpp | 123 ++++++++++++++++++++++++++++++---------- src/LoggerBase.h | 40 +++++-------- src/LoggerDreamHost.cpp | 30 ++++++---- src/LoggerDreamHost.h | 6 ++ src/LoggerEnviroDIY.cpp | 77 +++++++++++++++---------- src/LoggerEnviroDIY.h | 8 ++- 6 files changed, 182 insertions(+), 102 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 856bb437d..cd7f16474 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -38,18 +38,11 @@ volatile bool Logger::startTesting = false; // Initialization - cannot do this in constructor arduino has issues creating // instances of classes with non-empty constructors -void Logger::init(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t variableCount, - Variable *variableList[], - uint8_t loggingIntervalMinutes, - const char *loggerID) +Logger::Logger(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray) { - // initialize the variable array - VariableArray::init(variableCount, variableList); - - PRINTOUT(F("Initializing logger "), loggerID, F(" to record at "), - loggingIntervalMinutes, F(" minute intervals ... ")); - _SDCardPin = SDCardPin; _mcuWakePin = mcuWakePin; _loggingIntervalMinutes = loggingIntervalMinutes; @@ -58,6 +51,7 @@ void Logger::init(int8_t SDCardPin, int8_t mcuWakePin, _autoFileName = false; _isFileNameSet = false; _numTimepointsLogged = 0; + _internalArray = inputArray; // Set sleep variable, if an interrupt pin is given if(_mcuWakePin != -1) @@ -69,8 +63,6 @@ void Logger::init(int8_t SDCardPin, int8_t mcuWakePin, isLoggingNow = false; isTestingNow = false; startTesting = false; - - PRINTOUT(F(" ... Success!\n")); }; @@ -84,7 +76,6 @@ void Logger::setTimeZone(int8_t timeZone) else if (_timeZone > 0) PRINTOUT(F("UTC+")); else PRINTOUT(F("UTC")); if (_timeZone != 0) PRINTOUT(_timeZone, F("\n")); - } @@ -526,6 +517,23 @@ void Logger::setFileName(void) setFileName(fileName); } +// This is a PRE-PROCESSOR MACRO to speed up generating header rows +// Again, THIS IS NOT A FUNCTION, it is a pre-processor macro +#define makeHeaderRowMacro(firstCol, function) \ + dataHeader += F("\""); \ + dataHeader += firstCol; \ + dataHeader += F("\","); \ + for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) \ + { \ + dataHeader += F("\""); \ + dataHeader += function; \ + dataHeader += F("\""); \ + if (i + 1 != _internalArray->getVariableCount()) \ + { \ + dataHeader += F(","); \ + } \ + } \ + dataHeader += F("\r\n"); // This creates a header for the logger file String Logger::generateFileHeader(void) @@ -537,20 +545,56 @@ String Logger::generateFileHeader(void) // Create the header rows String dataHeader = ""; // Next line will be the parent sensor names - makeHeaderRowMacro(logIDRowHeader, _variableList[i]->getParentSensorName()) + makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getParentSensorName()) // Next comes the ODM2 variable name - makeHeaderRowMacro(logIDRowHeader, _variableList[i]->getVarName()) + makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarName()) // Next comes the ODM2 unit name - makeHeaderRowMacro(logIDRowHeader, _variableList[i]->getVarUnit()) + makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUnit()) + // Next comes the variable UUIDs unit name + makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUUID()) // We'll finish up the the custom variable codes String dtRowHeader = F("Date and Time in UTC"); dtRowHeader += _timeZone; - makeHeaderRowMacro(dtRowHeader, _variableList[i]->getVarCode()) + makeHeaderRowMacro(dtRowHeader, _internalArray->arrayOfVars[i]->getVarCode()) // Return everything return dataHeader; } +// // This sends a file header out over an Arduino stream +// void Logger::streamFileHeader(Stream *stream) +// { +// // Very first column of the header is the logger ID +// String logIDRowHeader = F("Data Logger: "); +// logIDRowHeader += String(_loggerID); +// +// // First line will be the variable UUID's +// stream->print(logIDRowHeader); +// _internalArray->streamVariableUUIDs(stream); +// stream->println(); +// +// // Next line will be the parent sensor names +// stream->print(logIDRowHeader); +// _internalArray->streamParentSensorNames(stream); +// stream->println(); +// +// // Next comes the ODM2 variable name +// stream->print(logIDRowHeader); +// _internalArray->streamVariableNames(stream); +// stream->println(); +// +// // Next comes the ODM2 unit name +// stream->print(logIDRowHeader); +// _internalArray->streamVariableUnits(stream); +// stream->println(); +// +// // We'll finish up the the custom variable codes +// stream->print(F("Date and Time in UTC")); +// stream->print(_timeZone); +// stream->print(logIDRowHeader); +// _internalArray->streamVariableCodes(stream); +// stream->println(); +// } // This generates a comma separated list of volues of sensor data - including the time @@ -559,9 +603,19 @@ String Logger::generateSensorDataCSV(void) String csvString = ""; markedDateTime.addToString(csvString); csvString += F(","); - csvString += VariableArray::generateSensorDataCSV(); + csvString += _internalArray->generateSensorDataCSV(); return csvString; } +// // This sends a comma separated list of volues of sensor data - including the +// // time - out over an Arduino stream +// void Logger::streamSensorDataCSV(Stream *stream) +// { +// String csvString = ""; +// markedDateTime.addToString(csvString); +// csvString += F(","); +// stream->print(csvString); +// _internalArray->streamSensorDataCSV(stream); +// } // This checks if the SD card is available and ready @@ -734,32 +788,32 @@ void Logger::testingMode() delay(100); // This seems to prevent crashes, no clue why .... // Power up all of the sensors - sensorsPowerUp(); + _internalArray->sensorsPowerUp(); // Wake up all of the sensors - sensorsWake(); + _internalArray->sensorsWake(); // Update the sensors and print out data 25 times for (uint8_t i = 0; i < 25; i++) { PRINTOUT(F("------------------------------------------\n")); // Update the values from all attached sensors - updateAllSensors(); + _internalArray->updateAllSensors(); // Print out the current logger time PRINTOUT(F("Current logger time is ")); PRINTOUT(formatDateTime_ISO8601(getNowEpoch()), F("\n")); PRINTOUT(F(" -----------------------\n")); // Print out the sensor data #if defined(STANDARD_SERIAL_OUTPUT) - printSensorData(&STANDARD_SERIAL_OUTPUT); + _internalArray->printSensorData(&STANDARD_SERIAL_OUTPUT); #endif PRINTOUT(F(" -----------------------\n")); delay(5000); } // Put sensors to sleep - sensorsSleep(); - sensorsPowerDown(); + _internalArray->sensorsSleep(); + _internalArray->sensorsPowerDown(); // Unset testing mode flag Logger::isTestingNow = false; @@ -790,8 +844,15 @@ void Logger::testingMode() PRINTOUT(F("Current RTC time is: ")); PRINTOUT(formatDateTime_ISO8601(getNowEpoch()), F("\n")); + PRINTOUT(F("Setting up logger "), _loggerID, F(" to record at "), + _loggingIntervalMinutes, F(" minute intervals.\n")); + + PRINTOUT(F("This logger has a variable array with "), + _internalArray->getVariableCount(), F(" variables from "), + _internalArray->getSensorCount(), F(" sensors.\n")); + // Set up the sensors - setupSensors(); + _internalArray->setupSensors(); // Set the filename for the logger to save to, if it hasn't been done if(!_isFileNameSet){setFileName();} @@ -826,19 +887,19 @@ void Logger::log(void) // Send power to all of the sensors MS_DBG(F(" Powering sensors...\n")); - sensorsPowerUp(); + _internalArray->sensorsPowerUp(); // Wake up all of the sensors MS_DBG(F(" Waking sensors...\n")); - sensorsWake(); + _internalArray->sensorsWake(); // Update the values from all attached sensors MS_DBG(F(" Updating sensor values...\n")); - updateAllSensors(); + _internalArray->updateAllSensors(); // Put sensors to sleep MS_DBG(F(" Putting sensors back to sleep...\n")); - sensorsSleep(); + _internalArray->sensorsSleep(); // Cut sensor power MS_DBG(F(" Cutting sensor power...\n")); - sensorsPowerDown(); + _internalArray->sensorsPowerDown(); // Create a csv data record and save it to the log file logToSD(generateSensorDataCSV()); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index e1e0cdcfb..9d08c1630 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -36,16 +36,14 @@ #include // To communicate with the SD card // Defines the "Logger" Class -class Logger : public VariableArray +class Logger { public: - // Initialization - cannot do this in constructor arduino has issues creating - // instances of classes with non-empty constructors - void init(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t variableCount, - Variable *variableList[], - uint8_t loggingIntervalMinutes, - const char *loggerID = 0); + // Constructor + Logger(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray); // Sets the static timezone - this must be set static void setTimeZone(int8_t timeZone); @@ -134,29 +132,17 @@ class Logger : public VariableArray // This returns the current filename. Must be run after setFileName. String getFileName(void){return _fileName;} - // This is a PRE-PROCESSOR MACRO to speed up generating header rows - // Again, THIS IS NOT A FUNCTION, it is a pre-processor macro - #define makeHeaderRowMacro(firstCol, function) \ - dataHeader += F("\""); \ - dataHeader += firstCol; \ - dataHeader += F("\","); \ - for (uint8_t i = 0; i < _variableCount; i++) \ - { \ - dataHeader += F("\""); \ - dataHeader += function; \ - dataHeader += F("\""); \ - if (i + 1 != _variableCount) \ - { \ - dataHeader += F(","); \ - } \ - } \ - dataHeader += F("\r\n"); - // This creates a header for the logger file virtual String generateFileHeader(void); + // This prints a header onto a stream - this removes need to pass around + // very long string objects when not needed + // void streamFileHeader(Stream *stream); // This generates a comma separated list of volues of sensor data - including the time String generateSensorDataCSV(void); + // This sends a comma separated list of volues of sensor data - including the + // time - out over an Arduino stream + // void streamSensorDataCSV(Stream *stream); // This initializes a file on the SD card with the given filename and // writes the given header to it @@ -185,6 +171,7 @@ class Logger : public VariableArray // This defines what to do in the testing mode virtual void testingMode(); + // ===================================================================== // // Convience functions to call several of the above functions // ===================================================================== // @@ -237,6 +224,7 @@ class Logger : public VariableArray uint8_t _numTimepointsLogged; bool _sleep; int8_t _ledPin; + VariableArray *_internalArray; // This checks if the SD card is available and ready bool initializeSDCard(uint8_t Pin); diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 7560cb2a7..143177f98 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -14,6 +14,14 @@ // Functions for the SWRC Sensors DreamHost data receivers. // ============================================================================ +// Constructor +LoggerDreamHost::LoggerDreamHost(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray) + : LoggerEnviroDIY(SDCardPin, mcuWakePin, loggingIntervalMinutes, loggerID, inputArray) + {} + // Functions for private SWRC server void LoggerDreamHost::setDreamHostPortalRX(const char *URL) { @@ -31,12 +39,12 @@ String LoggerDreamHost::generateSensorDataDreamHost(void) dhString += F("&Loggertime="); dhString += String(Logger::markedEpochTime - 946684800); // Coorect time from epoch to y2k - for (int i = 0; i < Logger::_variableCount; i++) + for (int i = 0; i < _internalArray->getVariableCount(); i++) { dhString += F("&"); - dhString += Logger::_variableList[i]->getVarCode(); + dhString += _internalArray->arrayOfVars[i]->getVarCode(); dhString += F("="); - dhString += Logger::_variableList[i]->getValueString(); + dhString += _internalArray->arrayOfVars[i]->getValueString(); } return dhString; } @@ -76,10 +84,10 @@ void LoggerDreamHost::streamDreamHostRequest(Stream *stream) stream->print(String(F("?LoggerID=")) + String(Logger::_loggerID)); stream->print(String(F("?Loggertime=")) + String(Logger::markedEpochTime - 946684800)); // Correct time from epoch to y2k - for (int i = 0; i < Logger::_variableCount; i++) + for (int i = 0; i < _internalArray->getVariableCount(); i++) { - stream->print(String(F("&")) + String(Logger::_variableList[i]->getVarCode()) \ - + String(F("=")) + String(Logger::_variableList[i]->getValueString())); + stream->print(String(F("&")) + String(_internalArray->arrayOfVars[i]->getVarCode()) \ + + String(F("=")) + String(_internalArray->arrayOfVars[i]->getValueString())); } stream->print(String(F(" HTTP/1.1"))); @@ -188,19 +196,19 @@ void LoggerDreamHost::log(void) // Send power to all of the sensors MS_DBG(F(" Powering sensors...\n")); - sensorsPowerUp(); + _internalArray->sensorsPowerUp(); // Wake up all of the sensors MS_DBG(F(" Waking sensors...\n")); - sensorsWake(); + _internalArray->sensorsWake(); // Update the values from all attached sensors MS_DBG(F(" Updating sensor values...\n")); - updateAllSensors(); + _internalArray->updateAllSensors(); // Put sensors to sleep MS_DBG(F(" Putting sensors back to sleep...\n")); - sensorsSleep(); + _internalArray->sensorsSleep(); // Cut sensor power MS_DBG(F(" Cutting sensor power...\n")); - sensorsPowerDown(); + _internalArray->sensorsPowerDown(); if (_modemAttached) { diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index 2ad5321b5..6bea91448 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -26,6 +26,12 @@ class LoggerDreamHost : public LoggerEnviroDIY { public: + // Constructor + LoggerDreamHost(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray); + // Functions for private SWRC server void setDreamHostPortalRX(const char *URL); diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index ae7f701e2..d9a5eccfd 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -16,7 +16,11 @@ // ============================================================================ // Constructor -LoggerEnviroDIY::LoggerEnviroDIY() +LoggerEnviroDIY::LoggerEnviroDIY(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray) + : Logger(SDCardPin, mcuWakePin, loggingIntervalMinutes, loggerID, inputArray) { _modemAttached = false; } @@ -50,13 +54,10 @@ void LoggerEnviroDIY::setSamplingFeatureUUID(const char *samplingFeature) // This adds extra data to the datafile header String LoggerEnviroDIY::generateFileHeader(void) { - String dataHeader = ""; - - // Add additional UUID information - String SFHeaderString = F("Sampling Feature: "); - SFHeaderString += _samplingFeature; - makeHeaderRowMacro(SFHeaderString, _variableList[i]->getVarUUID()) - + // All we're doing is putting the Sampling Feature UUID at the top + String dataHeader = F("Sampling Feature: "); + dataHeader += _samplingFeature; + dataHeader += "\r\n"; // Put the basic header below dataHeader += Logger::generateFileHeader(); @@ -73,12 +74,12 @@ String LoggerEnviroDIY::generateSensorDataJSON(void) jsonString += F("\"timestamp\": \""); jsonString += String(Logger::markedISO8601Time) + F("\", "); - for (int i = 0; i < Logger::_variableCount; i++) + for (int i = 0; i < _internalArray->getVariableCount(); i++) { jsonString += F("\""); - jsonString += Logger::_variableList[i]->getVarUUID() + F("\": "); - jsonString += Logger::_variableList[i]->getValueString(); - if (i + 1 != Logger::_variableCount) + jsonString += _internalArray->arrayOfVars[i]->getVarUUID() + F("\": "); + jsonString += _internalArray->arrayOfVars[i]->getValueString(); + if (i + 1 != _internalArray->getVariableCount()) { jsonString += F(", "); } @@ -128,13 +129,13 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) jsonLength += 17; // ", "timestamp": " jsonLength += 25; // markedISO8601Time jsonLength += 3; // ",_ - for (int i = 0; i < Logger::_variableCount; i++) + for (int i = 0; i < _internalArray->getVariableCount(); i++) { jsonLength += 1; // " jsonLength += 36; // variable UUID jsonLength += 3; // ":_ - jsonLength += Logger::_variableList[i]->getValueString().length(); - if (i + 1 != Logger::_variableCount) + jsonLength += _internalArray->arrayOfVars[i]->getValueString().length(); + if (i + 1 != _internalArray->getVariableCount()) { jsonLength += 2; // ,_ } @@ -153,10 +154,10 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) stream->print(String(F("\", \"timestamp\": \""))); stream->print(String(Logger::markedISO8601Time) + F("\", ")); - for (int i = 0; i < Logger::_variableCount; i++) + for (int i = 0; i < _internalArray->getVariableCount(); i++) { - stream->print(String(F("\"")) + Logger::_variableList[i]->getVarUUID() + String(F("\": ")) + Logger::_variableList[i]->getValueString()); - if (i + 1 != Logger::_variableCount) + stream->print(String(F("\"")) + _internalArray->arrayOfVars[i]->getVarUUID() + String(F("\": ")) + _internalArray->arrayOfVars[i]->getValueString()); + if (i + 1 != _internalArray->getVariableCount()) { stream->print(F(", ")); } @@ -237,7 +238,7 @@ int LoggerEnviroDIY::postDataEnviroDIY(String enviroDIYjson) // ===================================================================== // -// Convience functions to call several of the above functions +// Public functions for a "sensor testing" mode // ===================================================================== // // This defines what to do in the testing mode @@ -262,24 +263,24 @@ void LoggerEnviroDIY::testingMode() } // Power up all of the sensors - sensorsPowerUp(); + _internalArray->sensorsPowerUp(); // Wake up all of the sensors - sensorsWake(); + _internalArray->sensorsWake(); // Update the sensors and print out data 25 times for (uint8_t i = 0; i < 25; i++) { PRINTOUT(F("------------------------------------------\n")); // Update the values from all attached sensors - updateAllSensors(); + _internalArray->updateAllSensors(); // Print out the current logger time PRINTOUT(F("Current logger time is ")); PRINTOUT(formatDateTime_ISO8601(getNowEpoch()), F("\n")); PRINTOUT(F(" -----------------------\n")); // Print out the sensor data #if defined(STANDARD_SERIAL_OUTPUT) - printSensorData(&STANDARD_SERIAL_OUTPUT); + _internalArray->printSensorData(&STANDARD_SERIAL_OUTPUT); #endif PRINTOUT(F(" -----------------------\n")); @@ -296,8 +297,8 @@ void LoggerEnviroDIY::testingMode() } // Put sensors to sleep - sensorsSleep(); - sensorsPowerDown(); + _internalArray->sensorsSleep(); + _internalArray->sensorsPowerDown(); if (_modemAttached) { @@ -315,6 +316,10 @@ void LoggerEnviroDIY::testingMode() } +// ===================================================================== // +// Convience functions to call several of the above functions +// ===================================================================== // + // This calls all of the setup functions - must be run AFTER init void LoggerEnviroDIY::begin(void) { @@ -332,14 +337,24 @@ void LoggerEnviroDIY::begin(void) PRINTOUT(F("Current RTC time is: ")); PRINTOUT(formatDateTime_ISO8601(getNowEpoch()), F("\n")); + PRINTOUT(F("Setting up logger "), _loggerID, F(" to record at "), + _loggingIntervalMinutes, F(" minute intervals.\n")); + + PRINTOUT(F("This logger has a variable array with "), + _internalArray->getVariableCount(), F(" variables from "), + _internalArray->getSensorCount(), F(" sensors.\n")); + if (_modemAttached) { + // Print out the modem info + PRINTOUT(F("This logger is also tied to a ")); + PRINTOUT(_logModem->getSensorName(), F(" for internet connectivity.\n")); // Turn on the modem to let it start searching for the network _logModem->modemPowerUp(); } // Set up the sensors - setupSensors(); + _internalArray->setupSensors(); if (_modemAttached) { @@ -395,19 +410,19 @@ void LoggerEnviroDIY::log(void) // Send power to all of the sensors MS_DBG(F(" Powering sensors...\n")); - sensorsPowerUp(); + _internalArray->sensorsPowerUp(); // Wake up all of the sensors MS_DBG(F(" Waking sensors...\n")); - sensorsWake(); + _internalArray->sensorsWake(); // Update the values from all attached sensors MS_DBG(F(" Updating sensor values...\n")); - updateAllSensors(); + _internalArray->updateAllSensors(); // Put sensors to sleep MS_DBG(F(" Putting sensors back to sleep...\n")); - sensorsSleep(); + _internalArray->sensorsSleep(); // Cut sensor power MS_DBG(F(" Cutting sensor power...\n")); - sensorsPowerDown(); + _internalArray->sensorsPowerDown(); if (_modemAttached) { diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index ed35a4c7c..b75db2b0a 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -25,9 +25,11 @@ class LoggerEnviroDIY : public Logger { public: - - // need a constructor to initially not have an modem attached - LoggerEnviroDIY(); + // Constructor + LoggerEnviroDIY(int8_t SDCardPin, int8_t mcuWakePin, + uint8_t loggingIntervalMinutes, + const char *loggerID, + VariableArray *inputArray); // Adds a loggerModem objct to the logger // loggerModem = TinyGSM modem + TinyGSM client + Modem On Off From a33ed4685b9e26f45fe0fd02867554fecfc9e407 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 15:02:13 -0400 Subject: [PATCH 22/54] Changed order of logger constructor --- src/LoggerBase.cpp | 5 ++--- src/LoggerBase.h | 5 ++--- src/LoggerDreamHost.cpp | 7 +++---- src/LoggerDreamHost.h | 5 ++--- src/LoggerEnviroDIY.cpp | 7 +++---- src/LoggerEnviroDIY.h | 5 ++--- 6 files changed, 14 insertions(+), 20 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index cd7f16474..427f3eb4d 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -38,9 +38,8 @@ volatile bool Logger::startTesting = false; // Initialization - cannot do this in constructor arduino has issues creating // instances of classes with non-empty constructors -Logger::Logger(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, +Logger::Logger(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) { _SDCardPin = SDCardPin; diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 9d08c1630..dc06915b5 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -40,9 +40,8 @@ class Logger { public: // Constructor - Logger(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, + Logger(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); // Sets the static timezone - this must be set diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 143177f98..d81da371e 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -15,11 +15,10 @@ // ============================================================================ // Constructor -LoggerDreamHost::LoggerDreamHost(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, +LoggerDreamHost::LoggerDreamHost(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) - : LoggerEnviroDIY(SDCardPin, mcuWakePin, loggingIntervalMinutes, loggerID, inputArray) + : LoggerEnviroDIY(loggerID, loggingIntervalMinutes, SDCardPin, mcuWakePin, inputArray) {} // Functions for private SWRC server diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index 6bea91448..ebece9f62 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -27,9 +27,8 @@ class LoggerDreamHost : public LoggerEnviroDIY public: // Constructor - LoggerDreamHost(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, + LoggerDreamHost(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); // Functions for private SWRC server diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index d9a5eccfd..39d4c85a9 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -16,11 +16,10 @@ // ============================================================================ // Constructor -LoggerEnviroDIY::LoggerEnviroDIY(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, +LoggerEnviroDIY::LoggerEnviroDIY(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) - : Logger(SDCardPin, mcuWakePin, loggingIntervalMinutes, loggerID, inputArray) + : Logger(loggerID, loggingIntervalMinutes, SDCardPin, mcuWakePin, inputArray) { _modemAttached = false; } diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index b75db2b0a..a3736e1f2 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -26,9 +26,8 @@ class LoggerEnviroDIY : public Logger { public: // Constructor - LoggerEnviroDIY(int8_t SDCardPin, int8_t mcuWakePin, - uint8_t loggingIntervalMinutes, - const char *loggerID, + LoggerEnviroDIY(const char *loggerID, uint8_t loggingIntervalMinutes, + int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); // Adds a loggerModem objct to the logger From 18eec37934a4baae1901a0355c632733e5733517 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 15:55:19 -0400 Subject: [PATCH 23/54] Updated examples --- examples/DRWI_CitSci/DRWI_CitSci.ino | 45 ++++++----- examples/DRWI_NoCellular/DRWI_NoCellular.ino | 62 +++++++++------ .../baro_rho_correction.ino | 44 +++++------ examples/data_saving/data_saving.ino | 65 +++++++++------- examples/double_logger/double_logger.ino | 77 ++++++++++--------- .../logging_to_EnviroDIY.ino | 62 ++++++++------- .../logging_to_EnviroDIY_Zero.ino | 44 +++++------ .../multisensor_print/multisensor_print.ino | 39 ++++++---- examples/simple_logging/simple_logging.ino | 56 +++++++++----- 9 files changed, 274 insertions(+), 220 deletions(-) diff --git a/examples/DRWI_CitSci/DRWI_CitSci.ino b/examples/DRWI_CitSci/DRWI_CitSci.ino index d9f3fffd2..e68d6923b 100644 --- a/examples/DRWI_CitSci/DRWI_CitSci.ino +++ b/examples/DRWI_CitSci/DRWI_CitSci.ino @@ -29,28 +29,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include // for external and pin change interrupts #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== + // The name of this file const char *sketchName = "DWRI_CitSci.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -LoggerDreamHost EnviroDIYLogger; - // ========================================================================== // Primary Arduino-Based Board and Processor // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -59,7 +48,7 @@ const int8_t wakePin = A7; // Interrupt/Alarm pin to wake from sleep // In a SAMD system where you are using the built-in rtc, set wakePin to 1 const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be defined!) -// Create the processor "sensor" +// Create and return the processor "sensor" const char *MFVersion = "v0.5b"; ProcessorStats mayfly(MFVersion) ; @@ -125,6 +114,8 @@ DecagonCTD ctd(*CTDSDI12address, SDI12Power, SDI12Data, CTDnumberReadings); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { new ProcessorStats_Batt(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS3231_Temp(&ds3231, "12345678-abcd-1234-efgh-1234567890ab"), @@ -136,7 +127,23 @@ Variable *variableList[] = { new Modem_RSSI(&modem, "12345678-abcd-1234-efgh-1234567890ab"), new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"), }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +LoggerDreamHost EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -195,18 +202,14 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - EnviroDIYLogger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); - EnviroDIYLogger.setAlertPin(greenLED); - // Setup the logger modem modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); - // Attach the modem to the logger + // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.setAlertPin(greenLED); - // Set up the connection with EnviroDIY + // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); diff --git a/examples/DRWI_NoCellular/DRWI_NoCellular.ino b/examples/DRWI_NoCellular/DRWI_NoCellular.ino index f3f5eb77b..a32dda038 100644 --- a/examples/DRWI_NoCellular/DRWI_NoCellular.ino +++ b/examples/DRWI_NoCellular/DRWI_NoCellular.ino @@ -21,28 +21,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include // for external and pin change interrupts #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== + // The name of this file const char *sketchName = "DRWI_NoCellular.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -Logger logger; - // ========================================================================== // Primary Arduino-Based Board and Processor // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -51,7 +40,7 @@ const int8_t wakePin = A7; // Interrupt/Alarm pin to wake from sleep // In a SAMD system where you are using the built-in rtc, set wakePin to 1 const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be defined!) -// Create the processor "sensor" +// Create and return the processor "sensor" const char *MFVersion = "v0.5b"; ProcessorStats mayfly(MFVersion) ; @@ -102,16 +91,41 @@ DecagonCTD ctd(*CTDSDI12address, SDI12Power, SDI12Data, CTDnumberReadings); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { - new ProcessorStats_Batt(&mayfly), - new MaximDS3231_Temp(&ds3231), - new DecagonCTD_Cond(&ctd), - new DecagonCTD_Temp(&ctd), - new DecagonCTD_Depth(&ctd), - new CampbellOBS3_Turbidity(&osb3low, "", "TurbLow"), - new CampbellOBS3_Turbidity(&osb3high, "", "TurbHigh"), + new ProcessorStats_Batt(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"), + new MaximDS3231_Temp(&ds3231, "12345678-abcd-1234-efgh-1234567890ab"), + new DecagonCTD_Cond(&ctd, "12345678-abcd-1234-efgh-1234567890ab"), + new DecagonCTD_Temp(&ctd, "12345678-abcd-1234-efgh-1234567890ab"), + new DecagonCTD_Depth(&ctd, "12345678-abcd-1234-efgh-1234567890ab"), + new CampbellOBS3_Turbidity(&osb3low, "12345678-abcd-1234-efgh-1234567890ab", "TurbLow"), + new CampbellOBS3_Turbidity(&osb3high, "12345678-abcd-1234-efgh-1234567890ab", "TurbHigh") }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +Logger logger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); + +// ========================================================================== +// Device registration and sampling feature information +// This should be obtained after registration at http://data.envirodiy.org +// ========================================================================== +const char *registrationToken = "12345678-abcd-1234-efgh-1234567890ab"; // Device registration token +const char *samplingFeature = "12345678-abcd-1234-efgh-1234567890ab"; // Sampling feature UUID // ========================================================================== @@ -159,9 +173,7 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - logger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); + // Set an alert pin logger.setAlertPin(greenLED); // Begin the logger @@ -181,7 +193,7 @@ void setup() greenredflash(6, 25); // Sleep - EnviroDIYLogger.systemSleep(); + logger.systemSleep(); } diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index 82f017baa..b482e2704 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -30,21 +30,9 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "baro_rho_correction.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 1; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -LoggerEnviroDIY EnviroDIYLogger; - // ========================================================================== // Primary Arduino-Based Board and Processor @@ -61,7 +49,7 @@ const int8_t wakePin = A7; // Interrupt/Alarm pin to wake from sleep const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be defined!) // Create and return the processor "sensor" -const char *MFVersion = "v0.5"; +const char *MFVersion = "v0.5b"; ProcessorStats mayfly(MFVersion) ; // Create the battery voltage and free RAM variable objects for the Y504 and return variable-type pointers to them Variable *mayflyBatt = new ProcessorStats_Batt(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"); @@ -269,6 +257,7 @@ Variable *calcCorrDepth = new Variable(calculateWaterDepthTempCorrected, rhoDept // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Put all of the variable pointers into an Array // NOTE: Since we've created all of the variable pointers above, we can just // reference them by name here. Variable *variableList[] = { @@ -288,7 +277,23 @@ Variable *variableList[] = { modemRSSI, modemSinalPct }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -347,11 +352,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - EnviroDIYLogger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); - EnviroDIYLogger.setAlertPin(greenLED); - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -362,18 +362,14 @@ void setup() modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); #endif - // Attach the modem to the logger + // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.setAlertPin(greenLED); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - // Set up the connection with DreamHost - #ifdef DreamHostPortalRX - EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); - #endif - // Begin the logger EnviroDIYLogger.begin(); diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index fbee6c18d..12d8c3bf8 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -30,24 +30,9 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "data_saving.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create TWO new logger instances -// one is a simple logger with all variables -// one is an enviroDIY logger with an abbreviated list of variables -LoggerEnviroDIY loggerComplete; -LoggerEnviroDIY loggerToGo; - // ========================================================================== // Primary Arduino-Based Board and Processor @@ -203,6 +188,10 @@ Variable *y520Temp = new YosemitechY520_Temp(&y520, "12345678-abcd-1234-efgh-123 // ========================================================================== // The array that contains all variables to be logged // ========================================================================== + +// Put all of the variable pointers into an Array +// NOTE: Since we've created all of the variable pointers above, we can just +// reference them by name here. Variable *variableList_complete[] = { mayflyBatt, mayflyRAM, @@ -219,12 +208,19 @@ Variable *variableList_complete[] = { modemRSSI, modemSinalPct }; +// Count up the number of pointers in the array int variableCount_complete = sizeof(variableList_complete) / sizeof(variableList_complete[0]); +// Create the VariableArray object +VariableArray arrayComplete(variableCount_complete, variableList_complete); // ========================================================================== // The array that contains all variables to have their values sent out over the internet // ========================================================================== + +// Put all of the variable pointers into an Array +// NOTE: Since we've created all of the variable pointers above, we can just +// reference them by name here. Variable *variableList_toGo[] = { y504DOmgL, y504Temp, @@ -233,7 +229,25 @@ Variable *variableList_toGo[] = { y520Cond, modemRSSI }; +// Count up the number of pointers in the array int variableCount_toGo = sizeof(variableList_toGo) / sizeof(variableList_toGo[0]); +// Create the VariableArray object +VariableArray arrayToGo(variableCount_toGo, variableList_toGo); + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create TWO new logger instances +// one is a simple logger with all variables +// one is an enviroDIY logger with an abbreviated list of variables +LoggerEnviroDIY loggerComplete(LoggerID, loggingInterval, sdCardPin, wakePin, &arrayComplete); +LoggerEnviroDIY loggerToGo(LoggerID, loggingInterval,sdCardPin, wakePin, &arrayToGo); // ========================================================================== @@ -295,14 +309,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the two logger instances - loggerComplete.init(sdCardPin, wakePin, variableCount_complete, variableList_complete, - loggingInterval, LoggerID); - loggerToGo.init(sdCardPin, wakePin, variableCount_toGo, variableList_toGo, - loggingInterval, LoggerID); - // There is no reason to call the setAlertPin() function, because we have to - // write the loop on our own. - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -319,6 +325,9 @@ void setup() loggerComplete.attachModem(&modem); loggerToGo.attachModem(&modem); + // There is no reason to call the setAlertPin() function, because we have to + // write the loop on our own. + // Set up the connection information with EnviroDIY for both loggers // Doing this for both loggers ensures that the header of the csv will have the tokens in it loggerComplete.setToken(registrationToken); @@ -378,19 +387,19 @@ void loop() // Send power to all of the sensors Serial.print(F("Powering sensors...\n")); - loggerComplete.sensorsPowerUp(); + arrayComplete.sensorsPowerUp(); // Wake up all of the sensors Serial.print(F("Waking sensors...\n")); - loggerComplete.sensorsWake(); + arrayComplete.sensorsWake(); // Update the values from all attached sensors Serial.print(F("Updating sensor values...\n")); - loggerComplete.updateAllSensors(); + arrayComplete.updateAllSensors(); // Put sensors to sleep Serial.print(F("Putting sensors back to sleep...\n")); - loggerComplete.sensorsSleep(); + arrayComplete.sensorsSleep(); // Cut sensor power Serial.print(F("Cutting sensor power...\n")); - loggerComplete.sensorsPowerDown(); + arrayComplete.sensorsPowerDown(); // End the stream for the modbus sensors // Because RS485 adapters tend to "steal" current from the data pins diff --git a/examples/double_logger/double_logger.ino b/examples/double_logger/double_logger.ino index 80ce3efb2..23fe34283 100644 --- a/examples/double_logger/double_logger.ino +++ b/examples/double_logger/double_logger.ino @@ -32,29 +32,16 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "logger_test.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -const char *FileName5min = "SL099_5MinuteInterval.csv"; -const char *FileName1min = "SL099_1MinuteInterval.csv"; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create TWO new logger instances -Logger logger1min; -Logger logger5min; - // ========================================================================== // Primary Arduino-Based Board and Processor // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -106,8 +93,10 @@ ModemSleepType ModemSleepMode = modem_sleep_held; // How the modem is put to sl // Use "modem_always_on" if you do not want the library to control the modem power and sleep or if none of the above apply. #endif -const char *wifiId = "XXXXXXX"; // The WiFi access point -const char *wifiPwd = "XXXXXXX"; // The password for connecting to WiFi +const char *apn = "xxxxx"; // The APN for the gprs connection, unnecessary for WiFi +const char *wifiId = "xxxxx"; // The WiFi access point, unnecessary for gprs +const char *wifiPwd = "xxxxx"; // The password for connecting to WiFi, unnecessary for gprs + // Create the loggerModem instance // A "loggerModem" is a combination of a TinyGSM Modem, a TinyGSM Client, and an on/off method loggerModem modem; @@ -133,20 +122,44 @@ AOSongAM2315 am2315(I2CPower); // ========================================================================== // The two arrays that contains the variables for the different intervals // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList_at1min[] = { new AOSongAM2315_Humidity(&am2315), new AOSongAM2315_Temp(&am2315) // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount1min = sizeof(variableList_at1min) / sizeof(variableList_at1min[0]); +// Create the VariableArray object +VariableArray array1min(variableCount1min, variableList_at1min); + +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList_at5min[] = { new MaximDS3231_Temp(&ds3231), new ProcessorStats_Batt(&mayfly), new ProcessorStats_FreeRam(&mayfly) // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount5min = sizeof(variableList_at5min) / sizeof(variableList_at5min[0]); +// Create the VariableArray object +VariableArray array5min(variableCount5min, variableList_at5min); +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID - since it's the same logger device, we only need one +const char *LoggerID = "XXXXX"; +// The TWO filenames for the different logging intervals +const char *FileName5min = "Logger_5MinuteInterval.csv"; +const char *FileName1min = "Logger_1MinuteInterval.csv"; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create TWO new logger instances with different logging intervals +Logger logger1min(LoggerID, 1, sdCardPin, wakePin, &array1min); +Logger logger5min(LoggerID, 5, sdCardPin, wakePin, &array5min); // ========================================================================== @@ -201,14 +214,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the two logger instances - logger1min.init(sdCardPin, wakePin, variableCount1min, variableList_at1min, - 1, LoggerID); - logger5min.init(sdCardPin, wakePin, variableCount5min, variableList_at5min, - 5, LoggerID); - // There is no reason to call the setAlertPin() function, because we have to - // write the loop on our own. - // Setup the logger modem modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -216,8 +221,8 @@ void setup() modem.modemPowerUp(); // Set up the sensors on both loggers - logger1min.setupSensors(); - logger5min.setupSensors(); + array1min.setupSensors(); + array5min.setupSensors(); // Print out the current time Serial.print(F("Current RTC time is: ")); @@ -277,19 +282,19 @@ void loop() // Send power to all of the sensors Serial.print(F("Powering sensors...\n")); - logger1min.sensorsPowerUp(); + array1min.sensorsPowerUp(); // Wake up all of the sensors Serial.print(F("Waking sensors...\n")); - logger1min.sensorsWake(); + array1min.sensorsWake(); // Update the values from all attached sensors Serial.print(F("Updating sensor values...\n")); - logger1min.updateAllSensors(); + array1min.updateAllSensors(); // Put sensors to sleep Serial.print(F("Putting sensors back to sleep...\n")); - logger1min.sensorsSleep(); + array1min.sensorsSleep(); // Cut sensor power Serial.print(F("Cutting sensor power...\n")); - logger1min.sensorsPowerDown(); + array1min.sensorsPowerDown(); // Create a csv data record and save it to the log file logger1min.logToSD(logger1min.generateSensorDataCSV()); @@ -310,19 +315,19 @@ void loop() // Send power to all of the sensors Serial.print(F("Powering sensors...\n")); - logger5min.sensorsPowerUp(); + array1min.sensorsPowerUp(); // Wake up all of the sensors Serial.print(F("Waking sensors...\n")); - logger5min.sensorsWake(); + array1min.sensorsWake(); // Update the values from all attached sensors Serial.print(F("Updating sensor values...\n")); - logger5min.updateAllSensors(); + array1min.updateAllSensors(); // Put sensors to sleep Serial.print(F("Putting sensors back to sleep...\n")); - logger5min.sensorsSleep(); + array1min.sensorsSleep(); // Cut sensor power Serial.print(F("Cutting sensor power...\n")); - logger5min.sensorsPowerDown(); + array1min.sensorsPowerDown(); // Create a csv data record and save it to the log file logger5min.logToSD(logger5min.generateSensorDataCSV()); diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index 6f50866c5..c84b9fc27 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -30,28 +30,16 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "logging_to_EnviroDIY.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -LoggerEnviroDIY EnviroDIYLogger; - // ========================================================================== // Primary Arduino-Based Board and Processor // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -85,7 +73,7 @@ const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or of ModemSleepType ModemSleepMode = modem_always_on; // How the modem is put to sleep #elif defined(TINY_GSM_MODEM_UBLOX) -const long ModemBaud = 9600; +const long ModemBaud = 9600; // SARA-U201 default seems to be 9600 const int8_t modemSleepRqPin = 23; // Modem SleepRq Pin (for sleep requests) (-1 if unconnected) const int8_t modemStatusPin = 19; // Modem Status Pin (indicates power status) (-1 if unconnected) const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or off (-1 if unconnected) @@ -248,10 +236,18 @@ ExternalVoltage extvolt(VoltPower, VoltData, VoltGain, Volt_ADS1115Address, Volt // Neither hardware serial nor AltSoftSerial require any modifications to // deal with interrupt conflicts. -#include // for the stream communication const int SonarData = 11; // data receive pin + +#include // for the stream communication SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// #include // for the stream communication +// NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// void NeoSWSISR() +// { +// NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +// } + #include const int8_t SonarPower = 22; // Excite (power) pin (-1 if unconnected) const int8_t Sonar1Trigger = A1; // Trigger pin (a negative number if unconnected) (A1 = 25) @@ -429,6 +425,8 @@ ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { new ApogeeSQ212_PAR(&SQ212, "12345678-abcd-1234-efgh-1234567890ab"), new AOSongAM2315_Humidity(&am2315, "12345678-abcd-1234-efgh-1234567890ab"), @@ -499,7 +497,23 @@ Variable *variableList[] = { new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"), // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -547,7 +561,10 @@ void setup() sonarSerial.begin(9600); // Allow interrupts for software serial #if defined SoftwareSerial_ExtInts_h - enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + #endif + #if defined NeoSWSerial_h + enableInterrupt(SonarData, NeoSWSISR, CHANGE); #endif // Set up pins for the LED's @@ -568,11 +585,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - EnviroDIYLogger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); - EnviroDIYLogger.setAlertPin(greenLED); - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -583,18 +595,14 @@ void setup() modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); #endif - // Attach the modem to the logger + // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.setAlertPin(greenLED); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - // Set up the connection with DreamHost - #ifdef DreamHostPortalRX - EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); - #endif - // Begin the logger EnviroDIYLogger.begin(); diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index eefd5964c..436c3e205 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -31,20 +31,9 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "logging_to_EnviroDIY_Zero.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -LoggerEnviroDIY EnviroDIYLogger; // ========================================================================== @@ -52,7 +41,7 @@ LoggerEnviroDIY EnviroDIYLogger; // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 13; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -441,6 +430,8 @@ ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { new ApogeeSQ212_PAR(&SQ212, "12345678-abcd-1234-efgh-1234567890ab"), new AOSongAM2315_Humidity(&am2315, "12345678-abcd-1234-efgh-1234567890ab"), @@ -511,7 +502,23 @@ Variable *variableList[] = { new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"), // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -582,11 +589,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - EnviroDIYLogger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); - EnviroDIYLogger.setAlertPin(greenLED); - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -597,18 +599,14 @@ void setup() modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); #endif - // Attach the modem to the logger + // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.setAlertPin(greenLED); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - // Set up the connection with DreamHost - #ifdef DreamHostPortalRX - EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); - #endif - // Begin the logger EnviroDIYLogger.begin(); diff --git a/examples/multisensor_print/multisensor_print.ino b/examples/multisensor_print/multisensor_print.ino index 24fb07b0a..afd1275c8 100644 --- a/examples/multisensor_print/multisensor_print.ino +++ b/examples/multisensor_print/multisensor_print.ino @@ -14,9 +14,6 @@ DISCLAIMER: THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. *****************************************************************************/ -// Some define statements -#define STANDARD_SERIAL_OUTPUT Serial // Without this there will be no output - // ========================================================================== // Include the base required libraries // ========================================================================== @@ -26,24 +23,16 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "modular_sensors.ino"; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new sensor array instance -VariableArray sensors; - // ========================================================================== // Primary Arduino-Based Board and Processor // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) @@ -188,10 +177,18 @@ ExternalVoltage extvolt(VoltPower, VoltData, VoltGain, Volt_ADS1115Address, Volt // Neither hardware serial nor AltSoftSerial require any modifications to // deal with interrupt conflicts. -#include // for the stream communication const int SonarData = 11; // data receive pin + +#include // for the stream communication SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// #include // for the stream communication +// NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// void NeoSWSISR() +// { +// NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +// } + #include const int8_t SonarPower = 22; // Excite (power) pin (-1 if unconnected) const int8_t Sonar1Trigger = A1; // Trigger pin (a negative number if unconnected) (A1 = 25) @@ -369,6 +366,8 @@ ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { new ApogeeSQ212_PAR(&SQ212), new AOSongAM2315_Humidity(&am2315), @@ -437,7 +436,10 @@ Variable *variableList[] = { new MaximDS3231_Temp(&ds3231), // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray sensors(variableCount, variableList); // ========================================================================== @@ -458,6 +460,9 @@ void greenredflash(int numFlash = 4, int rate = 75) digitalWrite(redLED, LOW); } +// The clock's timezone. +const int8_t timeZone = -5; + // Helper function to get the current date/time from the RTC // as a unix timestamp - and apply the correct time zone. long currentepochtime = 0; @@ -518,7 +523,10 @@ void setup() sonarSerial.begin(9600); // Allow interrupts for software serial #if defined SoftwareSerial_ExtInts_h - enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + #endif + #if defined NeoSWSerial_h + enableInterrupt(SonarData, NeoSWSISR, CHANGE); #endif // Start the Real Time Clock @@ -540,9 +548,6 @@ void setup() Serial.print(String(variableCount)); Serial.println(F(" variables to be recorded.")); - // Initialize the sensor array; - sensors.init(variableCount, variableList); - // Set up all the sensors sensors.setupSensors(); diff --git a/examples/simple_logging/simple_logging.ino b/examples/simple_logging/simple_logging.ino index 720fd6c45..e0c9741f2 100644 --- a/examples/simple_logging/simple_logging.ino +++ b/examples/simple_logging/simple_logging.ino @@ -21,20 +21,9 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include -// ========================================================================== -// Basic Logger Settings -// ========================================================================== // The name of this file const char *sketchName = "simple_logging.ino"; -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create a new logger instance -Logger logger; // ========================================================================== @@ -42,7 +31,7 @@ Logger logger; // ========================================================================== #include -const long serialBaud = 57600; // Baud rate for the primary serial port for debugging +const long serialBaud = 115200; // Baud rate for the primary serial port for debugging const int8_t greenLED = 8; // Pin for the green LED (-1 if unconnected) const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) const int8_t buttonPin = 21; // Pin for a button to use to enter debugging mode (-1 if unconnected) @@ -192,10 +181,18 @@ ExternalVoltage extvolt(VoltPower, VoltData, VoltGain, Volt_ADS1115Address, Volt // Neither hardware serial nor AltSoftSerial require any modifications to // deal with interrupt conflicts. -#include // for the stream communication const int SonarData = 11; // data receive pin + +#include // for the stream communication SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// #include // for the stream communication +// NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// void NeoSWSISR() +// { +// NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +// } + #include const int8_t SonarPower = 22; // Excite (power) pin (-1 if unconnected) const int8_t Sonar1Trigger = A1; // Trigger pin (a negative number if unconnected) (A1 = 25) @@ -373,6 +370,8 @@ ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { new ApogeeSQ212_PAR(&SQ212), new AOSongAM2315_Humidity(&am2315), @@ -441,7 +440,23 @@ Variable *variableList[] = { new MaximDS3231_Temp(&ds3231), // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); + + +// ========================================================================== +// Data Logger Settings +// ========================================================================== +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; +// Create a new logger instance +Logger logger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -478,7 +493,10 @@ void setup() sonarSerial.begin(9600); // Allow interrupts for software serial #if defined SoftwareSerial_ExtInts_h - enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + #endif + #if defined NeoSWSerial_h + enableInterrupt(SonarData, NeoSWSISR, CHANGE); #endif // Set up pins for the LED's @@ -499,9 +517,7 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - logger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); + // Set information pins logger.setAlertPin(greenLED); // Begin the logger @@ -517,9 +533,11 @@ void setup() Serial.print(buttonPin); Serial.println(F(" at any time to enter sensor testing mode.")); - // Sleep - logger.systemSleep(); + // Blink the LEDs really fast to show start-up is done + greenredflash(6, 25); + // Sleep + EnviroDIYLogger.systemSleep(); } From dcc0a5eda397948ca2d02887b7f11f245e23939b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 16:00:50 -0400 Subject: [PATCH 24/54] Fixed example --- examples/simple_logging/simple_logging.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/simple_logging/simple_logging.ino b/examples/simple_logging/simple_logging.ino index e0c9741f2..3a9a337b6 100644 --- a/examples/simple_logging/simple_logging.ino +++ b/examples/simple_logging/simple_logging.ino @@ -537,7 +537,7 @@ void setup() greenredflash(6, 25); // Sleep - EnviroDIYLogger.systemSleep(); + logger.systemSleep(); } From 327467fe346d26d80499f19bf346b8663501cc2d Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 16:13:27 -0400 Subject: [PATCH 25/54] Removed unpopular "checkForTestingMode" --- src/LoggerBase.cpp | 88 +++++++++++++++++++++------------------------- src/LoggerBase.h | 4 +-- 2 files changed, 41 insertions(+), 51 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 427f3eb4d..440f4a1d9 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -52,12 +52,6 @@ Logger::Logger(const char *loggerID, uint8_t loggingIntervalMinutes, _numTimepointsLogged = 0; _internalArray = inputArray; - // Set sleep variable, if an interrupt pin is given - if(_mcuWakePin != -1) - { - _sleep = true; - } - // Set the testing/logging flags isLoggingNow = false; isTestingNow = false; @@ -250,6 +244,7 @@ bool Logger::checkInterval(void) MS_DBG(F("Mod of Logging Interval: "), checkTime % _loggingIntervalSeconds, F("\n")); MS_DBG(F("Number of Readings so far: "), _numTimepointsLogged, F("\n")); MS_DBG(F("Mod of 120: "), checkTime % 120, F("\n")); + if ((checkTime % _loggingIntervalSeconds == 0 ) or (_numTimepointsLogged < 10 and checkTime % 120 == 0)) { @@ -287,6 +282,7 @@ bool Logger::checkMarkedInterval(void) MS_DBG(F("Mod of Logging Interval: "), markedEpochTime % _loggingIntervalSeconds, F("\n")); MS_DBG(F("Number of Readings so far: "), _numTimepointsLogged, F("\n")); MS_DBG(F("Mod of 120: "), markedEpochTime % 120, F("\n")); + if (markedEpochTime != 0 && ((markedEpochTime % _loggingIntervalSeconds == 0 ) or (_numTimepointsLogged < 10 and markedEpochTime % 120 == 0))) @@ -549,7 +545,7 @@ String Logger::generateFileHeader(void) makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarName()) // Next comes the ODM2 unit name makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUnit()) - // Next comes the variable UUIDs unit name + // Next comes the variable UUIDs makeHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUUID()) // We'll finish up the the custom variable codes @@ -567,12 +563,7 @@ String Logger::generateFileHeader(void) // String logIDRowHeader = F("Data Logger: "); // logIDRowHeader += String(_loggerID); // -// // First line will be the variable UUID's -// stream->print(logIDRowHeader); -// _internalArray->streamVariableUUIDs(stream); -// stream->println(); -// -// // Next line will be the parent sensor names +// // First line will be the parent sensor names // stream->print(logIDRowHeader); // _internalArray->streamParentSensorNames(stream); // stream->println(); @@ -587,6 +578,11 @@ String Logger::generateFileHeader(void) // _internalArray->streamVariableUnits(stream); // stream->println(); // +// // Next comes the variable UUID's +// stream->print(logIDRowHeader); +// _internalArray->streamVariableUUIDs(stream); +// stream->println(); +// // // We'll finish up the the custom variable codes // stream->print(F("Date and Time in UTC")); // stream->print(_timeZone); @@ -617,11 +613,11 @@ String Logger::generateSensorDataCSV(void) // } -// This checks if the SD card is available and ready -bool Logger::initializeSDCard(uint8_t Pin) +// Private helper function - This checks if the SD card is available and ready +bool Logger::initializeSDCard(void) { // Initialise the SD card - if (!sd.begin(Pin, SPI_FULL_SPEED)) + if (!sd.begin(_SDCardPin, SPI_FULL_SPEED)) { PRINTOUT(F("Error: SD card failed to initialize or is missing.\n")); PRINTOUT(F("Data will not be saved!\n")); @@ -630,17 +626,13 @@ bool Logger::initializeSDCard(uint8_t Pin) else // skip everything else if there's no SD card, otherwise it might hang { PRINTOUT(F("Successfully connected to SD Card with card/slave select on pin ")); - PRINTOUT(Pin, F("\n")); + PRINTOUT(_SDCardPin, F("\n")); return true; } } -bool Logger::initializeSDCard(void) -{ - return initializeSDCard(_SDCardPin); -} -// This sets a timestamp on a file +// Private helper function - This sets a timestamp on a file void Logger::setFileTimestame(SdFile fileToStamp, uint8_t stampFlag) { fileToStamp.timestamp(stampFlag, dtFromEpoch(getNowEpoch()).year(), @@ -738,29 +730,29 @@ void Logger::logToSD(String rec) // This checks to see if you want to enter the sensor mode // This should be run as the very last step within the setup function -void Logger::checkForTestingMode(int8_t buttonPin) -{ - // Set the pin attached to some button to enter debug mode - if (buttonPin > 0) pinMode(buttonPin, INPUT_PULLUP); - - // Flash the LED to let user know it is now possible to enter debug mode - for (uint8_t i = 0; i < 15; i++) - { - digitalWrite(_ledPin, HIGH); - delay(50); - digitalWrite(_ledPin, LOW); - delay(50); - } - - // Look for up to 5 seconds for a button press - PRINTOUT(F("Push button NOW to enter sensor testing mode.\n")); - for (uint32_t start = millis(); millis() - start < 5000; ) - { - if (digitalRead(buttonPin) == HIGH) testingMode(); - } - PRINTOUT(F("------------------------------------------\n\n")); - PRINTOUT(F("End of sensor testing mode.\n")); -} +// void Logger::checkForTestingMode(int8_t buttonPin) +// { +// // Set the pin attached to some button to enter debug mode +// if (buttonPin > 0) pinMode(buttonPin, INPUT_PULLUP); +// +// // Flash the LED to let user know it is now possible to enter debug mode +// for (uint8_t i = 0; i < 15; i++) +// { +// digitalWrite(_ledPin, HIGH); +// delay(50); +// digitalWrite(_ledPin, LOW); +// delay(50); +// } +// +// // Look for up to 5 seconds for a button press +// PRINTOUT(F("Push button NOW to enter sensor testing mode.\n")); +// for (uint32_t start = millis(); millis() - start < 5000; ) +// { +// if (digitalRead(buttonPin) == HIGH) testingMode(); +// } +// PRINTOUT(F("------------------------------------------\n\n")); +// PRINTOUT(F("End of sensor testing mode.\n")); +// } // A static function if you'd prefer to enter testing based on an interrupt void Logger::testingISR() @@ -818,7 +810,7 @@ void Logger::testingMode() Logger::isTestingNow = false; // Sleep - if(_sleep){systemSleep();} + if(_mcuWakePin > -1){systemSleep();} } @@ -862,7 +854,7 @@ void Logger::testingMode() setupLogFile(); // Setup sleep mode - if(_sleep){setupSleep();} + if(_mcuWakePin > -1){setupSleep();} PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); @@ -915,5 +907,5 @@ void Logger::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_sleep){systemSleep();} + if(_mcuWakePin > -1){systemSleep();} } diff --git a/src/LoggerBase.h b/src/LoggerBase.h index dc06915b5..d986e4219 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -162,7 +162,7 @@ class Logger // This checks to see if you want to enter the sensor mode // This should be run as the very last step within the setup function - void checkForTestingMode(int8_t buttonPin); + // void checkForTestingMode(int8_t buttonPin); // A function if you'd prefer to enter testing based on an interrupt static void testingISR(void); @@ -221,12 +221,10 @@ class Logger bool _autoFileName; bool _isFileNameSet; uint8_t _numTimepointsLogged; - bool _sleep; int8_t _ledPin; VariableArray *_internalArray; // This checks if the SD card is available and ready - bool initializeSDCard(uint8_t Pin); bool initializeSDCard(void); // This sets a timestamp on a file From 7c70c580103ca6b96da27931bd8b06d81bf607fa Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 16:31:07 -0400 Subject: [PATCH 26/54] Some small clean-up --- src/LoggerBase.cpp | 42 ++++++++++++++++++++++++++++-------------- src/LoggerBase.h | 6 +++--- src/VariableArray.cpp | 28 ++++++++++++++-------------- src/VariableArray.h | 2 +- 4 files changed, 46 insertions(+), 32 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 440f4a1d9..c88795ab5 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -598,7 +598,16 @@ String Logger::generateSensorDataCSV(void) String csvString = ""; markedDateTime.addToString(csvString); csvString += F(","); - csvString += _internalArray->generateSensorDataCSV(); + + for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) + { + csvString += _internalArray->arrayOfVars[i]->getValueString(); + if (i + 1 != _internalArray->getVariableCount()) + { + csvString += F(","); + } + } + return csvString; } // // This sends a comma separated list of volues of sensor data - including the @@ -609,7 +618,14 @@ String Logger::generateSensorDataCSV(void) // markedDateTime.addToString(csvString); // csvString += F(","); // stream->print(csvString); -// _internalArray->streamSensorDataCSV(stream); +// for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) +// { +// stream->print(_internalArray->arrayOfVars[i]->getValueString()); +// if (i + 1 != _internalArray->getVariableCount()) +// { +// tream->print(F(",")); +// } +// } // } @@ -682,8 +698,10 @@ void Logger::setupLogFile(void) } -// This writes a record to the SD card with the given filename -void Logger::logToSD(String rec, String filename) +// This writes a record to the SD card, using the logger's filename +// The filename may either be set by setFileName(String) or will be +//automatically generated by setFileName(void) +void Logger::logToSD(String rec) { // Initialise the SD card // skip everything else if there's no SD card, otherwise it might hang @@ -691,19 +709,20 @@ void Logger::logToSD(String rec, String filename) else // skip everything else if there's no SD card, otherwise it might hang { // Convert the string filename to a character file name for SdFat - uint8_t fileNameLength = filename.length() + 1; + uint8_t fileNameLength = _fileName.length() + 1; char charFileName[fileNameLength]; - filename.toCharArray(charFileName, fileNameLength); + _fileName.toCharArray(charFileName, fileNameLength); // Check that the file exists, just in case someone yanked the SD card if (!logFile.open(charFileName, O_WRITE | O_AT_END)) { PRINTOUT(F("SD Card File Lost! Starting new file.\n")); - setupLogFile(filename, ""); + setupLogFile(); } - // Write the CSV data - logFile.println(rec); + // Write the data + if (rec == "") logFile.println(generateSensorDataCSV()); + else logFile.println(rec); // Echo the line to the serial port PRINTOUT(F("\n \\/---- Line Saved to SD Card ----\\/ \n")); PRINTOUT(rec, F("\n")); @@ -717,11 +736,6 @@ void Logger::logToSD(String rec, String filename) logFile.close(); } } -// This writes a record to the SD card, using the logger's filename -void Logger::logToSD(String rec) -{ - logToSD(rec, _fileName); -} // ===================================================================== // diff --git a/src/LoggerBase.h b/src/LoggerBase.h index d986e4219..a2b4d45af 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -150,10 +150,10 @@ class Logger // writes a header to it based on the sensors attached to variables in the array void setupLogFile(void); - // This writes a record to the SD card with the given filename - void logToSD(String rec, String filename); // This writes a record to the SD card, using the logger's filename - void logToSD(String rec); + // The filename may either be set by setFileName(String) or will be + // automatically generated by setFileName(void) + void logToSD(String rec = ""); // ===================================================================== // diff --git a/src/VariableArray.cpp b/src/VariableArray.cpp index 986862104..b0d861870 100644 --- a/src/VariableArray.cpp +++ b/src/VariableArray.cpp @@ -480,21 +480,21 @@ void VariableArray::printSensorData(Stream *stream) // These generate some helpful comma-separated lists of variable information // This is a PRE-PROCESSOR MACRO to speed up generating header rows // Again, THIS IS NOT A FUNCTION, it is a pre-processor macro -#define makeVarListCSV(function) \ - { \ - String csvString = ""; \ - for (uint8_t i = 0; i < _variableCount; i++) \ - { \ - csvString += arrayOfVars[i]->function; \ - if (i + 1 != _variableCount) \ - { \ - csvString += F(","); \ - } \ - } \ - return csvString; \ - } +// #define makeVarListCSV(function) \ +// { \ +// String csvString = ""; \ +// for (uint8_t i = 0; i < _variableCount; i++) \ +// { \ +// csvString += arrayOfVars[i]->function; \ +// if (i + 1 != _variableCount) \ +// { \ +// csvString += F(","); \ +// } \ +// } \ +// return csvString; \ +// } // This generates a comma separated list of sensor values WITHOUT TIME STAMP -String VariableArray::generateSensorDataCSV(void){makeVarListCSV(getValueString())}; +// String VariableArray::generateSensorDataCSV(void){makeVarListCSV(getValueString())}; // This generates a comma separated list of parent sensor names // String VariableArray::listParentSensorNames(void){makeVarListCSV(getParentSensorName())}; // This generates a comma separated list of variable names diff --git a/src/VariableArray.h b/src/VariableArray.h index 00f4c8712..18680edb4 100644 --- a/src/VariableArray.h +++ b/src/VariableArray.h @@ -64,7 +64,7 @@ class VariableArray // These generate some helpful comma-separated lists of variable information // This generates a comma separated list of sensor values WITHOUT TIME STAMP - String generateSensorDataCSV(void); + // String generateSensorDataCSV(void); // This generates a comma separated list of parent sensor names // String listParentSensorNames(void); // This generates a comma separated list of variable names From 2ac9dc8d46fa0b2ab26d8fdaa8775c8ccb793c95 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 16:35:02 -0400 Subject: [PATCH 27/54] Fix for removed _sleep --- src/LoggerDreamHost.cpp | 2 +- src/LoggerEnviroDIY.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index d81da371e..5df4aa624 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -252,5 +252,5 @@ void LoggerDreamHost::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_sleep){systemSleep();} + if(_mcuWakePin > -1){systemSleep();} } diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 39d4c85a9..4a8ea1449 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -311,7 +311,7 @@ void LoggerEnviroDIY::testingMode() Logger::isTestingNow = false; // Sleep - if(_sleep){systemSleep();} + if(_mcuWakePin > -1){systemSleep();} } @@ -379,7 +379,7 @@ void LoggerEnviroDIY::begin(void) setupLogFile(); // Setup sleep mode - if(_sleep){setupSleep();} + if(_mcuWakePin > -1){setupSleep();} PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); @@ -460,5 +460,5 @@ void LoggerEnviroDIY::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_sleep){systemSleep();} + if(_mcuWakePin > -1){systemSleep();} } From 94231136d25fe048ee9da48a3b1195b95737839e Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 16:41:10 -0400 Subject: [PATCH 28/54] Fixed multisensor_print --- examples/multisensor_print/multisensor_print.ino | 4 +--- src/LoggerBase.cpp | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/examples/multisensor_print/multisensor_print.ino b/examples/multisensor_print/multisensor_print.ino index afd1275c8..fd76776af 100644 --- a/examples/multisensor_print/multisensor_print.ino +++ b/examples/multisensor_print/multisensor_print.ino @@ -38,7 +38,7 @@ const int8_t redLED = 9; // Pin for the red LED (-1 if unconnected) // Create and return the processor "sensor" const char *MFVersion = "v0.5"; -ProcessorStats mayfly(MFVersion) ; +ProcessorStats mayfly(MFVersion); // ========================================================================== @@ -590,8 +590,6 @@ void loop() Serial.print(F("Updated all sensors at ")); Serial.println(getDateTime_ISO8601()); sensors.printSensorData(&Serial); - Serial.print(F("In CSV Format: ")); - Serial.println(sensors.generateSensorDataCSV()); // Turn off the LED to show we're done with the reading digitalWrite(greenLED, LOW); // Print a to close it off diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index c88795ab5..56a0cb48b 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -685,7 +685,7 @@ void Logger::setupLogFile(String filename, String header) // Add header information logFile.print(header); - MS_DBG(header, F("\n")); + MS_DBG(F("File Header:\n"), header, F("\n")); //Close the file to save it logFile.close(); From 2734d320a43d60249f747c8478b41e960719fc44 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Wed, 23 May 2018 17:17:52 -0400 Subject: [PATCH 29/54] Made testing mode part of a logger Also, 0 is a valid pin number --- examples/DRWI_CitSci/DRWI_CitSci.ino | 17 +------ examples/DRWI_NoCellular/DRWI_NoCellular.ino | 19 ++------ .../baro_rho_correction.ino | 17 +------ examples/data_saving/data_saving.ino | 19 +------- .../logging_to_EnviroDIY.ino | 17 +------ .../logging_to_EnviroDIY_Zero.ino | 3 -- examples/simple_logging/simple_logging.ino | 17 +------ src/KellerParent.cpp | 2 +- src/LoggerBase.cpp | 45 +++++++++++++++---- src/LoggerBase.h | 4 ++ src/LoggerDreamHost.cpp | 6 +-- src/LoggerEnviroDIY.cpp | 36 +++++++++++---- src/MaxBotixSonar.cpp | 4 +- src/SensorBase.cpp | 10 ++--- src/YosemitechParent.cpp | 2 +- 15 files changed, 88 insertions(+), 130 deletions(-) diff --git a/examples/DRWI_CitSci/DRWI_CitSci.ino b/examples/DRWI_CitSci/DRWI_CitSci.ino index e68d6923b..e50b84043 100644 --- a/examples/DRWI_CitSci/DRWI_CitSci.ino +++ b/examples/DRWI_CitSci/DRWI_CitSci.ino @@ -212,28 +212,13 @@ void setup() // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); + EnviroDIYLogger.setTestingModePin(buttonPin); // Set up the connection with DreamHost EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); // Begin the logger EnviroDIYLogger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Sleep - EnviroDIYLogger.systemSleep(); } diff --git a/examples/DRWI_NoCellular/DRWI_NoCellular.ino b/examples/DRWI_NoCellular/DRWI_NoCellular.ino index a32dda038..2a44c7b07 100644 --- a/examples/DRWI_NoCellular/DRWI_NoCellular.ino +++ b/examples/DRWI_NoCellular/DRWI_NoCellular.ino @@ -175,25 +175,10 @@ void setup() // Set an alert pin logger.setAlertPin(greenLED); + logger.setTestingModePin(buttonPin); // Begin the logger logger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Sleep - logger.systemSleep(); } @@ -205,3 +190,5 @@ void loop() // Log the data logger.log(); } + +EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index b482e2704..e7f599634 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -365,6 +365,7 @@ void setup() // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); EnviroDIYLogger.setAlertPin(greenLED); + EnviroDIYLogger.setTestingModePin(buttonPin); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); @@ -372,22 +373,6 @@ void setup() // Begin the logger EnviroDIYLogger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Sleep - EnviroDIYLogger.systemSleep(); } diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index 12d8c3bf8..a50234488 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -324,7 +324,7 @@ void setup() // attaching it to both allows either logger to control NIST synchronization loggerComplete.attachModem(&modem); loggerToGo.attachModem(&modem); - + loggerComplete.setTestingModePin(buttonPin); // There is no reason to call the setAlertPin() function, because we have to // write the loop on our own. @@ -340,23 +340,6 @@ void setup() // and all of the sensors. We don't need to bother with the "begin" for the // other logger because it has the same processor and clock. loggerComplete.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // loggerComplete.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Call the processor sleep - // Only need to do this for one of the loggers - loggerComplete.systemSleep(); } diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index c84b9fc27..a1b0f7be0 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -598,6 +598,7 @@ void setup() // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); EnviroDIYLogger.setAlertPin(greenLED); + EnviroDIYLogger.setTestingModePin(buttonPin); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); @@ -605,22 +606,6 @@ void setup() // Begin the logger EnviroDIYLogger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Sleep - EnviroDIYLogger.systemSleep(); } diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index 436c3e205..6dd0e8551 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -609,9 +609,6 @@ void setup() // Begin the logger EnviroDIYLogger.begin(); - - // Sleep - EnviroDIYLogger.systemSleep(); } diff --git a/examples/simple_logging/simple_logging.ino b/examples/simple_logging/simple_logging.ino index 3a9a337b6..fb34ebc2d 100644 --- a/examples/simple_logging/simple_logging.ino +++ b/examples/simple_logging/simple_logging.ino @@ -519,25 +519,10 @@ void setup() // Set information pins logger.setAlertPin(greenLED); + logger.setTestingModePin(buttonPin); // Begin the logger logger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); - - // Sleep - logger.systemSleep(); } diff --git a/src/KellerParent.cpp b/src/KellerParent.cpp index 40d08d583..80a244af1 100644 --- a/src/KellerParent.cpp +++ b/src/KellerParent.cpp @@ -59,7 +59,7 @@ String KellerParent::getSensorLocation(void) bool KellerParent::setup(void) { bool retVal = Sensor::setup(); // sets time stamp and status bits - if (_RS485EnablePin > 0) pinMode(_RS485EnablePin, OUTPUT); + if (_RS485EnablePin >= 0) pinMode(_RS485EnablePin, OUTPUT); #if defined(DEEP_DEBUGGING_SERIAL_OUTPUT) sensor.setDebugStream(&DEEP_DEBUGGING_SERIAL_OUTPUT); diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 56a0cb48b..1e7886a47 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -56,6 +56,10 @@ Logger::Logger(const char *loggerID, uint8_t loggingIntervalMinutes, isLoggingNow = false; isTestingNow = false; startTesting = false; + + // Set the info pin numbers + _ledPin = -1; + _buttonPin = -1; }; @@ -99,6 +103,14 @@ void Logger::setAlertPin(int8_t ledPin) } +// Sets up a pin for an interrupt to enter testing mode +void Logger::setTestingModePin(int8_t buttonPin) +{ + _buttonPin = buttonPin; + MS_DBG(F("Pin "), _buttonPin, F(" set as testing mode entry pin\n")); +} + + // ===================================================================== // // Public functions to access the clock in proper format and time zone // ===================================================================== // @@ -747,7 +759,7 @@ void Logger::logToSD(String rec) // void Logger::checkForTestingMode(int8_t buttonPin) // { // // Set the pin attached to some button to enter debug mode -// if (buttonPin > 0) pinMode(buttonPin, INPUT_PULLUP); +// if (buttonPin >= 0) pinMode(buttonPin, INPUT_PULLUP); // // // Flash the LED to let user know it is now possible to enter debug mode // for (uint8_t i = 0; i < 15; i++) @@ -824,7 +836,7 @@ void Logger::testingMode() Logger::isTestingNow = false; // Sleep - if(_mcuWakePin > -1){systemSleep();} + if(_mcuWakePin >= 0){systemSleep();} } @@ -836,7 +848,8 @@ void Logger::testingMode() void Logger::begin(void) { // Set up pins for the LED's - if (_ledPin > 0) pinMode(_ledPin, OUTPUT); + if (_ledPin >= 0) pinMode(_ledPin, OUTPUT); + if (_buttonPin >= 0) pinMode(_buttonPin, INPUT_PULLUP); #if defined ARDUINO_ARCH_SAMD zero_sleep_rtc.begin(); @@ -853,8 +866,10 @@ void Logger::testingMode() _loggingIntervalMinutes, F(" minute intervals.\n")); PRINTOUT(F("This logger has a variable array with "), - _internalArray->getVariableCount(), F(" variables from "), - _internalArray->getSensorCount(), F(" sensors.\n")); + _internalArray->getVariableCount(), F(" variables, of which "), + _internalArray->getVariableCount() - _internalArray->getCalculatedVariableCount(), + F(" come from "),_internalArray->getSensorCount(), F(" sensors and "), + _internalArray->getCalculatedVariableCount(), F(" are calculated.\n")); // Set up the sensors _internalArray->setupSensors(); @@ -868,10 +883,22 @@ void Logger::testingMode() setupLogFile(); // Setup sleep mode - if(_mcuWakePin > -1){setupSleep();} + if(_mcuWakePin >= 0){setupSleep();} + + // Set up the interrupt to be able to enter sensor testing mode + if (_buttonPin >= 0) + { + enableInterrupt(_buttonPin, Logger::testingISR, CHANGE); + Serial.print(F("Push button on pin ")); + Serial.print(_buttonPin); + Serial.println(F(" at any time to enter sensor testing mode.")); + } PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); + + // Sleep + if(_mcuWakePin >= 0){systemSleep();} } @@ -888,7 +915,7 @@ void Logger::log(void) // Print a line to show new reading PRINTOUT(F("------------------------------------------\n")); // Turn on the LED to show we're taking a reading - digitalWrite(_ledPin, HIGH); + if (_ledPin >= 0) digitalWrite(_ledPin, HIGH); // Send power to all of the sensors MS_DBG(F(" Powering sensors...\n")); @@ -909,7 +936,7 @@ void Logger::log(void) logToSD(generateSensorDataCSV()); // Turn off the LED - digitalWrite(_ledPin, LOW); + if (_ledPin >= 0) digitalWrite(_ledPin, LOW); // Print a line to show reading ended PRINTOUT(F("------------------------------------------\n\n")); @@ -921,5 +948,5 @@ void Logger::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_mcuWakePin > -1){systemSleep();} + if(_mcuWakePin >= 0){systemSleep();} } diff --git a/src/LoggerBase.h b/src/LoggerBase.h index a2b4d45af..8da6c5d4e 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -58,6 +58,9 @@ class Logger // Sets up a pin for an LED or other way of alerting that data is being logged void setAlertPin(int8_t ledPin); + // Sets up a pin for an interrupt to enter testing mode + void setTestingModePin(int8_t buttonPin); + // ===================================================================== // // Public functions to access the clock in proper format and time zone @@ -222,6 +225,7 @@ class Logger bool _isFileNameSet; uint8_t _numTimepointsLogged; int8_t _ledPin; + int8_t _buttonPin; VariableArray *_internalArray; // This checks if the SD card is available and ready diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 5df4aa624..1acb63d5e 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -185,7 +185,7 @@ void LoggerDreamHost::log(void) // Print a line to show new reading PRINTOUT(F("------------------------------------------\n")); // Turn on the LED to show we're taking a reading - digitalWrite(_ledPin, HIGH); + if (_ledPin >= 0) digitalWrite(_ledPin, HIGH); if (_modemAttached) { @@ -240,7 +240,7 @@ void LoggerDreamHost::log(void) logToSD(generateSensorDataCSV()); // Turn off the LED - digitalWrite(_ledPin, LOW); + if (_ledPin >= 0) digitalWrite(_ledPin, LOW); // Print a line to show reading ended PRINTOUT(F("------------------------------------------\n\n")); @@ -252,5 +252,5 @@ void LoggerDreamHost::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_mcuWakePin > -1){systemSleep();} + if(_mcuWakePin >= 0){systemSleep();} } diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 4a8ea1449..0a610e519 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -10,6 +10,11 @@ #include "LoggerEnviroDIY.h" +// To prevent compiler/linker crashes with Enable interrupt +#define LIBCALL_ENABLEINTERRUPT +// To handle external and pin change interrupts +#include + // ============================================================================ // Functions for the EnviroDIY data portal receivers. @@ -311,7 +316,7 @@ void LoggerEnviroDIY::testingMode() Logger::isTestingNow = false; // Sleep - if(_mcuWakePin > -1){systemSleep();} + if(_mcuWakePin >= 0){systemSleep();} } @@ -323,7 +328,8 @@ void LoggerEnviroDIY::testingMode() void LoggerEnviroDIY::begin(void) { // Set up pins for the LED's - if (_ledPin > 0) pinMode(_ledPin, OUTPUT); + if (_ledPin >= 0) pinMode(_ledPin, OUTPUT); + if (_buttonPin >= 0) pinMode(_buttonPin, INPUT_PULLUP); #if defined ARDUINO_ARCH_SAMD zero_sleep_rtc.begin(); @@ -340,8 +346,10 @@ void LoggerEnviroDIY::begin(void) _loggingIntervalMinutes, F(" minute intervals.\n")); PRINTOUT(F("This logger has a variable array with "), - _internalArray->getVariableCount(), F(" variables from "), - _internalArray->getSensorCount(), F(" sensors.\n")); + _internalArray->getVariableCount(), F(" variables, of which "), + _internalArray->getVariableCount() - _internalArray->getCalculatedVariableCount(), + F(" come from "),_internalArray->getSensorCount(), F(" sensors and "), + _internalArray->getCalculatedVariableCount(), F(" are calculated.\n")); if (_modemAttached) { @@ -379,10 +387,22 @@ void LoggerEnviroDIY::begin(void) setupLogFile(); // Setup sleep mode - if(_mcuWakePin > -1){setupSleep();} + if(_mcuWakePin >= 0){setupSleep();} + + // Set up the interrupt to be able to enter sensor testing mode + if (_buttonPin >= 0) + { + enableInterrupt(_buttonPin, Logger::testingISR, CHANGE); + Serial.print(F("Push button on pin ")); + Serial.print(_buttonPin); + Serial.println(F(" at any time to enter sensor testing mode.")); + } PRINTOUT(F("Logger setup finished!\n")); PRINTOUT(F("------------------------------------------\n\n")); + + // Sleep + if(_mcuWakePin >= 0){systemSleep();} } @@ -399,7 +419,7 @@ void LoggerEnviroDIY::log(void) // Print a line to show new reading PRINTOUT(F("------------------------------------------\n")); // Turn on the LED to show we're taking a reading - digitalWrite(_ledPin, HIGH); + if (_ledPin >= 0) digitalWrite(_ledPin, HIGH); if (_modemAttached) { @@ -448,7 +468,7 @@ void LoggerEnviroDIY::log(void) logToSD(generateSensorDataCSV()); // Turn off the LED - digitalWrite(_ledPin, LOW); + if (_ledPin >= 0) digitalWrite(_ledPin, LOW); // Print a line to show reading ended PRINTOUT(F("------------------------------------------\n\n")); @@ -460,5 +480,5 @@ void LoggerEnviroDIY::log(void) if (Logger::startTesting) testingMode(); // Sleep - if(_mcuWakePin > -1){systemSleep();} + if(_mcuWakePin >= 0){systemSleep();} } diff --git a/src/MaxBotixSonar.cpp b/src/MaxBotixSonar.cpp index 1ddd92c7c..1d2f50f51 100644 --- a/src/MaxBotixSonar.cpp +++ b/src/MaxBotixSonar.cpp @@ -44,7 +44,7 @@ String MaxBotixSonar::getSensorLocation(void) bool MaxBotixSonar::setup(void) { // Set up the trigger, if applicable - if(_triggerPin > 0) + if(_triggerPin >= 0) { pinMode(_triggerPin, OUTPUT); digitalWrite(_triggerPin, LOW); @@ -116,7 +116,7 @@ bool MaxBotixSonar::addSingleMeasurementResult(void) // for each "single measurement" until a valid value is returned // and the measurement time is <166ms, we'll actually activate // the trigger here. - if(_triggerPin > 0) + if(_triggerPin >= 0) { MS_DBG(F("Triggering Sonar with "), _triggerPin, '\n'); digitalWrite(_triggerPin, HIGH); diff --git a/src/SensorBase.cpp b/src/SensorBase.cpp index 942f9d223..a8c0d655c 100644 --- a/src/SensorBase.cpp +++ b/src/SensorBase.cpp @@ -109,7 +109,7 @@ uint8_t Sensor::getStatus(void) // This turns on sensor power void Sensor::powerUp(void) { - if (_powerPin > 0) + if (_powerPin >= 0) { MS_DBG(F("Powering "), getSensorName(), F(" at "), getSensorLocation(), F(" with pin "), _powerPin, F("\n")); @@ -130,7 +130,7 @@ void Sensor::powerUp(void) // This turns off sensor power void Sensor::powerDown(void) { - if (_powerPin > 0) + if (_powerPin >= 0) { MS_DBG(F("Turning off power to "), getSensorName(), F(" at "), getSensorLocation(), F(" with pin "), _powerPin, F("\n")); @@ -165,8 +165,8 @@ bool Sensor::setup(void) MS_DBG(_measurementsToAverage); MS_DBG(F(" individual measurements will be averaged for each reading.\n")); - if (_powerPin > 0) pinMode(_powerPin, OUTPUT); - if (_dataPin > 0) pinMode(_dataPin, INPUT_PULLUP); + if (_powerPin >= 0) pinMode(_powerPin, OUTPUT); + if (_dataPin >= 0) pinMode(_dataPin, INPUT_PULLUP); // Set the status bit marking that the sensor has been set up (bit 1) _sensorStatus |= 0b00000010; @@ -413,7 +413,7 @@ bool Sensor::checkPowerOn(bool debug) { if (debug) MS_DBG(F("Checking power status: Power to "), getSensorName(), F(" at "), getSensorLocation()); - if (_powerPin > 0) + if (_powerPin >= 0) { int powerBitNumber = log(digitalPinToBitMask(_powerPin))/log(2); diff --git a/src/YosemitechParent.cpp b/src/YosemitechParent.cpp index 503f22440..8120a3f8f 100644 --- a/src/YosemitechParent.cpp +++ b/src/YosemitechParent.cpp @@ -57,7 +57,7 @@ String YosemitechParent::getSensorLocation(void) bool YosemitechParent::setup(void) { bool retVal = Sensor::setup(); // sets time stamp and status bits - if (_RS485EnablePin > 0) pinMode(_RS485EnablePin, OUTPUT); + if (_RS485EnablePin >= 0) pinMode(_RS485EnablePin, OUTPUT); #if defined(DEEP_DEBUGGING_SERIAL_OUTPUT) sensor.setDebugStream(&DEEP_DEBUGGING_SERIAL_OUTPUT); From 4ae43cb9ab32e1aed8fbe418d58ff781ac771ff1 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 12:33:09 -0400 Subject: [PATCH 30/54] Restructured to allow data to be streamed to SD card --- examples/data_saving/data_saving.ino | 5 +- examples/double_logger/double_logger.ino | 17 +- src/LoggerBase.cpp | 283 +++++++++++++++-------- src/LoggerBase.h | 50 ++-- src/LoggerDreamHost.cpp | 2 +- src/LoggerEnviroDIY.cpp | 6 +- 6 files changed, 231 insertions(+), 132 deletions(-) diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index a50234488..f6da9d4fe 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -389,8 +389,9 @@ void loop() // we will explicitly start and end the serial connection in the loop. modbusSerial.end(); - // Create a csv data record and save it to the log file - loggerComplete.logToSD(loggerComplete.generateSensorDataCSV()); + // Stream the variable results from the complete set of variables to + // the SD card + loggerComplete.logToSD(); // Connect to the network Serial.print(F("Connecting to the internet...\n")); diff --git a/examples/double_logger/double_logger.ino b/examples/double_logger/double_logger.ino index 23fe34283..8572008fa 100644 --- a/examples/double_logger/double_logger.ino +++ b/examples/double_logger/double_logger.ino @@ -245,9 +245,12 @@ void setup() logger1min.setFileName(FileName1min); logger5min.setFileName(FileName5min); - // Setup the logger files. This will automatically add headers to each - logger1min.setupLogFile(); - logger5min.setupLogFile(); + // Setup the logger files. Specifying true will put a default header at + // on to the file when it's created. + // Because we've already called setFileName, we do not need to specify the + // file name for this function. + logger1min.createLogFile(true); + logger5min.createLogFile(true); // Set up the processor sleep mode // Because there's only one processor, we only need to do this once @@ -296,8 +299,8 @@ void loop() Serial.print(F("Cutting sensor power...\n")); array1min.sensorsPowerDown(); - // Create a csv data record and save it to the log file - logger1min.logToSD(logger1min.generateSensorDataCSV()); + // Stream the csv data to the SD card + logger1min.logToSD(); // Turn off the LED digitalWrite(greenLED, LOW); @@ -329,8 +332,8 @@ void loop() Serial.print(F("Cutting sensor power...\n")); array1min.sensorsPowerDown(); - // Create a csv data record and save it to the log file - logger5min.logToSD(logger5min.generateSensorDataCSV()); + // Stream the csv data to the SD card + logger5min.logToSD(); // Turn off the LED digitalWrite(redLED, LOW); diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 1e7886a47..c900691f6 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -568,40 +568,46 @@ String Logger::generateFileHeader(void) // Return everything return dataHeader; } -// // This sends a file header out over an Arduino stream -// void Logger::streamFileHeader(Stream *stream) -// { -// // Very first column of the header is the logger ID -// String logIDRowHeader = F("Data Logger: "); -// logIDRowHeader += String(_loggerID); -// -// // First line will be the parent sensor names -// stream->print(logIDRowHeader); -// _internalArray->streamParentSensorNames(stream); -// stream->println(); -// -// // Next comes the ODM2 variable name -// stream->print(logIDRowHeader); -// _internalArray->streamVariableNames(stream); -// stream->println(); -// -// // Next comes the ODM2 unit name -// stream->print(logIDRowHeader); -// _internalArray->streamVariableUnits(stream); -// stream->println(); -// -// // Next comes the variable UUID's -// stream->print(logIDRowHeader); -// _internalArray->streamVariableUUIDs(stream); -// stream->println(); -// -// // We'll finish up the the custom variable codes -// stream->print(F("Date and Time in UTC")); -// stream->print(_timeZone); -// stream->print(logIDRowHeader); -// _internalArray->streamVariableCodes(stream); -// stream->println(); -// } + +// This is another PRE-PROCESSOR MACRO to speed up generating header rows +// Again, THIS IS NOT A FUNCTION, it is a pre-processor macro +#define streamHeaderRowMacro(firstCol, function) \ + stream->print(F("\"")); \ + stream->print(firstCol); \ + stream->print(F("\",")); \ + for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) \ + { \ + stream->print(F("\"")); \ + stream->print(function); \ + stream->print(F("\"")); \ + if (i + 1 != _internalArray->getVariableCount()) \ + { \ + stream->print(F(",")); \ + } \ + } \ + stream->print(F("\r\n")); + +// This sends a file header out over an Arduino stream +void Logger::streamFileHeader(Stream *stream) +{ + // Very first column of the header is the logger ID + String logIDRowHeader = F("Data Logger: "); + logIDRowHeader += String(_loggerID); + + // Next line will be the parent sensor names + streamHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getParentSensorName()) + // Next comes the ODM2 variable name + streamHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarName()) + // Next comes the ODM2 unit name + streamHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUnit()) + // Next comes the variable UUIDs + streamHeaderRowMacro(logIDRowHeader, _internalArray->arrayOfVars[i]->getVarUUID()) + + // We'll finish up the the custom variable codes + String dtRowHeader = F("Date and Time in UTC"); + dtRowHeader += _timeZone; + streamHeaderRowMacro(dtRowHeader, _internalArray->arrayOfVars[i]->getVarCode()); +} // This generates a comma separated list of volues of sensor data - including the time @@ -622,23 +628,23 @@ String Logger::generateSensorDataCSV(void) return csvString; } -// // This sends a comma separated list of volues of sensor data - including the -// // time - out over an Arduino stream -// void Logger::streamSensorDataCSV(Stream *stream) -// { -// String csvString = ""; -// markedDateTime.addToString(csvString); -// csvString += F(","); -// stream->print(csvString); -// for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) -// { -// stream->print(_internalArray->arrayOfVars[i]->getValueString()); -// if (i + 1 != _internalArray->getVariableCount()) -// { -// tream->print(F(",")); -// } -// } -// } +// This sends a comma separated list of volues of sensor data - including the +// time - out over an Arduino stream +void Logger::streamSensorDataCSV(Stream *stream) +{ + String csvString = ""; + markedDateTime.addToString(csvString); + csvString += F(","); + stream->print(csvString); + for (uint8_t i = 0; i < _internalArray->getVariableCount(); i++) + { + stream->print(_internalArray->arrayOfVars[i]->getValueString()); + if (i + 1 != _internalArray->getVariableCount()) + { + stream->print(F(",")); + } + } +} // Private helper function - This checks if the SD card is available and ready @@ -661,7 +667,7 @@ bool Logger::initializeSDCard(void) // Private helper function - This sets a timestamp on a file -void Logger::setFileTimestame(SdFile fileToStamp, uint8_t stampFlag) +void Logger::setFileTimestame(File fileToStamp, uint8_t stampFlag) { fileToStamp.timestamp(stampFlag, dtFromEpoch(getNowEpoch()).year(), dtFromEpoch(getNowEpoch()).month(), @@ -672,78 +678,151 @@ void Logger::setFileTimestame(SdFile fileToStamp, uint8_t stampFlag) } -// This initializes a file on the SD card with the given filename and writes the given header to it -void Logger::setupLogFile(String filename, String header) +// Private helper function - This opens or creates a file, converting a string +// file name to a character file name +bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) { // Initialise the SD card // skip everything else if there's no SD card, otherwise it might hang - if (!initializeSDCard()) return; - else - { - // Convert the string filename to a character file name for SdFat - uint8_t fileNameLength = filename.length() + 1; - char charFileName[fileNameLength]; - filename.toCharArray(charFileName, fileNameLength); + if (!initializeSDCard()) return false; - // Open the file in write mode (and create it if it did not exist) - logFile.open(charFileName, O_CREAT | O_WRITE | O_AT_END); - // Set creation date time - setFileTimestame(logFile, T_CREATE); - // Set write/modification date time - setFileTimestame(logFile, T_WRITE); + // Convert the string filename to a character file name for SdFat + uint8_t fileNameLength = filename.length() + 1; + char charFileName[fileNameLength]; + filename.toCharArray(charFileName, fileNameLength); + + // First attempt to open an already existing file (in write mode), so we + // tdon't try to re-create something that's already there. + // This should also prevent the header from being written over and over + // in the file. + if (logFile.open(charFileName, O_WRITE | O_AT_END)) + { + MS_DBG(F("Opened existing file: "), filename, F("\n")); // Set access date time setFileTimestame(logFile, T_ACCESS); - PRINTOUT(F("File created!\n")); + return true; + } + else if (createFile) + { + // Create and then open the file in write mode + if (logFile.open(charFileName, O_CREAT | O_WRITE | O_AT_END)) + { + MS_DBG(F("Created new file: "), filename, F("\n")); + // Set creation date time + setFileTimestame(logFile, T_CREATE); + // Write out a header, if requested + if (writeDefaultHeader) + { + // Add header information + streamFileHeader(&logFile); + // Print out the header for debugging + #if defined(DEBUGGING_SERIAL_OUTPUT) + MS_DBG(F("File Header:\n")); + streamFileHeader(&DEBUGGING_SERIAL_OUTPUT); + #endif + // Set write/modification date time + setFileTimestame(logFile, T_WRITE); + } + // Set access date time + setFileTimestame(logFile, T_ACCESS); + return true; + } + // Return false if we couldn't create the file + else + { + MS_DBG(F("Unable to create new file: "), filename, F("\n")); + return false; + } + } + // Return false if we couldn't access the file (and were not told to create it) + else + { + MS_DBG(F("Unable to to write to file: "), filename, F("\n")); + return false; + } +} - // Add header information - logFile.print(header); - MS_DBG(F("File Header:\n"), header, F("\n")); - //Close the file to save it +// These functions create a file on the SD card with the given filename and +// set the proper timestamps to the file. +// The filename may either be the one set by setFileName(String)/setFileName(void) +// or can be specified in the function. +// If specified, it will also write a header to the file based on +// the sensors in the group. +// This can be used to force a logger to create a file with a secondary file name. +void Logger::createLogFile(String filename, bool writeDefaultHeader) +{ + // Attempt to create and open a file + if (openFile(filename, true, writeDefaultHeader)) + { + // Close the file to save it (only do this if we'd opened it) logFile.close(); } } -// This initializes a file on the SD card and writes a header to it -void Logger::setupLogFile(void) +void Logger::createLogFile(bool writeDefaultHeader) { - setupLogFile(_fileName, generateFileHeader()); + createLogFile(_fileName, writeDefaultHeader); } -// This writes a record to the SD card, using the logger's filename -// The filename may either be set by setFileName(String) or will be -//automatically generated by setFileName(void) -void Logger::logToSD(String rec) +// These functions write a file on the SD card with the given filename and +// set the proper timestamps to the file. +// The filename may either be the one set by setFileName(String)/setFileName(void) +// or can be specified in the function. +// If the file does not already exist, the file will be created. +// This can be used to force a logger to write to a file with a secondary file name. +void Logger::logToSD(String filename, String rec) { - // Initialise the SD card - // skip everything else if there's no SD card, otherwise it might hang - if (!initializeSDCard()) return; - else // skip everything else if there's no SD card, otherwise it might hang + // First attempt to open the file without creating a new one + if (openFile(filename, false, false)) goto writeRecord; + // Next try to create the file, bail if we couldn't create it + else if (openFile(filename, true, false)) goto writeRecord; + else { - // Convert the string filename to a character file name for SdFat - uint8_t fileNameLength = _fileName.length() + 1; - char charFileName[fileNameLength]; - _fileName.toCharArray(charFileName, fileNameLength); - - // Check that the file exists, just in case someone yanked the SD card - if (!logFile.open(charFileName, O_WRITE | O_AT_END)) - { - PRINTOUT(F("SD Card File Lost! Starting new file.\n")); - setupLogFile(); - } + PRINTOUT(F("Unable to write to SD card!\n")); + return; + } - // Write the data - if (rec == "") logFile.println(generateSensorDataCSV()); - else logFile.println(rec); + writeRecord: + { + // If we could successfully open or create the file, write the data to it + logFile.println(rec); // Echo the line to the serial port PRINTOUT(F("\n \\/---- Line Saved to SD Card ----\\/ \n")); PRINTOUT(rec, F("\n")); // Set write/modification date time setFileTimestame(logFile, T_WRITE); - // Set access date time - setFileTimestame(logFile, T_ACCESS); + // Close the file to save it + logFile.close(); + } +} +void Logger::logToSD(String rec) +{ + logToSD(_fileName, rec); +} +// NOTE: This is structured differently than the version with a string input +// record. This is to avoid the creation/passing of very long strings. +void Logger::logToSD(void) +{ + // First attempt to open the file without creating a new one + if (openFile(_fileName, false, false)) goto writeRecord; + // Next try to create the file, bail if we couldn't create it + if (openFile(_fileName, true, false)) goto writeRecord; + else return; + + writeRecord: + { + // Write the data + streamSensorDataCSV(&logFile); + // Echo the line to the serial port + #if defined(STANDARD_SERIAL_OUTPUT) + PRINTOUT(F("\n \\/---- Line Saved to SD Card ----\\/ \n")); + streamSensorDataCSV(&STANDARD_SERIAL_OUTPUT); + #endif + // Set write/modification date time + setFileTimestame(logFile, T_WRITE); // Close the file to save it logFile.close(); } @@ -879,8 +958,8 @@ void Logger::testingMode() else if(_autoFileName){setFileName();} else setFileName(_fileName); // This just for a nice print-out - // Set up the log file - setupLogFile(); + // Create the log file, adding the default header to it + createLogFile(true); // Setup sleep mode if(_mcuWakePin >= 0){setupSleep();} @@ -933,7 +1012,7 @@ void Logger::log(void) MS_DBG(F(" Cutting sensor power...\n")); _internalArray->sensorsPowerDown(); // Create a csv data record and save it to the log file - logToSD(generateSensorDataCSV()); + logToSD(); // Turn off the LED if (_ledPin >= 0) digitalWrite(_ledPin, LOW); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 8da6c5d4e..34f078259 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -137,26 +137,38 @@ class Logger // This creates a header for the logger file virtual String generateFileHeader(void); // This prints a header onto a stream - this removes need to pass around - // very long string objects when not needed - // void streamFileHeader(Stream *stream); + // very long string objects which can crash the logger + void streamFileHeader(Stream *stream); // This generates a comma separated list of volues of sensor data - including the time String generateSensorDataCSV(void); // This sends a comma separated list of volues of sensor data - including the // time - out over an Arduino stream - // void streamSensorDataCSV(Stream *stream); - - // This initializes a file on the SD card with the given filename and - // writes the given header to it - void setupLogFile(String filename, String header); - // This initializes a file on the SD card using the logger's filename and - // writes a header to it based on the sensors attached to variables in the array - void setupLogFile(void); - - // This writes a record to the SD card, using the logger's filename - // The filename may either be set by setFileName(String) or will be - // automatically generated by setFileName(void) - void logToSD(String rec = ""); + void streamSensorDataCSV(Stream *stream); + + // These functions create a file on an SD card and set the created/modified/ + // accessed timestamps in that file. + // The filename may either be the one automatically generated by the logger + // id and the date, the one set by setFileName(String), or can be specified + // in the function. + // If asked to, these functions will also write a header to the file based + // on the variable information from the variable array. + // This can be used to force a logger to create a file with a secondary file name. + void createLogFile(String filename, bool writeDefaultHeader = false); + void createLogFile(bool writeDefaultHeader = false); + + // These functions create a file on an SD card and set the modified/accessed + // timestamps in that file. + // The filename may either be the one automatically generated by the logger + // id and the date, the one set by setFileName(String), or can be specified + // in the function. + // If the file does not already exist, the file will be created. + // The line to be written to the file can either be specified or will be + // a comma separated list of the current values of all variables in the + // variable array. + void logToSD(String filename, String rec); + void logToSD(String rec); + void logToSD(void); // ===================================================================== // @@ -204,7 +216,7 @@ class Logger // The SD card and file SdFat sd; - SdFile logFile; + File logFile; String _fileName; // Static variables - identical for EVERY logger @@ -232,7 +244,11 @@ class Logger bool initializeSDCard(void); // This sets a timestamp on a file - void setFileTimestame(SdFile fileToStamp, uint8_t stampFlag); + void setFileTimestame(File fileToStamp, uint8_t stampFlag); + + // This opens or creates a file, converting a string file name to a + // characterd file name + bool openFile(String filename, bool createFile, bool writeDefaultHeader); }; #endif diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 1acb63d5e..17ce3575f 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -237,7 +237,7 @@ void LoggerDreamHost::log(void) } // Create a csv data record and save it to the log file - logToSD(generateSensorDataCSV()); + logToSD(); // Turn off the LED if (_ledPin >= 0) digitalWrite(_ledPin, LOW); diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 0a610e519..9ce509c0a 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -383,8 +383,8 @@ void LoggerEnviroDIY::begin(void) else if(_autoFileName){setFileName();} else setFileName(_fileName); // This just for a nice print-out - // Set up the log file - setupLogFile(); + // Create the log file, adding the default header to it + createLogFile(true); // Setup sleep mode if(_mcuWakePin >= 0){setupSleep();} @@ -465,7 +465,7 @@ void LoggerEnviroDIY::log(void) } // Create a csv data record and save it to the log file - logToSD(generateSensorDataCSV()); + logToSD(); // Turn off the LED if (_ledPin >= 0) digitalWrite(_ledPin, LOW); From 60ca9eb3ae76cdad7c54ab99a6f9bcbb9b2852ed Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 12:58:05 -0400 Subject: [PATCH 31/54] Added missing new line in csv and EnviroDIY header Also made the loggingInterval a consistent uint16_t (it was a mix of uint8_t and float) --- src/LoggerBase.cpp | 17 +++++++++-------- src/LoggerBase.h | 5 ++--- src/LoggerDreamHost.cpp | 2 +- src/LoggerDreamHost.h | 2 +- src/LoggerEnviroDIY.cpp | 8 +++++++- src/LoggerEnviroDIY.h | 5 ++++- 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index c900691f6..56c1022d0 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -38,14 +38,13 @@ volatile bool Logger::startTesting = false; // Initialization - cannot do this in constructor arduino has issues creating // instances of classes with non-empty constructors -Logger::Logger(const char *loggerID, uint8_t loggingIntervalMinutes, +Logger::Logger(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) { _SDCardPin = SDCardPin; _mcuWakePin = mcuWakePin; _loggingIntervalMinutes = loggingIntervalMinutes; - _loggingIntervalSeconds = round(_loggingIntervalMinutes*60); // convert to even seconds _loggerID = loggerID; _autoFileName = false; _isFileNameSet = false; @@ -252,12 +251,12 @@ bool Logger::checkInterval(void) bool retval; uint32_t checkTime = getNowEpoch(); MS_DBG(F("Current Unix Timestamp: "), checkTime, F("\n")); - MS_DBG(F("Logging interval in seconds: "), _loggingIntervalSeconds, F("\n")); - MS_DBG(F("Mod of Logging Interval: "), checkTime % _loggingIntervalSeconds, F("\n")); + MS_DBG(F("Logging interval in seconds: "), (_loggingIntervalMinutes*60), F("\n")); + MS_DBG(F("Mod of Logging Interval: "), checkTime % (_loggingIntervalMinutes*60), F("\n")); MS_DBG(F("Number of Readings so far: "), _numTimepointsLogged, F("\n")); MS_DBG(F("Mod of 120: "), checkTime % 120, F("\n")); - if ((checkTime % _loggingIntervalSeconds == 0 ) or + if ((checkTime % (_loggingIntervalMinutes*60) == 0 ) or (_numTimepointsLogged < 10 and checkTime % 120 == 0)) { // Update the time variables with the current time @@ -290,13 +289,13 @@ bool Logger::checkMarkedInterval(void) { bool retval; MS_DBG(F("Marked Time: "), markedEpochTime, F("\n")); - MS_DBG(F("Logging interval in seconds: "), _loggingIntervalSeconds, F("\n")); - MS_DBG(F("Mod of Logging Interval: "), markedEpochTime % _loggingIntervalSeconds, F("\n")); + MS_DBG(F("Logging interval in seconds: "), (_loggingIntervalMinutes*60), F("\n")); + MS_DBG(F("Mod of Logging Interval: "), markedEpochTime % (_loggingIntervalMinutes*60), F("\n")); MS_DBG(F("Number of Readings so far: "), _numTimepointsLogged, F("\n")); MS_DBG(F("Mod of 120: "), markedEpochTime % 120, F("\n")); if (markedEpochTime != 0 && - ((markedEpochTime % _loggingIntervalSeconds == 0 ) or + ((markedEpochTime % (_loggingIntervalMinutes*60) == 0 ) or (_numTimepointsLogged < 10 and markedEpochTime % 120 == 0))) { // Update the number of readings taken @@ -644,6 +643,7 @@ void Logger::streamSensorDataCSV(Stream *stream) stream->print(F(",")); } } + stream->println(); } @@ -819,6 +819,7 @@ void Logger::logToSD(void) #if defined(STANDARD_SERIAL_OUTPUT) PRINTOUT(F("\n \\/---- Line Saved to SD Card ----\\/ \n")); streamSensorDataCSV(&STANDARD_SERIAL_OUTPUT); + PRINTOUT(F("\r\n")); #endif // Set write/modification date time diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 34f078259..65400e290 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -40,7 +40,7 @@ class Logger { public: // Constructor - Logger(const char *loggerID, uint8_t loggingIntervalMinutes, + Logger(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); @@ -230,8 +230,7 @@ class Logger // Initialization variables int8_t _SDCardPin; int8_t _mcuWakePin; - float _loggingIntervalMinutes; - uint16_t _loggingIntervalSeconds; + uint16_t _loggingIntervalMinutes; const char *_loggerID; bool _autoFileName; bool _isFileNameSet; diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 17ce3575f..8d62e4f6f 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -15,7 +15,7 @@ // ============================================================================ // Constructor -LoggerDreamHost::LoggerDreamHost(const char *loggerID, uint8_t loggingIntervalMinutes, +LoggerDreamHost::LoggerDreamHost(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) : LoggerEnviroDIY(loggerID, loggingIntervalMinutes, SDCardPin, mcuWakePin, inputArray) diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index ebece9f62..e6c92f5ff 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -27,7 +27,7 @@ class LoggerDreamHost : public LoggerEnviroDIY public: // Constructor - LoggerDreamHost(const char *loggerID, uint8_t loggingIntervalMinutes, + LoggerDreamHost(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 9ce509c0a..6ce22c2ae 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -21,7 +21,7 @@ // ============================================================================ // Constructor -LoggerEnviroDIY::LoggerEnviroDIY(const char *loggerID, uint8_t loggingIntervalMinutes, +LoggerEnviroDIY::LoggerEnviroDIY(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) : Logger(loggerID, loggingIntervalMinutes, SDCardPin, mcuWakePin, inputArray) @@ -67,6 +67,12 @@ String LoggerEnviroDIY::generateFileHeader(void) return dataHeader; } +void LoggerEnviroDIY::streamFileHeader(Stream *stream) +{ + stream->print(F("Sampling Feature: ")); + stream->println(_samplingFeature); + Logger::streamFileHeader(stream); +} // This generates a properly formatted JSON for EnviroDIY diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index a3736e1f2..9b774114d 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -26,7 +26,7 @@ class LoggerEnviroDIY : public Logger { public: // Constructor - LoggerEnviroDIY(const char *loggerID, uint8_t loggingIntervalMinutes, + LoggerEnviroDIY(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray); @@ -42,6 +42,9 @@ class LoggerEnviroDIY : public Logger // This adds extra data to the datafile header String generateFileHeader(void); + // This prints a header onto a stream - this removes need to pass around + // very long string objects which can crash the logger + void streamFileHeader(Stream *stream); // This generates a properly formatted JSON for EnviroDIY String generateSensorDataJSON(void); From 45e4048cf39b752bac637c66c53c4a23995b6686 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 13:05:38 -0400 Subject: [PATCH 32/54] stream header must be virtual --- src/LoggerEnviroDIY.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index 9b774114d..2b3b302b1 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -41,10 +41,10 @@ class LoggerEnviroDIY : public Logger void setSamplingFeatureUUID(const char *samplingFeature); // This adds extra data to the datafile header - String generateFileHeader(void); + String generateFileHeader(void) override; // This prints a header onto a stream - this removes need to pass around // very long string objects which can crash the logger - void streamFileHeader(Stream *stream); + void streamFileHeader(Stream *stream) override; // This generates a properly formatted JSON for EnviroDIY String generateSensorDataJSON(void); From 6d187da5e5897fb3a282c8b1f83deea02dc5423b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 14:27:10 -0400 Subject: [PATCH 33/54] Fixed some serial.print vs PRINTOUT --- src/LoggerBase.cpp | 9 +++++---- src/LoggerBase.h | 2 +- src/LoggerDreamHost.cpp | 3 +++ src/LoggerEnviroDIY.cpp | 9 ++++++--- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 56c1022d0..5fd3994b8 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -808,7 +808,8 @@ void Logger::logToSD(void) // First attempt to open the file without creating a new one if (openFile(_fileName, false, false)) goto writeRecord; // Next try to create the file, bail if we couldn't create it - if (openFile(_fileName, true, false)) goto writeRecord; + // Do add a default header! + if (openFile(_fileName, true, true)) goto writeRecord; else return; writeRecord: @@ -969,9 +970,9 @@ void Logger::testingMode() if (_buttonPin >= 0) { enableInterrupt(_buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(_buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); + PRINTOUT(F("Push button on pin ")); + PRINTOUT(_buttonPin); + PRINTOUT(F(" at any time to enter sensor testing mode.\n")); } PRINTOUT(F("Logger setup finished!\n")); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 65400e290..4508e8e1f 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -138,7 +138,7 @@ class Logger virtual String generateFileHeader(void); // This prints a header onto a stream - this removes need to pass around // very long string objects which can crash the logger - void streamFileHeader(Stream *stream); + virtual void streamFileHeader(Stream *stream); // This generates a comma separated list of volues of sensor data - including the time String generateSensorDataCSV(void); diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 8d62e4f6f..316dfd01f 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -212,6 +212,7 @@ void LoggerDreamHost::log(void) if (_modemAttached) { // Connect to the network + MS_DBG(F(" Connecting to the Internet...\n")); if (_logModem->connectInternet()) { if(_dualPost) @@ -224,12 +225,14 @@ void LoggerDreamHost::log(void) postDataDreamHost(); // Sync the clock every 288 readings (1/day at 5 min intervals) + MS_DBG(F(" Running a daily clock sync...\n")); if (_numTimepointsLogged % 288 == 0) { syncRTClock(_logModem->getNISTTime()); } // Disconnect from the network + MS_DBG(F(" Disconnecting from the Internet...\n")); _logModem->disconnectInternet(); } // Turn the modem off diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 6ce22c2ae..077f40502 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -399,9 +399,9 @@ void LoggerEnviroDIY::begin(void) if (_buttonPin >= 0) { enableInterrupt(_buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(_buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); + PRINTOUT(F("Push button on pin ")); + PRINTOUT(_buttonPin); + PRINTOUT(F(" at any time to enter sensor testing mode.\n")); } PRINTOUT(F("Logger setup finished!\n")); @@ -452,18 +452,21 @@ void LoggerEnviroDIY::log(void) if (_modemAttached) { // Connect to the network + MS_DBG(F(" Connecting to the Internet...\n")); if (_logModem->connectInternet()) { // Post the data to the WebSDL postDataEnviroDIY(); // Sync the clock every 288 readings (1/day at 5 min intervals) + MS_DBG(F(" Running a daily clock sync...\n")); if (_numTimepointsLogged % 288 == 0) { syncRTClock(_logModem->getNISTTime()); } // Disconnect from the network + MS_DBG(F(" Disconnecting from the Internet...\n")); _logModem->disconnectInternet(); } // Turn the modem off From 88bef717d7aac8a38a50c9a5dfc7b0a338fd6c0b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 14:44:45 -0400 Subject: [PATCH 34/54] Cleaned up some generate vs stream functions --- src/LoggerDreamHost.cpp | 53 +++++++++++++++++------------- src/LoggerDreamHost.h | 7 ++-- src/LoggerEnviroDIY.cpp | 72 +++++++++++++++++++++++------------------ src/LoggerEnviroDIY.h | 7 ++-- src/LoggerModem.h | 16 +++++---- 5 files changed, 88 insertions(+), 67 deletions(-) diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 316dfd01f..531065746 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -47,24 +47,36 @@ String LoggerDreamHost::generateSensorDataDreamHost(void) } return dhString; } - - -// This generates a fully structured GET request for DreamHost -String LoggerDreamHost::generateDreamHostGetRequest(String fullURL) -{ - String GETstring = String(F("GET ")); - GETstring += String(fullURL); - GETstring += String(F(" HTTP/1.1")); - GETstring += String(F("\r\nHost: swrcsensors.dreamhosters.com")); - GETstring += String(F("\r\n\r\n")); - return GETstring; -} -String LoggerDreamHost::generateDreamHostGetRequest(void) +void LoggerDreamHost::streamSensorDataDreamHost(Stream *stream) { - return generateDreamHostGetRequest(generateSensorDataDreamHost()); + stream->print(String(_DreamHostPortalRX)); + stream->print(String(F("?LoggerID=")) + String(Logger::_loggerID)); + stream->print(String(F("?Loggertime=")) + String(Logger::markedEpochTime - 946684800)); // Correct time from epoch to y2k + + for (int i = 0; i < _internalArray->getVariableCount(); i++) + { + stream->print(String(F("&")) + String(_internalArray->arrayOfVars[i]->getVarCode()) \ + + String(F("=")) + String(_internalArray->arrayOfVars[i]->getValueString())); + } } +// // This generates a fully structured GET request for DreamHost +// String LoggerDreamHost::generateDreamHostGetRequest(String fullURL) +// { +// String GETstring = String(F("GET ")); +// GETstring += String(fullURL); +// GETstring += String(F(" HTTP/1.1")); +// GETstring += String(F("\r\nHost: swrcsensors.dreamhosters.com")); +// GETstring += String(F("\r\n\r\n")); +// return GETstring; +// } +// String LoggerDreamHost::generateDreamHostGetRequest(void) +// { +// return generateDreamHostGetRequest(generateSensorDataDreamHost()); +// } + + // This prints a fully structured GET request for DreamHost to the // specified stream using the specified url. void LoggerDreamHost::streamDreamHostRequest(Stream *stream, String fullURL) @@ -77,18 +89,13 @@ void LoggerDreamHost::streamDreamHostRequest(Stream *stream, String fullURL) } void LoggerDreamHost::streamDreamHostRequest(Stream *stream) { + // Start the request stream->print(String(F("GET "))); - stream->print(String(_DreamHostPortalRX)); - stream->print(String(F("?LoggerID=")) + String(Logger::_loggerID)); - stream->print(String(F("?Loggertime=")) + String(Logger::markedEpochTime - 946684800)); // Correct time from epoch to y2k - - for (int i = 0; i < _internalArray->getVariableCount(); i++) - { - stream->print(String(F("&")) + String(_internalArray->arrayOfVars[i]->getVarCode()) \ - + String(F("=")) + String(_internalArray->arrayOfVars[i]->getValueString())); - } + // Stream the full URL with parameters + streamSensorDataDreamHost(stream); + // Send the rest of the HTTP header stream->print(String(F(" HTTP/1.1"))); stream->print(String(F("\r\nHost: swrcsensors.dreamhosters.com"))); stream->print(String(F("\r\n\r\n"))); diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index e6c92f5ff..617062414 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -36,10 +36,11 @@ class LoggerDreamHost : public LoggerEnviroDIY // This creates all of the URL parameters String generateSensorDataDreamHost(void); + void streamSensorDataDreamHost(Stream *stream); - // This generates a fully structured GET request for DreamHost - String generateDreamHostGetRequest(String fullURL); - String generateDreamHostGetRequest(void); + // // This generates a fully structured GET request for DreamHost + // String generateDreamHostGetRequest(String fullURL); + // String generateDreamHostGetRequest(void); // This prints a fully structured GET request for DreamHost to the // specified stream using the specified url. diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 077f40502..0ab45637c 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -98,26 +98,46 @@ String LoggerEnviroDIY::generateSensorDataJSON(void) jsonString += F("}"); return jsonString; } +void LoggerEnviroDIY::streamSensorDataJSON(Stream *stream) +{ + stream->print(String(F("{"))); + stream->print(String(F("\"sampling_feature\": \""))); + stream->print(String(_samplingFeature)); + F(""); + stream->print(String(F("\", \"timestamp\": \""))); + stream->print(String(Logger::markedISO8601Time) + F("\", ")); + for (int i = 0; i < _internalArray->getVariableCount(); i++) + { + stream->print(String(F("\"")) + _internalArray->arrayOfVars[i]->getVarUUID() + String(F("\": ")) + _internalArray->arrayOfVars[i]->getValueString()); + if (i + 1 != _internalArray->getVariableCount()) + { + stream->print(F(", ")); + } + } -// This generates a fully structured POST request for EnviroDIY -String LoggerEnviroDIY::generateEnviroDIYPostRequest(String enviroDIYjson) -{ - String POSTstring = String(F("POST /api/data-stream/ HTTP/1.1")); - POSTstring += String(F("\r\nHost: data.envirodiy.org")); - POSTstring += String(F("\r\nTOKEN: ")) + String(_registrationToken); - // POSTstring += String(F("\r\nCache-Control: no-cache")); - // POSTstring += String(F("\r\nConnection: close")); - POSTstring += String(F("\r\nContent-Length: ")) + String(enviroDIYjson.length()); - POSTstring += String(F("\r\nContent-Type: application/json\r\n\r\n")); - POSTstring += String(enviroDIYjson); - return POSTstring; -} -String LoggerEnviroDIY::generateEnviroDIYPostRequest(void) -{ - return generateEnviroDIYPostRequest(generateSensorDataJSON()); + stream->print(F("}")); } + +// // This generates a fully structured POST request for EnviroDIY +// String LoggerEnviroDIY::generateEnviroDIYPostRequest(String enviroDIYjson) +// { +// String POSTstring = String(F("POST /api/data-stream/ HTTP/1.1")); +// POSTstring += String(F("\r\nHost: data.envirodiy.org")); +// POSTstring += String(F("\r\nTOKEN: ")) + String(_registrationToken); +// // POSTstring += String(F("\r\nCache-Control: no-cache")); +// // POSTstring += String(F("\r\nConnection: close")); +// POSTstring += String(F("\r\nContent-Length: ")) + String(enviroDIYjson.length()); +// POSTstring += String(F("\r\nContent-Type: application/json\r\n\r\n")); +// POSTstring += String(enviroDIYjson); +// return POSTstring; +// } +// String LoggerEnviroDIY::generateEnviroDIYPostRequest(void) +// { +// return generateEnviroDIYPostRequest(generateSensorDataJSON()); +// } + + // This prints a fully structured post request for EnviroDIY to the // specified stream using the specified json. void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream, String enviroDIYjson) @@ -133,7 +153,8 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream, String enviroDIYjso } void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) { - // first we need to calculate how long the json string is going to be + // First we need to calculate how long the json string is going to be + // This is needed for the "Content-Length" header int jsonLength = 22; // {"sampling_feature": " jsonLength += 36; // sampling feature UUID jsonLength += 17; // ", "timestamp": " @@ -152,6 +173,7 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) } jsonLength += 1; // } + // Stream the HTTP headers for the post request stream->print(String(F("POST /api/data-stream/ HTTP/1.1"))); stream->print(String(F("\r\nHost: data.envirodiy.org"))); stream->print(String(F("\r\nTOKEN: ")) + String(_registrationToken)); @@ -159,21 +181,9 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) // stream->print(String(F("\r\nConnection: close"))); stream->print(String(F("\r\nContent-Length: ")) + String(jsonLength)); stream->print(String(F("\r\nContent-Type: application/json\r\n\r\n"))); - stream->print(String(F("{\"sampling_feature\": \""))); - stream->print(String(_samplingFeature)); + F(""); - stream->print(String(F("\", \"timestamp\": \""))); - stream->print(String(Logger::markedISO8601Time) + F("\", ")); - - for (int i = 0; i < _internalArray->getVariableCount(); i++) - { - stream->print(String(F("\"")) + _internalArray->arrayOfVars[i]->getVarUUID() + String(F("\": ")) + _internalArray->arrayOfVars[i]->getValueString()); - if (i + 1 != _internalArray->getVariableCount()) - { - stream->print(F(", ")); - } - } - stream->print(F("}")); + // Stream the JSON itself + streamSensorDataJSON(stream); } diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index 2b3b302b1..efcbf28a7 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -48,10 +48,11 @@ class LoggerEnviroDIY : public Logger // This generates a properly formatted JSON for EnviroDIY String generateSensorDataJSON(void); + void streamSensorDataJSON(Stream *stream); - // This generates a fully structured POST request for EnviroDIY - String generateEnviroDIYPostRequest(String enviroDIYjson); - String generateEnviroDIYPostRequest(void); + // // This generates a fully structured POST request for EnviroDIY + // String generateEnviroDIYPostRequest(String enviroDIYjson); + // String generateEnviroDIYPostRequest(void); // This prints a fully structured post request for EnviroDIY to the // specified stream using the specified json. diff --git a/src/LoggerModem.h b/src/LoggerModem.h index dc0619419..c372dc908 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -44,20 +44,22 @@ #define MODEM_NAME "SIMCom SIM868" #elif defined(TINY_GSM_MODEM_SIM900) #define MODEM_NAME "SIMCom SIM900" -#elif defined(TINY_GSM_MODEM_A6) - #define MODEM_NAME "AI-Thinker A6" -#elif defined(TINY_GSM_MODEM_A7) - #define MODEM_NAME "AI-Thinker A7" #elif defined(TINY_GSM_MODEM_UBLOX) #define MODEM_NAME "u-blox Cellular" -#elif defined(TINY_GSM_MODEM_M590) - #define MODEM_NAME "Neoway M590" #elif defined(TINY_GSM_MODEM_M95) #define MODEM_NAME "Quectel M95" #elif defined(TINY_GSM_MODEM_BG96) #define MODEM_NAME "Quectel BG96" +#elif defined(TINY_GSM_MODEM_A6) + #define MODEM_NAME "AI-Thinker A6" +#elif defined(TINY_GSM_MODEM_A7) + #define MODEM_NAME "AI-Thinker A7" +#elif defined(TINY_GSM_MODEM_M590) + #define MODEM_NAME "Neoway M590" +#elif defined(TINY_GSM_MODEM_MC60) + #define MODEM_NAME "Quectel MC60E" #elif defined(TINY_GSM_MODEM_MC60) - #define MODEM_NAME "Quectel MC60" + #define MODEM_NAME "Quectel MC60E" #elif defined(TINY_GSM_MODEM_ESP8266) #define MODEM_NAME "ESP8266" #elif defined(TINY_GSM_MODEM_XBEE) From f08b6fcb3411cde77afdaeb9e607724533113964 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 14:45:41 -0400 Subject: [PATCH 35/54] Update ReadMe, bumped version --- README.md | 141 ++++++++++++++++++++++----------------------- library.json | 2 +- library.properties | 2 +- 3 files changed, 71 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 6206aefa8..3328843a6 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ The "[single_sensor](https://github.com/EnviroDIY/ModularSensors/tree/master/exa Having a unified set of functions to access many sensors allows us to quickly poll through a list of sensors to get all results quickly. To this end, "VariableArray.h" adds the class "VariableArray" with functions to use on an array of pointers to variable objects. ### Functions Available for a VariableArray Object: -- **init(int variableCount, Variable variableList[])** - This initializes the variable array. This must be called in the setup() function. Note that the objects in the variable list must be pointers, not the variable objects themselves. The pointers may be to calculated or measured variable objects. +- **VariableArray(int variableCount, Variable variableList[])** - This is the constructor; it creates the variable array object. Note that the objects in the variable list must be pointers, not the variable objects themselves. The pointers may be to calculated or measured variable objects. - **getVariableCount()** - Simply returns the number of variables. - **getSensorCount()** - Returns the number of independent sensors. This will often be different from the number of variables because many sensors can return multiple variables. - **setupSensors()** - This sets up all of the variables in the array and their respective sensors by running all of their setup() functions. If a sensor doesn't respond to its setup command, the command is called 5 times in attempt to make a connection. If all sensors are set up successfully, returns true. @@ -231,34 +231,35 @@ Having a unified set of functions to access many sensors allows us to quickly po - **sensorsPowerDown()** - This cuts power to all sensors, skipping repeated sensors. No return. - **updateAllSensors()** - This updates all sensor values, skipping repeated sensors. Returns true. Does NOT return any values. - **printSensorData(Stream stream)** - This prints current sensor values along with meta-data to a stream (either hardware or software serial). By default, it will print to the first Serial port. Note that the input is a pointer to a stream instance so to use a hardware serial instance you must use an ampersand before the serial name (ie, &Serial1). -- **generateSensorDataCSV()** - This returns an Arduino String containing comma separated list of sensor values. This string does _NOT_ contain a time stamp of any kind. ### VariableArray Examples: -To use the VariableArray module, you must first create the array of pointers. This should be done outside of the setup() or loop() functions. Remember that you must create a new instance for each variable and each sensor. The sensor functions for sensors within a variable array take advantage of all of the timestamps and status bits within the sensor object to minimize the amount of time that all sensors are powered and the processor is awake. That is, the first sensor to be warmed up will be set up or activated first; the first sensor to stabilize will be asked for values first. All calculations for any calculated variables happen after all the sensor updating has finished. The order of the variables within the array should not matter, though for code readability, I strongly suggest putting all the variables attached to a single sensor next to each other in the array. +To use the VariableArray module, you must first create the array of pointers. This should be done outside of the setup() or loop() functions. Remember that for measured variables you must first create a new sensor instance and then one or more new variable instances for that sensor (depending on how many values it can return.) The sensor functions for sensors within a variable array take advantage of all of the timestamps and status bits within the sensor object to minimize the amount of time that all sensors are powered and the processor is awake. That is, the first sensor to be warmed up will be set up or activated first; the first sensor to stabilize will be asked for values first. All calculations for any calculated variables happen after all the sensor updating has finished. The order of the variables within the array should not matter, though for code readability, I strongly suggest putting all the variables attached to a single sensor next to each other in the array. The asterisk must be put in front of the variable name to indicate that it is a pointer to your variable object. With many variables, it is easier to create the object and the pointer to it all at once in the variable array. This can be done using the "new" keyword like so: ```cpp -// Create a new VariableArray object -VariableArray myVars; // Create new variable objects in an array named "variableList" using the "new" keyword // UUID's and customVarCodes are optional Variable \*variableList[] = { new Sensor1_Variable1(&parentSensor1, "UUID", "customVarCode1"), new Sensor1_Variable2(&parentSensor1, "UUID", "customVarCode2"), - new Sensor2_Variable1(&parentSensor2, "UUID", "customVarCode3"), ... new SensorX_VariableX(&parentSensorx, "UUID", "customVarCode4") }; -// Optionally, count the number of variables in the array +// Count the number of variables in the array (you can count them manually, too) int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray myVarArray(variableCount, variableList); ``` You can also create and name variable pointer objects outside of the array and then reference those pointers inside of the array like so: ```cpp // Create measured variable objects and return pointers to them +// NOTE: We are actually creating subclasses of variables here (tied to particular +// sensors) but returning pointers to the variable superclass as required for +// the variable array. Variable *var1 = new sensor1_var1(&parentSensor1, "UUID", "customVarCode1"); Variable *var2 = new sensor1_var2(&parentSensor1, "UUID", "customVarCode1"); Variable *var3 = new sensor2_var1(&parentSensor2, "UUID", "customVarCode1"); @@ -273,13 +274,9 @@ Variable *calcVar4 = new Variable(calculationFunction, "varName", "UUID", "varCode"); // Continue creating variables.. -Variable *varX = new sensorX_varX(&parentSensor2, "UUID", "customVarCode1"); +Variable *varX = new sensorX_varX(&parentSensorX, "UUID", "customVarCodeX"); -// Create a new VariableArray object -VariableArray myVars; - -// Create new variable objects in an array named "variableList" using the "new" keyword -// UUID's and customVarCodes are optional +// Put the already created variable type pointers into an array Variable \*variableList[] = { var1, var2, @@ -288,17 +285,17 @@ Variable \*variableList[] = { ... varX }; -// Optionally, count the number of variables in the array +// Count the number of variables in the array (you can count them manually, too) int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray myVarArray(variableCount, variableList); ``` Creating the variable pointers outside of the array is particularly helpful when you want to reference the same variables in multiple arrays or you want to do any post measurement calculations on the variables. -Once you have created the array of pointers, you can initialize the VariableArray module and setup all of the sensors at once in the setup function: +Once you have created the array of pointers, you can initialize the VariableArray module and setup all of the variables and their parent sensors at once in the setup function: ```cpp -// Initialize the sensor array; -myVars.init(variableCount, variableList); // Set up all the sensors AND variables (BOTH are done by this function) myVars.setupSensors(); ``` @@ -306,38 +303,49 @@ myVars.setupSensors(); You can then get values or variable names for all of the sensors within the loop with calls like: ```cpp -// Update the sensor value(s) -myVars.updateAllSensors(); +// Send power to all of the sensors +myVarArray.sensorsPowerUp(); +// Wake up all of the sensors +myVarArray.sensorsWake(); +// Update the values from all attached sensors +myVarArray.updateAllSensors(); +// Put sensors to sleep +myVarArray.sensorsSleep(); +// Cut sensor power +myVarArray.sensorsPowerDown(); // Print the data to the screen -myVars.printSensorData(); +myVarArray.printSensorData(); ``` ## Basic Logger Functions -Our main reason to unify the output from many sensors and variables is to easily log the data to an SD card and to send it to a live streaming data receiver, like the [MonitorMyWatershed/EnviroDIY data portal](http://data.envirodiy.org/). There are several modules available to use with the sensors to log data and stream data: LoggerBase, LoggerEnviroDIY, and LoggerModem. The classes Logger (in LoggerBase) is a sub-class of VariableArray and LoggerEnviroDIY (in LoggerEnviroDIY) is in-turn a sub-class of Logger. They contain all of the functions available to a VariableArray as described above. The Logger class adds the abilities to communicate with a real time clock, to put the board into deep sleep between readings to conserver power, and to write the data from the sensors to a csv file on a connected SD card. The LoggerModem module is essentially a wrapper for [TinyGSM](https://github.com/EnviroDIY/TinyGSM) which adds quick functions for turning modem on and off to save power and to synchronize the real-time clock with the [NIST Internet time service](https://www.nist.gov/pml/time-and-frequency-division/services/internet-time-service-its). The LoggerEnviroDIY class uses LoggerModem to add the ability to properly format and send data to the [EnviroDIY data portal](http://data.envirodiy.org/). +Our main reason to unify the output from many sensors and variables is to easily log the data to an SD card and to send it to a live streaming data receiver, like the [MonitorMyWatershed/EnviroDIY data portal](http://data.envirodiy.org/). There are several modules available to use with the sensors to log data and stream data: LoggerBase, LoggerEnviroDIY, and LoggerModem. The classes Logger (in LoggerBase) is a parent class for LoggerEnviroDIY (in LoggerEnviroDIY). Both also contain an internal VariableArray object. The Logger class has the abilities to communicate with a real time clock, to put the board into deep sleep between readings to conserver power, and to write the data from the sensors to a csv file on a connected SD card. The LoggerEnviroDIY class can also have a LoggerModem attached, synchronize the time to NIST, and format and send data to the [EnviroDIY data portal](http://data.envirodiy.org/). The LoggerModem module is essentially a wrapper for [TinyGSM](https://github.com/EnviroDIY/TinyGSM) which adds quick functions for turning modem on and off to save power and to synchronize the real-time clock with the [NIST Internet time service](https://www.nist.gov/pml/time-and-frequency-division/services/internet-time-service-its). ### Functions Available for a Logger Object: #### Setup and initialization functions: -- **init(int SDCardPin, int mcuWakePin, int variableCount, Variable \*variableList[], float loggingIntervalMinutes, const char \*loggerID = 0)** - Initializes the logger object. Must happen within the setup function. Note that the variableList[], and loggerID are pointers. The SDCardPin is the pin of the chip select/slave select for the SPI connection to the SD card. +- **Logger(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray)** - The constructor; creates the logger object. Note that the variableList[], and loggerID are pointers. The SDCardPin is the pin of the chip select/slave select for the SPI connection to the SD card. - NOTE regarding *loggingIntervalMinutes*: For the first 20 minutes that a logger has been powered up for a deployment, the logger will take readings at 2 minute intervals for 10 measurements, to assist with confirming that the deployment is successful. Afterwards, the time between measurements will revert to the number of minutes set with *loggingIntervalMinutes*. - **setAlertPin(int ledPin)** - Optionally sets a pin to put out an alert that a measurement is being logged. This is intended to be a pin with a LED on it so you can see the light come on when a measurement is being taken. +- **setTestingModePin(int buttonPin)** - Optionally sets a pin that is attached to a button or some other interrupt source to force the logger to enter sensor testing mode. #### Timezone functions: - **setTimeZone(int timeZone)** - Sets the timezone that you wish data to be logged in (in +/- hours from UTC). _This must always be set!_ +- **getTimeZone()** - Returns the set timezone. - **setTZOffset(int offset)** - This sets the offset between the built-in clock and the timezone the data should be logged in. If your clock is set in UTC, then the TZOffset should be the same as the TimeZone. For example, if you would like your clock to be set in UTC but your data should be output in Eastern Standard Time, both setTimeZone and setTZOffset should be called with -5. On the other hand, if your clock is already set EST, you do not need to call the setTZOffset function (or can call it with 0). A note about timezones: It is possible to create multiple logger objects in your code if you want to log different sensors at different intervals, _but every logger object will always have the same timezone and timezone offset_. If you attempt to call these functions more than once for different loggers, whatever value was called last will apply to every logger. +- **getTZOffset()** - Returns the set timezone offset. #### Functions to access the clock in proper format and time zone: - **syncRTClock(uint32_t timestamp)** - This synchronizes the real time clock with the provided timestamp, which should be a unix timestamp _in UTC_. -- **getNow()** - This gets the current epoch time (unix timestamp - number of seconds since Jan 1, 1970) and corrects it for the specified logger time zone offset. +- **getNowEpoch()** - This gets the current epoch time (unix timestamp - number of seconds since Jan 1, 1970) and corrects it for the specified logger time zone offset. - **formatDateTime_ISO8601(DateTime dt)** - Formats a DateTime object into an ISO8601 formatted Arduino String. - **formatDateTime_ISO8601(uint32_t unixTime)** - Formats a unix timestamp into an ISO8601 formatted Arduino String. -- **checkInterval()** - This returns true if the _current_ time is an even interval of the logging interval, otherwise false. This uses getNow() to get the curernt time. +- **checkInterval()** - This returns true if the _current_ time is an even interval of the logging interval, otherwise false. This uses getNowEpoch() to get the curernt time. - **markTime()** - This sets static variables for the date/time - this is needed so that all data outputs (SD, EnviroDIY, serial printing, etc) print the same time for updating the sensors - even though the routines to update the sensors and to output the data may take several seconds. It is not currently possible to output the instantaneous time an individual sensor was updated, just a single marked time. By custom, this should be called before updating the sensors, not after. If you do not call this function before saving or sending data, there will be no timestamps associated with your data. This is called for you every time the checkInterval() function is run. -- **checkMarkedInterval()** - This returns true if the _marked_ time is an even interval of the logging interval, otherwise false. This uses the static time value set by markTime() to get the time. It does not check the real-time-clock directly. +- **checkMarkedInterval()** - This returns true if the _marked_ time is an even interval of the logging interval, otherwise false. This uses the static time value set by markTime() to get the time. It does not check the current time. #### Functions for the processor sleep modes: @@ -347,29 +355,21 @@ A note about timezones: It is possible to create multiple logger objects in you #### Functions for logging data: -- **setFileName(fileName)** - This sets a specified file name for data to be saved as, if you want to decide on it in advance. Note that you must include the file extention (ie., '.txt') in the file name. If you do not call the setFileName function with a specific name, a csv file name will automatically be generated from the logger id and the current date. +- **setFileName(fileName)** - This sets a specified file name for data to be saved as, if you want to decide on it in advance. Note that you must include the file extension (ie., '.txt') in the file name. If you do not call the setFileName function with a specific name, a csv file name will automatically be generated from the logger id and the current date. - **getFileName()** - This returns the current filename as an Arduino String. -- **setupLogFile()** - This creates a file on the SD card and writes a header to it. It also sets the "file created" time stamp. -- **logToSD(String rec)** - This writes a data line containing "rec" the the SD card and sets the "file modified" timestamp. -- **generateFileHeader()** - This returns and Aruduino String with a comma separated list of headers for the csv. The headers will be ordered based on the order variables are listed in the array fed to the init function. -- **generateSensorDataCSV()** - This returns an Arduino String containing the time and a comma separated list of sensor values. The data will be ordered based on the order variables are listed in the array fed to the init function. +- **createLogFile(String filename, bool writeDefaultHeader = false)** or **createLogFile(bool writeDefaultHeader = false)** - These functions create a file on an SD card and set the created/modified/accessed timestamps in that file. The filename may either be the one automatically generated by the logger id and the date, the one set by setFileName(String), or can be specified in the function. If asked to, these functions will also write a header to the file based on the variable information from the variable array. This can be used to force a logger to create a file with a secondary file name. +- **logToSD(String filename, String rec)** or **logToSD(String rec)** or **logToSD(void)** - These functions create a file on an SD card and set the modified/accessed timestamps in that file. The filename may either be the one automatically generated by the logger id and the date, the one set by setFileName(String), or can be specified in the function. If the file does not already exist, the file will be created. The line to be written to the file can either be specified or will be a comma separated list of the current values of all variables in the variable array. +- **streamFileHeader(Stream \*stream)** - This prints a header for a csv out to an Arduino stream. The header will be ordered based on the order variables are listed in the VariableArray. + - If you would prefer to manually work with and change the header, the function **generateFileHeader()** returns an Aruduino String with a comma separated list of headers for the csv. This header _will_ be a very, very long string. _If the string is too long, it may not be printed or cause the entire program to crash!_ Only try to work directly with the header string for VariableArray's with a small number of variables. +- **streamSensorDataCSV(Stream \*stream)** - This returns an Arduino String containing the time and a comma separated list of sensor values. The data will be ordered based on the order variables are listed in the VariableArray. + - If you would like the manipulate or add to the csv data, **generateSensorDataCSV()** returns an Arduino String containing the same information as is printed streamSensorDataCSV(Stream \*stream). Before using this function, take into account the same warnings as given with generateFileHeader(), although this string will be much, much shorter than the string created by generateFileHeader(). #### Functions for sensor testing and communication debugging: By default, some status and set-up information will be sent to the Serial (for AVR processors) or SerialUSB (for SAMD processors). To stop all print out or to change the port the print out goes to, open ModSensorDebugger.h and change or remove lines 15-21 that define the STANDARD_SERIAL_OUTPUT. There is also a built-in function for "testing" sensors within sensor arrays - that is, continuously displaying current sensor values to test that the sensors are working properly: -- **testingMode()** - Enters a "testing" mode for the sensors. It prints out all of the sensor results for 25 records worth of data with a 5-second delay between readings. The printouts go to whichever serial port is given in the ```#define STANDARD_SERIAL_OUTPUT``` statement. - -Testing mode can be entered directly in a set-up or loop function by calling the ```testingMode()``` function. There is also a function to hold code to wait for a button press to enter test testing mode. I suggest only running this as the very last step of the setup function. -- **checkForTestingMode(int buttonPin)** - This stops everything and waits for five seconds for a button to be pressed to enter allow the user to enter "sensor testing" mode. - -If you would like to be able to enter the testing mode via a button press at any time while the logger is asleep, you can use the testingISR() function to define an interrupt for entering testing mode. Please note that the ISR verifies that you are not in the middle of taking/logging a measurement before beginning the testing mode, so you cannot enter testing mode during that time. Also note that the testing mode will not return any valid results until after the full setup is complete, so don't try to enter testing mode before then. -```cpp -pinMode(pinNumber, INPUT_PULLUP); -enableInterrupt(buttonPin, Logger::testingISR, CHANGE); -``` - +- **testingMode()** - Enters a "testing" mode for the sensors. It prints out all of the sensor results for 25 records worth of data with a 5-second delay between readings. The printouts go to whichever serial port is given in the ```#define STANDARD_SERIAL_OUTPUT``` statement. Testing mode can be entered directly in a set-up or loop function by calling the ```testingMode()``` function. If you have set a pin for testing mode via an interrupt with the setTestingModePin(buttonPin) function, you can also enter testing mode any time except when the logger is already taking a data point by creating an interrupt on that pin (ie, by pushing a button). For more intense _code_ debugging for any individual component of the library (sensor communication, modem communication, variable array functions, etc), open the source file header (\*.h), for that component. Find the line ```// #define DEBUGGING_SERIAL_OUTPUT xxxxx```, where xxxxx is the name of a serial output (ie, Serial or USBSerial). Remove the two comment slashes from that line. Then recompile and upload your code. This will (sometimes dramatically) increase the number of statements going out to the debugging serial port. A few sensors also the line ```// #define DEEP_DEBUGGING_SERIAL_OUTPUT xxxxx```, uncommenting of which will send even more information to the defined port. Note that this type of debugging is intended to help find errors in the code of this library, not problems with the sensors themselves! @@ -382,13 +382,19 @@ For more intense _code_ debugging for any individual component of the library (s A loggerModem serves two functions: First, it communicates with the internet via WiFi or cellular service and sends data to remote services. Second, it acts as a sensor which can return the strength of the WiFi or cellular connection. A loggerModem object is a combination of a [TinyGsm](https://github.com/EnviroDIY/TinyGSM) (modem instance), a TinyGsmClient, and a ModemOnOff to control modem power. -Before creating a loggerModem instance, _you must add one of these lines to the top of your sketch_, before any include statements: - -- ```#define TINY_GSM_MODEM_SIM800``` - for a SIMCom SIM800, SIM900, or variant thereof (including [Sodaq GPRSBees](https://shop.sodaq.com/en/gprsbee.html)) +Before creating a loggerModem instance, _you must define your modem at top of your sketch_, before any include statements. ie: +- ```#define TINY_GSM_MODEM_SIM900``` - for a SIMCom SIM900, or variant thereof (including older [Sodaq GPRSBees](https://shop.sodaq.com/en/gprsbee.html)) +- ```#define TINY_GSM_MODEM_SIM800``` - for a SIMCom SIM800 or variant thereof (including current [Sodaq GPRSBees](https://shop.sodaq.com/en/gprsbee.html)) - ```#define TINY_GSM_MODEM_SIM808``` - for a SIMCom SIM808 (essentially a SIMCom SIM800 with GPS support) -- ```#define TINY_GSM_MODEM_A6``` - for an AI-Thinker A6 or A7 -- ```#define TINY_GSM_MODEM_M590``` - for a Neoway M590 +- ```#define TINY_GSM_MODEM_SIM868``` - for a SIMCom SIM868 (another SIM800 variant with GPS support) - ```#define TINY_GSM_MODEM_UBLOX``` - for most u-blox cellular modems ((LEON-G100, LISA-U2xx, SARA-G3xx, SARA-U2xx, TOBY-L2xx, LARA-R2xx, MPCI-L2xx, or a Digi 3G XBee running in bypass mode) +- ```#define TINY_GSM_MODEM_M95``` - for an Quectel M95 +- ```#define TINY_GSM_MODEM_BG96``` - for an Quectel BG96 +- ```#define TINY_GSM_MODEM_A6``` - for an AI-Thinker A6 +- ```#define TINY_GSM_MODEM_A7``` - for an AI-Thinker A7 +- ```#define TINY_GSM_MODEM_M590``` - for a Neoway M590 +- ```#define TINY_GSM_MODEM_MC60``` - for a Quectel MC60 +- ```#define TINY_GSM_MODEM_MC60E``` - for a Quectel MC60E - ```#define TINY_GSM_MODEM_ESP8266``` - for an ESP8266 using the _default AT command firmware_ - ```#define TINY_GSM_MODEM_XBEE``` - for Digi brand WiFi or Cellular XBee's running in normal (transparent) mode @@ -399,13 +405,14 @@ Then you must create the modem object: loggerModem modem; ``` -See [TinyGSM's documentation](https://github.com/vshymanskyy/TinyGSM/blob/master/README.md) for a full list of all of the chip variants and modules that are supported. +See [TinyGSM's documentation](https://github.com/vshymanskyy/TinyGSM/blob/master/README.md) for a more details about of all of the chip variants and modules that are supported. After defining your modem, set it up using one of these two commands, depending on whether you are using cellular or WiFi communication: - **setupModem(Stream modemStream, int vcc33Pin, int modemStatusPin, int modemSleepRqPin, ModemSleepType sleepType, const char \*APN)** - Sets up the internet communcation with a cellular modem. Note that the modemStream and APN should be pointers. Use -1 for any pins that are not connected. - **setupModem(Stream modemStream, int vcc33Pin, int modemStatusPin, int modemSleepRqPin, ModemSleepType sleepType, const char \*ssid, const char \*pwd)** - Sets up the internet communication with a WiFi modem. Note that the modemStream, ssid, and password should be pointers. Use -1 for any pins that are not connected. -- The **vcc33Pin** is the pin that controls whether or not the modem itself is powered. Use -1 if your modem is always receiving power from your logger board or if you want to control modem power independently. +- The **vcc33Pin** is the pin that controls whether or not the modem itself is powered. Use -1 if your modem is always receiving power or if you want to control modem power independently. + - NOTE: _Many_ modem chips require more power than the 0.5A that most Arduino-style boards can provide! The power draw is particularly high during network connection and sending. Some chips require up to 2.5A. _Know your modem's specs!_ If it requires more power than your board can provide, ensure that the modem has an alternate battery connection or power source! - The **modemStatusPin** is the pin that indicates whether the modem is turned on and it is clear to send data. If you use -1, the modem is assumed to always be ready. - The **modemSleepRqPin** is the _pin_ used to put the modem to sleep or to wake it up. - The **ModemSleepType** controls _how the modemSleepRqPin is used_ to put the modem to sleep between readings. @@ -437,22 +444,21 @@ Variable *modemSinalPct = Modem_SignalPercent(&modem, "UUID", "customVarCode"); The modem does not behave quite the same as all the other sensors do, though. Setup must be done with the ```setupModem(...)``` function; the normal ```setup()``` function does not do anything. The ```powerUp()``` and ```powerDown()``` functions also do not work, the modem will only go on with the ```modemPowerUp()``` function and off with the ```modemPowerDown()``` function. -Note for GPRSBee modems: To start the modem you will need to power the logger board off, connect the battery to the logger board, and finally attach the modem to the logger board. Then you may power the board and run your sketch. We have found that attaching a GPRSBee modem to power in a different sequence results in the modem reporting zero signal strength. Note, the Mayfly connected to a computer via USB does not supply sufficient power to the GPRSBee. If the community finds this true for other modems, please let us know. +Special note for Sodaq GPRSBee modems: To start the modem you will need to power the logger board off, connect the battery to the logger board, and finally attach the modem to the logger board. Then you may power the board and run your sketch. We have found that attaching a GPRSBee modem to power in a different sequence results in the modem reporting zero signal strength. ### Additional Functions Available for a LoggerEnviroDIY Object: These functions attach a modem and set up the required registration token and sampling feature UUID for the EnviroDIY web streaming data loader API. **All three** functions must be called before calling any of the other EnviroDIYLogger functions. You *must* also add the correct variable UUID's to the constructors for each variable you are using. All of the UUID and token values can be obtained after registering at http://data.envirodiy.org/. -- **attachModem(loggerModem &modem)** - Attaches a loggerModem to the logger, which the logger then can use to send data to the internet. See [Modem and Internet Functions](#Modem) for more information on how the modem must be set up before it is attached to the logger. You must include an ampersand to tie in the already created modem! +- **attachModem(loggerModem &modem)** - Attaches a loggerModem to the logger, which the logger then can use to send data to the internet. See [Modem and Internet Functions](#Modem) for more information on how the modem must be set up before it is attached to the logger. You must include an ampersand to tie in the already created modem! If you do not attach a modem, you cannot send data to The EnviroDIY data portal! - **setToken(const char \*registrationToken)** - Sets the registration token to access the EnviroDIY streaming data loader API. Note that the input is a pointer to the registrationToken. - **setSamplingFeatureUUID(const char \*samplingFeatureUUID)** - Sets the universally unique identifier (UUID or GUID) of the sampling feature. Note that the input is a pointer to the samplingFeatureUUID. -Because sending data to EnviroDIY depends on having some sort of modem or internet connection, there is a modem object created within the LoggerEnviroDIY Object. To set up that modem object, you still need to call the functions listed in the LoggerModem section, but you need to add an extra "modem." before the function name to call the internal modem object. You do not need to separately create the object. - -Within the loop, these two functions will then format and send out data: +Within the loop, these functions can then format and send out data: -- **generateSensorDataJSON()** - Generates a properly formatted JSON string to go to the EnviroDIY streaming data loader API. -- **postDataEnviroDIY()** - Creates proper headers and sends data to the EnviroDIY data portal. Depends on the modem support module. Returns an HTML response code. +- **streamSensorDataJSON(Stream \*stream)** - Prints a properly formatted EnviroDIY datqa portal JSON string to the selected Arduino stream. + - If you would like the manipulate or add to the csv data, **generateSensorDataJSON()** returns an Arduino String containing the same information as is printed by streamSensorDataJSON(Stream \*stream). Keep in mind, the JSON is likely to be a very long string and _may crash your program_. Only use generateSensorDataJSON() when working with a small variable array +- **postDataEnviroDIY(String enviroDIYjson = "");** - Creates proper HTTP headers and sends the entered JSON to the EnviroDIY data portal. Depends on the having a modem attached. Returns an HTML response code. If you do not enter a JSON, the streamSensorDataJSON(Stream \*stream) function will be used internally to generate one. Please keep in mind when attempting to enter a String JSON that very long strings _may crash your program_. ### Logger Examples: @@ -471,20 +477,20 @@ Logger logger; // Import Logger Module #include // Create a new logger instance -LoggerEnviroDIY EnviroDIYLogger; +LoggerEnviroDIY EnviroDIYLogger(loggerID, loggingIntervalMinutes, SDCardPin, mcuWakePin, inputArray); ``` -_Within the setup function_, you must then initialize the logger and then run the logger setup. For the EnviroDIY logger, you must also set up the communication. (Please note that these are shown with default values.): +_Within the setup function_, you must then set the logger time zones and attach informational pins. For the EnviroDIY logger, you must also set up the communication.: ```cpp // Set the time zone and offset from the RTC logger.setTimeZone(timeZone); logger.setTZOffset(offset); -// Initialize the logger -logger.init(SDCardPin, mcuWakePin, variableCount, variableList, loggingIntervalMinutes, loggerID); // OPTIONAL - specify a pin to give an alert when a measurement is taken // This should generally be a pin with an LED setAlertPin(int ledPin); +// OPTIONAL - specify a pin for entering testing mode +setTestingModePin(int buttonPin); // Begin the logger; logger.begin(); ``` @@ -495,11 +501,11 @@ logger.begin(); // Set the time zone and offset from the RTC EnviroDIYLogger.setTimeZone(timeZone); EnviroDIYLogger.setTZOffset(offset); -// Initialize the logger -EnviroDIYLogger.init(SDCardPin, mcuWakePin, variableCount, variableList, loggingIntervalMinutes, loggerID); // OPTIONAL - specify a pin to give an alert when a measurement is taken // This should generally be a pin with an LED setAlertPin(ledPin); +// OPTIONAL - specify a pin for entering testing mode +setTestingModePin(int buttonPin); // Set up the communication with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeature(samplingFeature); @@ -511,20 +517,11 @@ modem.setupModem(modemStream, vcc33Pin, modemStatusPin, modemSleepRqPin, sleepTy // Attach the modem to the logger EnviroDIYLogger.attachModem(&modem); -// Connect to the network -if (modem.connectInternet()) -{ - // Synchronize the RTC - EnviroDIYLogger.syncRTClock(); -} -// Disconnect from the network -modem.disconnectInternet(); - // Begin the logger; EnviroDIYLogger.begin(); ``` -_Within the main loop function_, all logging and sending of data can be done using a single program line. Because the built-in log functions already handle sleeping and waking the board processor, **there cannot be nothing else within the loop function.** +_Within the main loop function_, all logging and sending of data can be done using a single program line. Because the built-in log functions already handle sleeping and waking the board processor, **there cannot be nothing else within the loop function.** This is a wonderful helper if you are setting up your logger to do only the "normal" things. Please keep in mind, _this is not the only option_. ```cpp void loop() @@ -553,7 +550,7 @@ If you would like to do other things within the loop function, you should access - After updating the sensors, then call any functions you want to send/print/save data. - Finish by putting the logger back to sleep, if desired, with ```systemSleep()```. -The [double_logger example program](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/double_logger) demonstrates using a custom loop function in order to log two different groups of sensors at different logging intervals. The [baro_rho_correction example program](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/baro_rho_correction) demonstrates using a custom loop function in order to create calculated variables before saving the data and sending it to the EnviroDIY data portal. The [data_saving example program](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/data_saving) shows using a custom loop in order to save cellular data by saving data from many variables on the SD card, but only sending a portion of the data to the EnviroDIY data portal. +The [double_logger example program](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/double_logger) demonstrates using a custom loop function in order to log two different groups of sensors at different logging intervals. The [data_saving example program](https://github.com/EnviroDIY/ModularSensors/tree/master/examples/data_saving) shows using a custom loop in order to save cellular data by saving data from many variables on the SD card, but only sending a portion of the data to the EnviroDIY data portal. ## Available sensors diff --git a/library.json b/library.json index 97d66f9af..ad71251e2 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "EnviroDIY_ModularSensors", - "version": "0.12.0", + "version": "0.12.1", "description": "A library that allows access to multiple sensors through a unified interface. This allows the user to simply access many sensors to log the data or send the data to data repositories like the EnviroDIY data portal.", "keywords": "modular, sensor, sensors, datalogger, logger, low power, sleeping, EnviroDIY, ModularSensors, Mayfly, WikiWatershed", "platforms": "atmelavr, atmelsam", diff --git a/library.properties b/library.properties index 01058c1d8..80655887d 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=EnviroDIY_ModularSensors -version=0.12.0 +version=0.12.1 author=Sara Damiano , Shannon Hicks maintainer=Sara Damiano sentence=A library that allows access to multiple sensors through a unified interface. From b0ee96a67dba11d91c608c05acf07fa7afe34c36 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 15:30:54 -0400 Subject: [PATCH 36/54] Minor example rearranging I like the logger info better at the top, even if we create the logger at the bottom. --- examples/DRWI_CitSci/DRWI_CitSci.ino | 23 ++-- examples/DRWI_NoCellular/DRWI_NoCellular.ino | 24 ++-- .../baro_rho_correction.ino | 22 ++- examples/data_saving/data_saving.ino | 36 +++-- examples/double_logger/double_logger.ino | 64 ++++----- .../logging_to_EnviroDIY.ino | 20 ++- .../logging_to_EnviroDIY_Zero.ino | 22 ++- examples/simple_logging/simple_logging.ino | 21 ++- library.json | 2 +- library.properties | 2 +- sensor_tests/AnthonyTest2/AnthonyTest2.ino | 126 +++++++++++------- 11 files changed, 187 insertions(+), 175 deletions(-) diff --git a/examples/DRWI_CitSci/DRWI_CitSci.ino b/examples/DRWI_CitSci/DRWI_CitSci.ino index e50b84043..29bbc70b9 100644 --- a/examples/DRWI_CitSci/DRWI_CitSci.ino +++ b/examples/DRWI_CitSci/DRWI_CitSci.ino @@ -29,9 +29,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include // for external and pin change interrupts #include - +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "DWRI_CitSci.ino"; +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -131,17 +139,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance LoggerDreamHost EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); @@ -208,11 +205,11 @@ void setup() // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); EnviroDIYLogger.setAlertPin(greenLED); + EnviroDIYLogger.setTestingModePin(buttonPin); // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - EnviroDIYLogger.setTestingModePin(buttonPin); // Set up the connection with DreamHost EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); diff --git a/examples/DRWI_NoCellular/DRWI_NoCellular.ino b/examples/DRWI_NoCellular/DRWI_NoCellular.ino index 2a44c7b07..c4fed82ca 100644 --- a/examples/DRWI_NoCellular/DRWI_NoCellular.ino +++ b/examples/DRWI_NoCellular/DRWI_NoCellular.ino @@ -22,8 +22,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "DRWI_NoCellular.ino"; +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -106,17 +115,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance Logger logger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); @@ -173,7 +171,7 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Set an alert pin + // Set pins for alerts and entering testing mode logger.setAlertPin(greenLED); logger.setTestingModePin(buttonPin); @@ -190,5 +188,3 @@ void loop() // Log the data logger.log(); } - -EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index e7f599634..873ff7145 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -30,8 +30,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "baro_rho_correction.ino"; +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -49,7 +58,7 @@ const int8_t wakePin = A7; // Interrupt/Alarm pin to wake from sleep const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be defined!) // Create and return the processor "sensor" -const char *MFVersion = "v0.5b"; +const char *MFVersion = "v0.5"; ProcessorStats mayfly(MFVersion) ; // Create the battery voltage and free RAM variable objects for the Y504 and return variable-type pointers to them Variable *mayflyBatt = new ProcessorStats_Batt(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"); @@ -281,17 +290,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index f6da9d4fe..3d32b8a50 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -30,8 +30,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "data_saving.ino"; +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -212,6 +221,8 @@ Variable *variableList_complete[] = { int variableCount_complete = sizeof(variableList_complete) / sizeof(variableList_complete[0]); // Create the VariableArray object VariableArray arrayComplete(variableCount_complete, variableList_complete); +// Create the new logger instance +LoggerEnviroDIY loggerComplete(LoggerID, loggingInterval, sdCardPin, wakePin, &arrayComplete); // ========================================================================== @@ -233,20 +244,7 @@ Variable *variableList_toGo[] = { int variableCount_toGo = sizeof(variableList_toGo) / sizeof(variableList_toGo[0]); // Create the VariableArray object VariableArray arrayToGo(variableCount_toGo, variableList_toGo); - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create TWO new logger instances -// one is a simple logger with all variables -// one is an enviroDIY logger with an abbreviated list of variables -LoggerEnviroDIY loggerComplete(LoggerID, loggingInterval, sdCardPin, wakePin, &arrayComplete); +// Create the new logger instance LoggerEnviroDIY loggerToGo(LoggerID, loggingInterval,sdCardPin, wakePin, &arrayToGo); @@ -368,19 +366,19 @@ void loop() // we will explicitly start and end the serial connection in the loop. modbusSerial.begin(9600); - // Send power to all of the sensors + // Send power to all of the sensors (do this directly on the VariableArray) Serial.print(F("Powering sensors...\n")); arrayComplete.sensorsPowerUp(); - // Wake up all of the sensors + // Wake up all of the sensors (do this directly on the VariableArray) Serial.print(F("Waking sensors...\n")); arrayComplete.sensorsWake(); - // Update the values from all attached sensors + // Update the values from all attached sensors (do this directly on the VariableArray) Serial.print(F("Updating sensor values...\n")); arrayComplete.updateAllSensors(); - // Put sensors to sleep + // Put sensors to sleep (do this directly on the VariableArray) Serial.print(F("Putting sensors back to sleep...\n")); arrayComplete.sensorsSleep(); - // Cut sensor power + // Cut sensor power (do this directly on the VariableArray) Serial.print(F("Cutting sensor power...\n")); arrayComplete.sensorsPowerDown(); diff --git a/examples/double_logger/double_logger.ino b/examples/double_logger/double_logger.ino index 8572008fa..31028a667 100644 --- a/examples/double_logger/double_logger.ino +++ b/examples/double_logger/double_logger.ino @@ -32,8 +32,18 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "logger_test.ino"; +// Logger ID - since it's the same logger device, we only need one +const char *LoggerID = "XXXXX"; +// The TWO filenames for the different logging intervals +const char *FileName5min = "Logger_5MinuteInterval.csv"; +const char *FileName1min = "Logger_1MinuteInterval.csv"; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -122,43 +132,33 @@ AOSongAM2315 am2315(I2CPower); // ========================================================================== // The two arrays that contains the variables for the different intervals // ========================================================================== -// Create pointers for all of the variables from the sensors -// at the same time putting them into an array +// Create pointers for all of the variables from the sensors recording at 1 +// minute intervals and at the same time putting them into an array Variable *variableList_at1min[] = { new AOSongAM2315_Humidity(&am2315), new AOSongAM2315_Temp(&am2315) // new YOUR_variableName_HERE(&) }; -// Count up the number of pointers in the array +// Count up the number of pointers in the 1-minute array int variableCount1min = sizeof(variableList_at1min) / sizeof(variableList_at1min[0]); -// Create the VariableArray object +// Create the 1-minute VariableArray object VariableArray array1min(variableCount1min, variableList_at1min); +// Create the 1-minute logger instance +Logger logger1min(LoggerID, 1, sdCardPin, wakePin, &array1min); -// Create pointers for all of the variables from the sensors -// at the same time putting them into an array +// Create pointers for all of the variables from the sensors recording at 5 +// minute intervals and at the same time putting them into an array Variable *variableList_at5min[] = { new MaximDS3231_Temp(&ds3231), new ProcessorStats_Batt(&mayfly), new ProcessorStats_FreeRam(&mayfly) // new YOUR_variableName_HERE(&) }; -// Count up the number of pointers in the array +// Count up the number of pointers in the 5-minute array int variableCount5min = sizeof(variableList_at5min) / sizeof(variableList_at5min[0]); -// Create the VariableArray object +// Create the 5-minute VariableArray object VariableArray array5min(variableCount5min, variableList_at5min); - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID - since it's the same logger device, we only need one -const char *LoggerID = "XXXXX"; -// The TWO filenames for the different logging intervals -const char *FileName5min = "Logger_5MinuteInterval.csv"; -const char *FileName1min = "Logger_1MinuteInterval.csv"; -// Your logger's timezone. -const int8_t timeZone = -5; -// Create TWO new logger instances with different logging intervals -Logger logger1min(LoggerID, 1, sdCardPin, wakePin, &array1min); +// Create the 1-minute logger instance Logger logger5min(LoggerID, 5, sdCardPin, wakePin, &array5min); @@ -220,7 +220,7 @@ void setup() // Turn on the modem modem.modemPowerUp(); - // Set up the sensors on both loggers + // Set up the sensors (do this directly on the VariableArray) array1min.setupSensors(); array5min.setupSensors(); @@ -283,19 +283,19 @@ void loop() // Turn on the LED to show we're taking a reading digitalWrite(greenLED, HIGH); - // Send power to all of the sensors + // Send power to all of the sensors (do this directly on the VariableArray) Serial.print(F("Powering sensors...\n")); array1min.sensorsPowerUp(); - // Wake up all of the sensors + // Wake up all of the sensors (do this directly on the VariableArray) Serial.print(F("Waking sensors...\n")); array1min.sensorsWake(); - // Update the values from all attached sensors + // Update the values from all attached sensors (do this directly on the VariableArray) Serial.print(F("Updating sensor values...\n")); array1min.updateAllSensors(); - // Put sensors to sleep + // Put sensors to sleep (do this directly on the VariableArray) Serial.print(F("Putting sensors back to sleep...\n")); array1min.sensorsSleep(); - // Cut sensor power + // Cut sensor power (do this directly on the VariableArray) Serial.print(F("Cutting sensor power...\n")); array1min.sensorsPowerDown(); @@ -316,19 +316,19 @@ void loop() // Turn on the LED to show we're taking a reading digitalWrite(redLED, HIGH); - // Send power to all of the sensors + // Send power to all of the sensors (do this directly on the VariableArray) Serial.print(F("Powering sensors...\n")); array1min.sensorsPowerUp(); - // Wake up all of the sensors + // Wake up all of the sensors (do this directly on the VariableArray) Serial.print(F("Waking sensors...\n")); array1min.sensorsWake(); - // Update the values from all attached sensors + // Update the values from all attached sensors (do this directly on the VariableArray) Serial.print(F("Updating sensor values...\n")); array1min.updateAllSensors(); - // Put sensors to sleep + // Put sensors to sleep (do this directly on the VariableArray) Serial.print(F("Putting sensors back to sleep...\n")); array1min.sensorsSleep(); - // Cut sensor power + // Cut sensor power (do this directly on the VariableArray) Serial.print(F("Cutting sensor power...\n")); array1min.sensorsPowerDown(); diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index a1b0f7be0..d5380a099 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -30,8 +30,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "logging_to_EnviroDIY.ino"; +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -501,17 +510,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index 6dd0e8551..6c670cf06 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -31,9 +31,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "logging_to_EnviroDIY_Zero.ino"; - +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -506,17 +514,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); @@ -602,6 +599,7 @@ void setup() // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); EnviroDIYLogger.setAlertPin(greenLED); + // No button on the feather, so we're not attaching a testingMode pin // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); diff --git a/examples/simple_logging/simple_logging.ino b/examples/simple_logging/simple_logging.ino index fb34ebc2d..99e0393c4 100644 --- a/examples/simple_logging/simple_logging.ino +++ b/examples/simple_logging/simple_logging.ino @@ -21,9 +21,17 @@ THIS CODE IS PROVIDED "AS IS" - NO WARRANTY IS GIVEN. #include +// ========================================================================== +// Data Logger Settings +// ========================================================================== // The name of this file const char *sketchName = "simple_logging.ino"; - +// Logger ID, also becomes the prefix for the name of the data file on SD card +const char *LoggerID = "XXXXX"; +// How frequently (in minutes) to log data +const uint8_t loggingInterval = 5; +// Your logger's timezone. +const int8_t timeZone = -5; // ========================================================================== @@ -444,17 +452,6 @@ Variable *variableList[] = { int variableCount = sizeof(variableList) / sizeof(variableList[0]); // Create the VariableArray object VariableArray varArray(variableCount, variableList); - - -// ========================================================================== -// Data Logger Settings -// ========================================================================== -// Logger ID, also becomes the prefix for the name of the data file on SD card -const char *LoggerID = "XXXXX"; -// How frequently (in minutes) to log data -const uint8_t loggingInterval = 5; -// Your logger's timezone. -const int8_t timeZone = -5; // Create a new logger instance Logger logger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); diff --git a/library.json b/library.json index ad71251e2..4266ad7f2 100644 --- a/library.json +++ b/library.json @@ -1,6 +1,6 @@ { "name": "EnviroDIY_ModularSensors", - "version": "0.12.1", + "version": "0.12.2", "description": "A library that allows access to multiple sensors through a unified interface. This allows the user to simply access many sensors to log the data or send the data to data repositories like the EnviroDIY data portal.", "keywords": "modular, sensor, sensors, datalogger, logger, low power, sleeping, EnviroDIY, ModularSensors, Mayfly, WikiWatershed", "platforms": "atmelavr, atmelsam", diff --git a/library.properties b/library.properties index 80655887d..9f1d8447b 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=EnviroDIY_ModularSensors -version=0.12.1 +version=0.12.2 author=Sara Damiano , Shannon Hicks maintainer=Sara Damiano sentence=A library that allows access to multiple sensors through a unified interface. diff --git a/sensor_tests/AnthonyTest2/AnthonyTest2.ino b/sensor_tests/AnthonyTest2/AnthonyTest2.ino index 829572338..b7a814e34 100644 --- a/sensor_tests/AnthonyTest2/AnthonyTest2.ino +++ b/sensor_tests/AnthonyTest2/AnthonyTest2.ino @@ -36,19 +36,16 @@ https://github.com/EnviroDIY/ModularSensors/commit/7d0d15ae5bc6dddf13adbd735032e // ========================================================================== -// Basic Logger Settings +// Data Logger Settings // ========================================================================== // The name of this file const char *sketchName = "AnthonyTest2.ino"; - // Logger ID, also becomes the prefix for the name of the data file on SD card const char *LoggerID = "AnthonyTest2"; // How frequently (in minutes) to log data const uint8_t loggingInterval = 10; // Your logger's timezone. const int8_t timeZone = -6; // Central Standard Time (CST=-6) -// Create a new logger instance -LoggerEnviroDIY EnviroDIYLogger; // ========================================================================== @@ -65,7 +62,7 @@ const int8_t wakePin = A7; // Interrupt/Alarm pin to wake from sleep // In a SAMD system where you are using the built-in rtc, set wakePin to 1 const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be defined!) -// Create the processor "sensor" +// Create and return the processor "sensor" const char *MFVersion = "v0.5b"; ProcessorStats mayfly(MFVersion) ; @@ -76,35 +73,36 @@ ProcessorStats mayfly(MFVersion) ; HardwareSerial &ModemSerial = Serial1; // The serial port for the modem - software serial can also be used. #if defined(TINY_GSM_MODEM_XBEE) +const long ModemBaud = 9600; // Default for XBee is 9600, I've sped mine up to 57600 const int8_t modemSleepRqPin = 23; // Modem SleepRq Pin (for sleep requests) (-1 if unconnected) const int8_t modemStatusPin = 19; // Modem Status Pin (indicates power status) (-1 if unconnected) const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or off (-1 if unconnected) ModemSleepType ModemSleepMode = modem_sleep_reverse; // How the modem is put to sleep #elif defined(TINY_GSM_MODEM_ESP8266) +const long ModemBaud = 57600; // Default for ESP8266 is 115200, but the Mayfly itself stutters above 57600 const int8_t modemSleepRqPin = 19; // Modem SleepRq Pin (for sleep requests) (-1 if unconnected) const int8_t modemStatusPin = -1; // Modem Status Pin (indicates power status) (-1 if unconnected) const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or off (-1 if unconnected) ModemSleepType ModemSleepMode = modem_always_on; // How the modem is put to sleep +#elif defined(TINY_GSM_MODEM_UBLOX) +const long ModemBaud = 9600; // SARA-U201 default seems to be 9600 +const int8_t modemSleepRqPin = 23; // Modem SleepRq Pin (for sleep requests) (-1 if unconnected) +const int8_t modemStatusPin = 19; // Modem Status Pin (indicates power status) (-1 if unconnected) +const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or off (-1 if unconnected) +ModemSleepType ModemSleepMode = modem_sleep_held; // How the modem is put to sleep + #else +const long ModemBaud = 9600; // SIM800 auto-detects, but I've had trouble making it fast (19200 works) const int8_t modemSleepRqPin = 23; // Modem SleepRq Pin (for sleep requests) (-1 if unconnected) const int8_t modemStatusPin = 19; // Modem Status Pin (indicates power status) (-1 if unconnected) const int8_t modemVCCPin = -1; // Modem power pin, if it can be turned on or off (-1 if unconnected) ModemSleepType ModemSleepMode = modem_sleep_held; // How the modem is put to sleep -#endif // Use "modem_sleep_held" if the DTR pin is held HIGH to keep the modem awake, as with a Sodaq GPRSBee rev6. // Use "modem_sleep_pulsed" if the DTR pin is pulsed high and then low to wake the modem up, as with an Adafruit Fona or Sodaq GPRSBee rev4. // Use "modem_sleep_reverse" if the DTR pin is held LOW to keep the modem awake, as with all XBees. // Use "modem_always_on" if you do not want the library to control the modem power and sleep or if none of the above apply. -#if defined(TINY_GSM_MODEM_ESP8266) -const long ModemBaud = 9600; // Default for ESP8266 is 115200, but the Mayfly itself stutters above 57600 -#elif defined(TINY_GSM_MODEM_SIM800) -const long ModemBaud = 9600; // SIM800 auto-detects, but I've had trouble making it fast (19200 works) -#elif defined(TINY_GSM_MODEM_XBEE) -const long ModemBaud = 9600; // Default for XBee is 9600, I've sped mine up to 57600 -#else -const long ModemBaud = 9600; // Modem baud rate #endif const char *apn = "apn.konekt.io"; // The APN for the gprs connection, unnecessary for WiFi @@ -120,14 +118,17 @@ loggerModem modem; // Maxim DS3231 RTC (Real Time Clock) // ========================================================================== #include +// Create and return the DS3231 sensor object MaximDS3231 ds3231(1); + /**** // ========================================================================== // AOSong AM2315 Digital Humidity and Temperature Sensor // ========================================================================== #include const int8_t I2CPower = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the AOSong AM2315 sensor object AOSongAM2315 am2315(I2CPower); @@ -138,6 +139,7 @@ AOSongAM2315 am2315(I2CPower); const int8_t DHTPower = 22; // Pin to switch power on and off (-1 if unconnected) const int8_t DHTPin = 10; // DHT data pin DHTtype dhtType = DHT11; // DHT type, either DHT11, DHT21, or DHT22 +// Create and return the AOSong DHT sensor object AOSongDHT dht(DHTPower, DHTPin, dhtType); @@ -148,17 +150,21 @@ AOSongDHT dht(DHTPower, DHTPin, dhtType); const int8_t SQ212Power = 22; // Pin to switch power on and off (-1 if unconnected) const int8_t SQ212Data = 2; // The data pin ON THE ADS1115 (NOT the Arduino Pin Number) const uint8_t SQ212_ADS1115Address = 0x48; // The I2C address of the ADS1115 ADC +// Create and return the Apogee SQ212 sensor object ApogeeSQ212 SQ212(SQ212Power, SQ212Data); ***/ + // ========================================================================== // Bosch BME280 Environmental Sensor (Temperature, Humidity, Pressure) // ========================================================================== #include uint8_t BMEi2c_addr = 0x77; // The BME280 can be addressed either as 0x76 or 0x77 const int8_t I2CPower = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the Bosch BME280 sensor object BoschBME280 bme280(I2CPower, BMEi2c_addr); + /*** // ========================================================================== // CAMPBELL OBS 3 / OBS 3+ Analog Turbidity Sensor @@ -172,12 +178,14 @@ const int8_t OBSLowPin = 0; // The low voltage analog pin ON THE ADS1115 (NOT t const float OBSLow_A = 4.0749E+00; // The "A" value (X^2) from the low range calibration const float OBSLow_B = 9.1011E+01; // The "B" value (X) from the low range calibration const float OBSLow_C = -3.9570E-01; // The "C" value from the low range calibration +// Create and return the Campbell OBS3+ LOW RANGE sensor object CampbellOBS3 osb3low(OBS3Power, OBSLowPin, OBSLow_A, OBSLow_B, OBSLow_C, OBS3_ADS1115Address, OBS3numberReadings); // Campbell OBS 3+ High Range calibration in Volts const int8_t OBSHighPin = 1; // The high voltage analog pin ON THE ADS1115 (NOT the Arduino Pin Number) const float OBSHigh_A = 5.2996E+01; // The "A" value (X^2) from the high range calibration const float OBSHigh_B = 3.7828E+02; // The "B" value (X) from the high range calibration const float OBSHigh_C = -1.3927E+00; // The "C" value from the high range calibration +// Create and return the Campbell OBS3+ HIGH RANGE sensor object CampbellOBS3 osb3high(OBS3Power, OBSHighPin, OBSHigh_A, OBSHigh_B, OBSHigh_C, OBS3_ADS1115Address, OBS3numberReadings); @@ -188,6 +196,7 @@ CampbellOBS3 osb3high(OBS3Power, OBSHighPin, OBSHigh_A, OBSHigh_B, OBSHigh_C, OB const char *TMSDI12address = "2"; // The SDI-12 Address of the 5-TM const int8_t SDI12Data = 7; // The pin the 5TM is attached to const int8_t SDI12Power = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the Decagon 5TM sensor object Decagon5TM fivetm(*TMSDI12address, SDI12Power, SDI12Data); @@ -199,6 +208,7 @@ const char *CTDSDI12address = "1"; // The SDI-12 Address of the CTD const uint8_t CTDnumberReadings = 6; // The number of readings to average // const int8_t SDI12Data = 7; // The pin the CTD is attached to // const int8_t SDI12Power = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the Decagon CTD sensor object DecagonCTD ctd(*CTDSDI12address, SDI12Power, SDI12Data, CTDnumberReadings); @@ -210,9 +220,11 @@ const char *ES2SDI12address = "3"; // The SDI-12 Address of the ES2 // const int8_t SDI12Data = 7; // The pin the ES2 is attached to // const int8_t SDI12Power = 22; // Pin to switch power on and off (-1 if unconnected) const uint8_t ES2NumberReadings = 3; +// Create and return the Decagon ES2 sensor object DecagonES2 es2(*ES2SDI12address, SDI12Power, SDI12Data, ES2NumberReadings); ***/ + // ========================================================================== // External Voltage via TI ADS1115 // ========================================================================== @@ -222,16 +234,14 @@ const int8_t VoltData = 0; // The data pin ON THE ADS1115 (NOT the Arduino Pin const float VoltGain = 10; // Default 1/gain for grove voltage divider is 10x const uint8_t Volt_ADS1115Address = 0x48; // The I2C address of the ADS1115 ADC const uint8_t VoltReadsToAvg = 1; // Only read one sample +// Create and return the External Voltage sensor object ExternalVoltage extvolt(VoltPower, VoltData, VoltGain, Volt_ADS1115Address, VoltReadsToAvg); + /*** // ========================================================================== // Maxbotix HRXL Ultrasonic Range Finder // ========================================================================== -#include -const int8_t SonarPower = 22; // Excite (power) pin (-1 if unconnected) -const int8_t Sonar1Trigger = A1; // Trigger pin (a negative number if unconnected) -const int8_t Sonar2Trigger = A2; // Trigger pin (a negative number if unconnected) // Set up a serial port for receiving sonar data - in this case, using software serial // Because the standard software serial library uses interrupts that conflict @@ -245,11 +255,23 @@ const int8_t Sonar2Trigger = A2; // Trigger pin (a negative number if unconnect // Neither hardware serial nor AltSoftSerial require any modifications to // deal with interrupt conflicts. -#include // for the stream communication const int SonarData = 11; // data receive pin + +#include // for the stream communication SoftwareSerial_ExtInts sonarSerial(SonarData, -1); // No Tx pin is required, only Rx -// Now actually creating the sensor object +// #include // for the stream communication +// NeoSWSerial sonarSerial(SonarData, -1); // No Tx pin is required, only Rx +// void NeoSWSISR() +// { +// NeoSWSerial::rxISR( *portInputRegister( digitalPinToPort( SonarData ) ) ); +// } + +#include +const int8_t SonarPower = 22; // Excite (power) pin (-1 if unconnected) +const int8_t Sonar1Trigger = A1; // Trigger pin (a negative number if unconnected) (A1 = 25) +const int8_t Sonar2Trigger = A2; // Trigger pin (a negative number if unconnected) (A2 = 26) +// Create and return the MaxBotix Sonar sensor object MaxBotixSonar sonar1(sonarSerial, SonarPower, Sonar1Trigger) ; MaxBotixSonar sonar2(sonarSerial, SonarPower, Sonar2Trigger) ; @@ -266,11 +288,13 @@ DeviceAddress OneWireAddress4 = {0x28, 0xFF, 0xB6, 0x6E, 0x84, 0x16, 0x05, 0x9B} DeviceAddress OneWireAddress5 = {0x28, 0xFF, 0x3B, 0x07, 0x82, 0x16, 0x03, 0xB3}; const int8_t OneWireBus = A0; // Pin attached to the OneWire Bus (-1 if unconnected) const int8_t OneWirePower = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the Maxim DS18 sensor objects (use this form for a known address) MaximDS18 ds18_1(OneWireAddress1, OneWirePower, OneWireBus); MaximDS18 ds18_2(OneWireAddress2, OneWirePower, OneWireBus); MaximDS18 ds18_3(OneWireAddress3, OneWirePower, OneWireBus); MaximDS18 ds18_4(OneWireAddress4, OneWirePower, OneWireBus); MaximDS18 ds18_5(OneWireAddress5, OneWirePower, OneWireBus); +// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknow address) // MaximDS18 ds18_5(OneWirePower, OneWireBus); @@ -282,6 +306,7 @@ MaximDS18 ds18_5(OneWireAddress5, OneWirePower, OneWireBus); const uint8_t MS5803i2c_addr = 0x76; // The MS5803 can be addressed either as 0x76 or 0x77 const int MS5803maxPressure = 14; // The maximum pressure measurable by the specific MS5803 model const uint8_t MS5803ReadingsToAvg = 1; +// Create and return the MeaSpec MS5803 pressure and temperature sensor object MeaSpecMS5803 ms5803(I2CPower, MS5803i2c_addr, MS5803maxPressure, MS5803ReadingsToAvg); @@ -291,15 +316,18 @@ MeaSpecMS5803 ms5803(I2CPower, MS5803i2c_addr, MS5803maxPressure, MS5803Readings #include // const int8_t I2CPower = 22; // Pin to switch power on and off (-1 if unconnected) const uint8_t MPL115A2ReadingsToAvg = 1; +// Create and return the MPL115A2 barometer sensor object MPL115A2 mpl115a2(I2CPower, MPL115A2ReadingsToAvg); ***/ + // ========================================================================== // External I2C Rain Tipping Bucket Counter // ========================================================================== #include const uint8_t RainCounterI2CAddress = 0x08; // I2C Address for external tip counter const float depthPerTipEvent = 0.2; // rain depth in mm per tip event +// Create and return the Rain Counter sensor object RainCounterI2C tip(RainCounterI2CAddress, depthPerTipEvent); @@ -315,17 +343,20 @@ byte acculevelModbusAddress = 0x01; // The modbus address of KellerAcculevel const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t acculevelNumberReadings = 5; // The manufacturer recommends taking and averaging a few readings +// Create and return the Keller Acculevel sensor object KellerAcculevel acculevel(acculevelModbusAddress, modbusSerial, modbusPower, max485EnablePin, acculevelNumberReadings); + /*** // ========================================================================== // Yosemitech Y504 Dissolved Oxygen Sensor // ========================================================================== #include byte y504modbusAddress = 0x04; // The modbus address of the Y504 -const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) -const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) +// const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) +// const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y504NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Yosemitech Y504 dissolved oxygen sensor object YosemitechY504 y504(y504modbusAddress, modbusSerial, modbusPower, max485EnablePin, y504NumberReadings); @@ -337,6 +368,7 @@ byte y510modbusAddress = 0x0B; // The modbus address of the Y510 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y510NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Y510-B Turbidity sensor object YosemitechY510 y510(y510modbusAddress, modbusSerial, modbusPower, max485EnablePin, y510NumberReadings); @@ -348,6 +380,7 @@ byte y511modbusAddress = 0x1A; // The modbus address of the Y511 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y511NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Y511-A Turbidity sensor object YosemitechY511 y511(y511modbusAddress, modbusSerial, modbusPower, max485EnablePin, y511NumberReadings); @@ -359,6 +392,7 @@ byte y514modbusAddress = 0x14; // The modbus address of the Y514 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y514NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Y514 chlorophyll sensor object YosemitechY514 y514(y514modbusAddress, modbusSerial, modbusPower, max485EnablePin, y514NumberReadings); @@ -370,6 +404,7 @@ byte y520modbusAddress = 0x20; // The modbus address of the Y520 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y520NumberReadings = 5; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Y520 conductivity sensor object YosemitechY520 y520(y520modbusAddress, modbusSerial, modbusPower, max485EnablePin, y520NumberReadings); @@ -381,9 +416,11 @@ byte y532modbusAddress = 0x32; // The modbus address of the Y532 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y532NumberReadings = 1; // The manufacturer actually doesn't mention averaging for this one +// Create and return the Yosemitech Y532 pH sensor object YosemitechY532 y532(y532modbusAddress, modbusSerial, modbusPower, max485EnablePin, y532NumberReadings); ***/ + // ========================================================================== // Yosemitech Y4000 Multiparameter Sonde (DOmgL, Turbidity, Cond, pH, Temp, ORP, Chlorophyll, BGA) // ========================================================================== @@ -392,8 +429,10 @@ byte y4000modbusAddress = 0x05; // The modbus address of the Y4000 // const int8_t modbusPower = 22; // Pin to switch power on and off (-1 if unconnected) // const int8_t max485EnablePin = -1; // Pin connected to the RE/DE on the 485 chip (-1 if unconnected) const uint8_t y4000NumberReadings = 3; // The manufacturer recommends averaging 10 readings, but we take 5 to minimize power consumption +// Create and return the Yosemitech Y4000 multi-parameter sensor object YosemitechY4000 y4000(y4000modbusAddress, modbusSerial, modbusPower, max485EnablePin, y4000NumberReadings); + /*** // ========================================================================== // Zebra Tech D-Opto Dissolved Oxygen Sensor @@ -402,12 +441,16 @@ YosemitechY4000 y4000(y4000modbusAddress, modbusSerial, modbusPower, max485Enabl const char *DOptoDI12address = "5"; // The SDI-12 Address of the Zebra Tech D-Opto // const int8_t SDI12Data = 7; // The pin the D-Opto is attached to // const int8_t SDI12Power = 22; // Pin to switch power on and off (-1 if unconnected) +// Create and return the Zebra Tech DOpto dissolved oxygen sensor object ZebraTechDOpto dopto(*DOptoDI12address, SDI12Power, SDI12Data); ***/ + // ========================================================================== // The array that contains all variables to be logged // ========================================================================== +// Create pointers for all of the variables from the sensors +// at the same time putting them into an array Variable *variableList[] = { // new ApogeeSQ212_PAR(&SQ212, "12345678-abcd-1234-efgh-1234567890ab"), // new AOSongAM2315_Humidity(&am2315, "12345678-abcd-1234-efgh-1234567890ab"), @@ -478,7 +521,12 @@ Variable *variableList[] = { // new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"), // new YOUR_variableName_HERE(&) }; +// Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); +// Create the VariableArray object +VariableArray varArray(variableCount, variableList); +// Create a new logger instance +LoggerEnviroDIY EnviroDIYLogger(LoggerID, loggingInterval, sdCardPin, wakePin, &varArray); // ========================================================================== @@ -526,7 +574,10 @@ void setup() // sonarSerial.begin(9600); // // Allow interrupts for software serial // #if defined SoftwareSerial_ExtInts_h - // enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + // enableInterrupt(SonarData, SoftwareSerial_ExtInts::handle_interrupt, CHANGE); + // #endif + // #if defined NeoSWSerial_h + // enableInterrupt(SonarData, NeoSWSISR, CHANGE); // #endif // Set up pins for the LED's @@ -547,11 +598,6 @@ void setup() // Offset is the same as the time zone because the RTC is in UTC Logger::setTZOffset(timeZone); - // Initialize the logger - EnviroDIYLogger.init(sdCardPin, wakePin, variableCount, variableList, - loggingInterval, LoggerID); - EnviroDIYLogger.setAlertPin(greenLED); - // Setup the logger modem #if defined(TINY_GSM_MODEM_ESP8266) modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, wifiId, wifiPwd); @@ -562,33 +608,17 @@ void setup() modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); #endif - // Attach the modem to the logger + // Attach the modem and information pins to the logger EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.setAlertPin(greenLED); + EnviroDIYLogger.setTestingModePin(buttonPin); - // Set up the connection with EnviroDIY + // Enter the tokens for the connection with EnviroDIY EnviroDIYLogger.setToken(registrationToken); EnviroDIYLogger.setSamplingFeatureUUID(samplingFeature); - // Set up the connection with DreamHost - #ifdef DreamHostPortalRX - EnviroDIYLogger.setDreamHostPortalRX(DreamHostPortalRX); - #endif - // Begin the logger EnviroDIYLogger.begin(); - - // Hold up for 10-seconds to allow immediate entry into sensor testing mode - // EnviroDIYLogger.checkForTestingMode(buttonPin); - - // Set up an interrupt on a pin to enter sensor testing mode at any time - pinMode(buttonPin, INPUT_PULLUP); - enableInterrupt(buttonPin, Logger::testingISR, CHANGE); - Serial.print(F("Push button on pin ")); - Serial.print(buttonPin); - Serial.println(F(" at any time to enter sensor testing mode.")); - - // Blink the LEDs really fast to show start-up is done - greenredflash(6, 25); } From 7f7a47e181a12f799fccd7d638c4fcf5279ddd82 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 15:32:33 -0400 Subject: [PATCH 37/54] Updated platformio's --- examples/DRWI_CitSci/platformio.ini | 2 +- examples/DRWI_NoCellular/platformio.ini | 2 +- examples/baro_rho_correction/platformio.ini | 2 +- examples/data_saving/platformio.ini | 2 +- examples/double_logger/platformio.ini | 2 +- examples/logging_to_EnviroDIY/platformio.ini | 2 +- examples/logging_to_EnviroDIY_Zero/platformio.ini | 2 +- examples/multisensor_print/platformio.ini | 2 +- examples/simple_logging/platformio.ini | 2 +- examples/single_sensor/platformio.ini | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/DRWI_CitSci/platformio.ini b/examples/DRWI_CitSci/platformio.ini index f528942b2..0e1892c66 100644 --- a/examples/DRWI_CitSci/platformio.ini +++ b/examples/DRWI_CitSci/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/DRWI_NoCellular/platformio.ini b/examples/DRWI_NoCellular/platformio.ini index 374af4969..c342574e4 100644 --- a/examples/DRWI_NoCellular/platformio.ini +++ b/examples/DRWI_NoCellular/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/baro_rho_correction/platformio.ini b/examples/baro_rho_correction/platformio.ini index 58b6891b3..d8c8b1204 100644 --- a/examples/baro_rho_correction/platformio.ini +++ b/examples/baro_rho_correction/platformio.ini @@ -19,6 +19,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/data_saving/platformio.ini b/examples/data_saving/platformio.ini index 8ad78cbd0..4545b5e47 100644 --- a/examples/data_saving/platformio.ini +++ b/examples/data_saving/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/double_logger/platformio.ini b/examples/double_logger/platformio.ini index 9929cfa77..7b6d19415 100644 --- a/examples/double_logger/platformio.ini +++ b/examples/double_logger/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/logging_to_EnviroDIY/platformio.ini b/examples/logging_to_EnviroDIY/platformio.ini index 1bfa827cb..5b9f5a1b6 100644 --- a/examples/logging_to_EnviroDIY/platformio.ini +++ b/examples/logging_to_EnviroDIY/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/logging_to_EnviroDIY_Zero/platformio.ini b/examples/logging_to_EnviroDIY_Zero/platformio.ini index 053f2da7d..f95780907 100644 --- a/examples/logging_to_EnviroDIY_Zero/platformio.ini +++ b/examples/logging_to_EnviroDIY_Zero/platformio.ini @@ -18,5 +18,5 @@ framework = arduino lib_ldf_mode = deep lib_ignore = SoftwareSerial_ExtInts, AltSoftSerial lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 RTCZero diff --git a/examples/multisensor_print/platformio.ini b/examples/multisensor_print/platformio.ini index b693096c1..2b8f5c68b 100644 --- a/examples/multisensor_print/platformio.ini +++ b/examples/multisensor_print/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/simple_logging/platformio.ini b/examples/simple_logging/platformio.ini index 8950ccf2d..345a84468 100644 --- a/examples/simple_logging/platformio.ini +++ b/examples/simple_logging/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git diff --git a/examples/single_sensor/platformio.ini b/examples/single_sensor/platformio.ini index c12f50055..57f40f03f 100644 --- a/examples/single_sensor/platformio.ini +++ b/examples/single_sensor/platformio.ini @@ -18,6 +18,6 @@ framework = arduino lib_ldf_mode = deep lib_ignore = RTCZero lib_deps = - EnviroDIY_ModularSensors@>=0.12.0 + EnviroDIY_ModularSensors@>=0.12.2 https://github.com/PaulStoffregen/AltSoftSerial.git https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git From 14f61a07a684f0788773dad45f79d2b1f127587d Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 15:48:15 -0400 Subject: [PATCH 38/54] Fixed modem name typo --- src/LoggerModem.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/LoggerModem.h b/src/LoggerModem.h index c372dc908..16da0a612 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -57,8 +57,8 @@ #elif defined(TINY_GSM_MODEM_M590) #define MODEM_NAME "Neoway M590" #elif defined(TINY_GSM_MODEM_MC60) - #define MODEM_NAME "Quectel MC60E" -#elif defined(TINY_GSM_MODEM_MC60) + #define MODEM_NAME "Quectel MC60" +#elif defined(TINY_GSM_MODEM_MC60E) #define MODEM_NAME "Quectel MC60E" #elif defined(TINY_GSM_MODEM_ESP8266) #define MODEM_NAME "ESP8266" From a84934eebc1fadef8b372dc0251cb3b127c8f71a Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 24 May 2018 17:10:09 -0400 Subject: [PATCH 39/54] Cleaned up some messiness with creating a file name --- src/ExternalVoltage.cpp | 2 +- src/LoggerBase.cpp | 113 ++++++++++++++++++++-------------------- src/LoggerBase.h | 30 +++++------ src/LoggerEnviroDIY.cpp | 13 ++--- 4 files changed, 77 insertions(+), 81 deletions(-) diff --git a/src/ExternalVoltage.cpp b/src/ExternalVoltage.cpp index db86e3c0d..c7f34d29e 100644 --- a/src/ExternalVoltage.cpp +++ b/src/ExternalVoltage.cpp @@ -53,7 +53,7 @@ String ExternalVoltage::getSensorLocation(void) { String sensorLocation = F("ADS1115_0x"); sensorLocation += String(_i2cAddress, HEX); - sensorLocation += F("_Pin"); + sensorLocation += F("_Pin"); sensorLocation += String(_dataPin); return sensorLocation; } diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 5fd3994b8..3e0c57c01 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -42,23 +42,28 @@ Logger::Logger(const char *loggerID, uint16_t loggingIntervalMinutes, int8_t SDCardPin, int8_t mcuWakePin, VariableArray *inputArray) { + // Set parameters from constructor + _loggerID = loggerID; + _loggingIntervalMinutes = loggingIntervalMinutes; _SDCardPin = SDCardPin; _mcuWakePin = mcuWakePin; - _loggingIntervalMinutes = loggingIntervalMinutes; - _loggerID = loggerID; - _autoFileName = false; - _isFileNameSet = false; - _numTimepointsLogged = 0; _internalArray = inputArray; - // Set the testing/logging flags + // Initialize with no points recorded + _numTimepointsLogged = 0; + + // Set the testing/logging flags to false isLoggingNow = false; isTestingNow = false; startTesting = false; - // Set the info pin numbers + // Initialize with informational pins set void _ledPin = -1; _buttonPin = -1; + + // Initialize with no file name + _fileName = ""; + _autoFileName = true; }; @@ -484,43 +489,33 @@ void Logger::wakeISR(void){MS_DBG(F("Clock interrupt!\n"));} // ===================================================================== // // This sets a file name, if you want to decide on it in advance -void Logger::setFileName(char *fileName) +void Logger::setFileName(String fileName) { - // Save the filename to the static String _fileName = fileName; - _isFileNameSet = true; - - // Print out the file name - PRINTOUT(F("Data will be saved as "), _fileName, '\n'); - if (!_autoFileName) PRINTOUT(F("\n")); + _autoFileName = false; } -// Same as above, with a string (overload function) -void Logger::setFileName(String fileName) +// Same as above, with a character array (overload function) +void Logger::setFileName(char *fileName) { - // Convert the string filename to a character file name - uint8_t fileNameLength = fileName.length() + 1; - char charFileName[fileNameLength]; - fileName.toCharArray(charFileName, fileNameLength); - setFileName(charFileName); + setFileName(String(fileName)); } // This generates a file name from the logger id and the current date // This will be used if the setFileName function is not called before // the begin() function is called. -void Logger::setFileName(void) +void Logger::generateAutoFileName(void) { - _autoFileName = true; - // Generate the file name from logger ID and date - String fileName = ""; - if (_loggerID) + if (_autoFileName) { - fileName += String(_loggerID); + // Generate the file name from logger ID and date + String fileName = String(_loggerID); fileName += F("_"); + fileName += formatDateTime_ISO8601(getNowEpoch()).substring(0, 10); + fileName += F(".csv"); + setFileName(fileName); + _fileName = fileName; } - fileName += formatDateTime_ISO8601(getNowEpoch()).substring(0, 10); - fileName += F(".csv"); - setFileName(fileName); } // This is a PRE-PROCESSOR MACRO to speed up generating header rows @@ -667,7 +662,7 @@ bool Logger::initializeSDCard(void) // Private helper function - This sets a timestamp on a file -void Logger::setFileTimestame(File fileToStamp, uint8_t stampFlag) +void Logger::setFileTimestamp(File fileToStamp, uint8_t stampFlag) { fileToStamp.timestamp(stampFlag, dtFromEpoch(getNowEpoch()).year(), dtFromEpoch(getNowEpoch()).month(), @@ -692,14 +687,14 @@ bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) filename.toCharArray(charFileName, fileNameLength); // First attempt to open an already existing file (in write mode), so we - // tdon't try to re-create something that's already there. + // don't try to re-create something that's already there. // This should also prevent the header from being written over and over // in the file. if (logFile.open(charFileName, O_WRITE | O_AT_END)) { MS_DBG(F("Opened existing file: "), filename, F("\n")); // Set access date time - setFileTimestame(logFile, T_ACCESS); + setFileTimestamp(logFile, T_ACCESS); return true; } else if (createFile) @@ -709,7 +704,7 @@ bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) { MS_DBG(F("Created new file: "), filename, F("\n")); // Set creation date time - setFileTimestame(logFile, T_CREATE); + setFileTimestamp(logFile, T_CREATE); // Write out a header, if requested if (writeDefaultHeader) { @@ -721,10 +716,10 @@ bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) streamFileHeader(&DEBUGGING_SERIAL_OUTPUT); #endif // Set write/modification date time - setFileTimestame(logFile, T_WRITE); + setFileTimestamp(logFile, T_WRITE); } // Set access date time - setFileTimestame(logFile, T_ACCESS); + setFileTimestamp(logFile, T_ACCESS); return true; } // Return false if we couldn't create the file @@ -750,18 +745,21 @@ bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) // If specified, it will also write a header to the file based on // the sensors in the group. // This can be used to force a logger to create a file with a secondary file name. -void Logger::createLogFile(String filename, bool writeDefaultHeader) +bool Logger::createLogFile(String filename, bool writeDefaultHeader) { // Attempt to create and open a file if (openFile(filename, true, writeDefaultHeader)) { // Close the file to save it (only do this if we'd opened it) logFile.close(); + return true; } + else return false; } -void Logger::createLogFile(bool writeDefaultHeader) +bool Logger::createLogFile(bool writeDefaultHeader) { - createLogFile(_fileName, writeDefaultHeader); + if (_autoFileName) generateAutoFileName(); + return createLogFile(_fileName, writeDefaultHeader); } @@ -771,16 +769,17 @@ void Logger::createLogFile(bool writeDefaultHeader) // or can be specified in the function. // If the file does not already exist, the file will be created. // This can be used to force a logger to write to a file with a secondary file name. -void Logger::logToSD(String filename, String rec) +bool Logger::logToSD(String filename, String rec) { // First attempt to open the file without creating a new one if (openFile(filename, false, false)) goto writeRecord; // Next try to create the file, bail if we couldn't create it + // This will not attempt to generate a new file name or add a header! else if (openFile(filename, true, false)) goto writeRecord; else { PRINTOUT(F("Unable to write to SD card!\n")); - return; + return false; } writeRecord: @@ -792,25 +791,28 @@ void Logger::logToSD(String filename, String rec) PRINTOUT(rec, F("\n")); // Set write/modification date time - setFileTimestame(logFile, T_WRITE); + setFileTimestamp(logFile, T_WRITE); // Close the file to save it logFile.close(); + return true; } } -void Logger::logToSD(String rec) +bool Logger::logToSD(String rec) { - logToSD(_fileName, rec); + return logToSD(_fileName, rec); } // NOTE: This is structured differently than the version with a string input // record. This is to avoid the creation/passing of very long strings. -void Logger::logToSD(void) +bool Logger::logToSD(void) { // First attempt to open the file without creating a new one if (openFile(_fileName, false, false)) goto writeRecord; - // Next try to create the file, bail if we couldn't create it - // Do add a default header! + // Next try to create a new file, bail if we couldn't create it + // Generate a filename with the current date, if the file name isn't set + if (_autoFileName) generateAutoFileName(); + // Do add a default header to the new file! if (openFile(_fileName, true, true)) goto writeRecord; - else return; + else return false; writeRecord: { @@ -824,9 +826,10 @@ void Logger::logToSD(void) #endif // Set write/modification date time - setFileTimestame(logFile, T_WRITE); + setFileTimestamp(logFile, T_WRITE); // Close the file to save it logFile.close(); + return true; } } @@ -952,17 +955,13 @@ void Logger::testingMode() F(" come from "),_internalArray->getSensorCount(), F(" sensors and "), _internalArray->getCalculatedVariableCount(), F(" are calculated.\n")); + // Create the log file, adding the default header to it + if (createLogFile(true)) PRINTOUT(F("Data will be saved as "), _fileName, '\n'); + else PRINTOUT(F("Unable to create a file to save data to!")); + // Set up the sensors _internalArray->setupSensors(); - // Set the filename for the logger to save to, if it hasn't been done - if(!_isFileNameSet){setFileName();} - else if(_autoFileName){setFileName();} - else setFileName(_fileName); // This just for a nice print-out - - // Create the log file, adding the default header to it - createLogFile(true); - // Setup sleep mode if(_mcuWakePin >= 0){setupSleep();} diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 4508e8e1f..a548c2ccf 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -126,10 +126,6 @@ class Logger void setFileName(char *fileName); // Same as above, with a string (overload function) void setFileName(String fileName); - // This generates a file name from the logger id and the current date - // This will be used if the setFileName function is not called before - // the begin() function is called. - void setFileName(void); // This returns the current filename. Must be run after setFileName. String getFileName(void){return _fileName;} @@ -154,8 +150,8 @@ class Logger // If asked to, these functions will also write a header to the file based // on the variable information from the variable array. // This can be used to force a logger to create a file with a secondary file name. - void createLogFile(String filename, bool writeDefaultHeader = false); - void createLogFile(bool writeDefaultHeader = false); + bool createLogFile(String filename, bool writeDefaultHeader = false); + bool createLogFile(bool writeDefaultHeader = false); // These functions create a file on an SD card and set the modified/accessed // timestamps in that file. @@ -166,9 +162,9 @@ class Logger // The line to be written to the file can either be specified or will be // a comma separated list of the current values of all variables in the // variable array. - void logToSD(String filename, String rec); - void logToSD(String rec); - void logToSD(void); + bool logToSD(String filename, String rec); + bool logToSD(String rec); + bool logToSD(void); // ===================================================================== // @@ -218,6 +214,7 @@ class Logger SdFat sd; File logFile; String _fileName; + bool _autoFileName; // Static variables - identical for EVERY logger static int8_t _timeZone; @@ -228,22 +225,25 @@ class Logger static char markedISO8601Time[26]; // Initialization variables + const char *_loggerID; + uint16_t _loggingIntervalMinutes; int8_t _SDCardPin; int8_t _mcuWakePin; - uint16_t _loggingIntervalMinutes; - const char *_loggerID; - bool _autoFileName; - bool _isFileNameSet; + VariableArray *_internalArray; + uint8_t _numTimepointsLogged; int8_t _ledPin; int8_t _buttonPin; - VariableArray *_internalArray; // This checks if the SD card is available and ready bool initializeSDCard(void); + // This generates a file name from the logger id and the current date + // NOTE: This cannot be called until the set-up after the RTC is started + void generateAutoFileName(void); + // This sets a timestamp on a file - void setFileTimestame(File fileToStamp, uint8_t stampFlag); + void setFileTimestamp(File fileToStamp, uint8_t stampFlag); // This opens or creates a file, converting a string file name to a // characterd file name diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 0ab45637c..0b3c07c4f 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -367,6 +367,10 @@ void LoggerEnviroDIY::begin(void) F(" come from "),_internalArray->getSensorCount(), F(" sensors and "), _internalArray->getCalculatedVariableCount(), F(" are calculated.\n")); + // Create the log file, adding the default header to it + if (createLogFile(true)) PRINTOUT(F("Data will be saved as "), _fileName, '\n'); + else PRINTOUT(F("Unable to create a file to save data to!")); + if (_modemAttached) { // Print out the modem info @@ -383,6 +387,7 @@ void LoggerEnviroDIY::begin(void) { // Synchronize the RTC with NIST PRINTOUT(F("Attempting to synchronize RTC with NIST\n")); + PRINTOUT(F("This may take up to two minutes!\n")); // Connect to the network if (_logModem->connectInternet(120000L)) { @@ -394,14 +399,6 @@ void LoggerEnviroDIY::begin(void) _logModem->modemPowerDown(); } - // Set the filename for the logger to save to, if it hasn't been done - if(!_isFileNameSet){setFileName();} - else if(_autoFileName){setFileName();} - else setFileName(_fileName); // This just for a nice print-out - - // Create the log file, adding the default header to it - createLogFile(true); - // Setup sleep mode if(_mcuWakePin >= 0){setupSleep();} From 75030161f62af184c90947335fba03de94b84f9d Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 11:43:59 -0400 Subject: [PATCH 40/54] Fixed if statement in example --- examples/baro_rho_correction/baro_rho_correction.ino | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index 873ff7145..a0f568380 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -187,7 +187,7 @@ float calculateWaterPressure(void) float totalPressureFromMS5803 = msPress->getValue(); float baroPressureFromBME280 = bPress->getValue(); float waterPressure = totalPressureFromMS5803 - (baroPressureFromBME280)*0.01; - if (totalPressureFromMS5803 = -9999 || baroPressureFromBME280 == -9999) + if (totalPressureFromMS5803 == -9999 || baroPressureFromBME280 == -9999) waterPressure = -9999; // Serial.print(F("Water pressure is ")); // for debugging // Serial.println(waterPressure); // for debugging From 559da6f5672bed5cc1875eefdaeeea8fce76ca9b Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 12:33:16 -0400 Subject: [PATCH 41/54] Changed some pointers to references --- README.md | 2 +- examples/DRWI_CitSci/DRWI_CitSci.ino | 2 +- .../baro_rho_correction.ino | 2 +- examples/data_saving/data_saving.ino | 4 +- .../logging_to_EnviroDIY.ino | 2 +- .../logging_to_EnviroDIY_Zero.ino | 2 +- sensor_tests/AnthonyTest2/AnthonyTest2.ino | 2 +- src/ApogeeSQ212.cpp | 2 +- src/LoggerBase.cpp | 13 ++--- src/LoggerBase.h | 12 ++--- src/LoggerDreamHost.cpp | 26 +++++----- src/LoggerDreamHost.h | 2 +- src/LoggerEnviroDIY.cpp | 52 +++++++++---------- src/LoggerEnviroDIY.h | 6 +-- 14 files changed, 65 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 3328843a6..a33c2401f 100644 --- a/README.md +++ b/README.md @@ -515,7 +515,7 @@ EnviroDIYLogger.setUUIDs(UUIDs[]); modem.setupModem(modemStream, vcc33Pin, modemStatusPin, modemSleepRqPin, sleepType, APN); // Attach the modem to the logger -EnviroDIYLogger.attachModem(&modem); +EnviroDIYLogger.attachModem(modem); // Begin the logger; EnviroDIYLogger.begin(); diff --git a/examples/DRWI_CitSci/DRWI_CitSci.ino b/examples/DRWI_CitSci/DRWI_CitSci.ino index 29bbc70b9..b9a772197 100644 --- a/examples/DRWI_CitSci/DRWI_CitSci.ino +++ b/examples/DRWI_CitSci/DRWI_CitSci.ino @@ -203,7 +203,7 @@ void setup() modem.setupModem(&ModemSerial, modemVCCPin, modemStatusPin, modemSleepRqPin, ModemSleepMode, apn); // Attach the modem and information pins to the logger - EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.attachModem(modem); EnviroDIYLogger.setAlertPin(greenLED); EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index a0f568380..ef6fdd5bc 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -361,7 +361,7 @@ void setup() #endif // Attach the modem and information pins to the logger - EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.attachModem(modem); EnviroDIYLogger.setAlertPin(greenLED); EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index 3d32b8a50..7fc23e233 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -320,8 +320,8 @@ void setup() // Attach the same modem to both loggers // It is only needed for the logger that will be sending out data, but // attaching it to both allows either logger to control NIST synchronization - loggerComplete.attachModem(&modem); - loggerToGo.attachModem(&modem); + loggerComplete.attachModem(modem); + loggerToGo.attachModem(modem); loggerComplete.setTestingModePin(buttonPin); // There is no reason to call the setAlertPin() function, because we have to // write the loop on our own. diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index d5380a099..0451e742c 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -594,7 +594,7 @@ void setup() #endif // Attach the modem and information pins to the logger - EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.attachModem(modem); EnviroDIYLogger.setAlertPin(greenLED); EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index 6c670cf06..02095472c 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -597,7 +597,7 @@ void setup() #endif // Attach the modem and information pins to the logger - EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.attachModem(modem); EnviroDIYLogger.setAlertPin(greenLED); // No button on the feather, so we're not attaching a testingMode pin diff --git a/sensor_tests/AnthonyTest2/AnthonyTest2.ino b/sensor_tests/AnthonyTest2/AnthonyTest2.ino index b7a814e34..64c452446 100644 --- a/sensor_tests/AnthonyTest2/AnthonyTest2.ino +++ b/sensor_tests/AnthonyTest2/AnthonyTest2.ino @@ -609,7 +609,7 @@ void setup() #endif // Attach the modem and information pins to the logger - EnviroDIYLogger.attachModem(&modem); + EnviroDIYLogger.attachModem(modem); EnviroDIYLogger.setAlertPin(greenLED); EnviroDIYLogger.setTestingModePin(buttonPin); diff --git a/src/ApogeeSQ212.cpp b/src/ApogeeSQ212.cpp index 36f151057..c950a2ba6 100644 --- a/src/ApogeeSQ212.cpp +++ b/src/ApogeeSQ212.cpp @@ -48,7 +48,7 @@ String ApogeeSQ212::getSensorLocation(void) { String sensorLocation = F("ADS1115_0x"); sensorLocation += String(_i2cAddress, HEX); - sensorLocation += F("_Pin"); + sensorLocation += F("_Pin"); sensorLocation += String(_dataPin); return sensorLocation; } diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 3e0c57c01..8fb719993 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -489,15 +489,16 @@ void Logger::wakeISR(void){MS_DBG(F("Clock interrupt!\n"));} // ===================================================================== // // This sets a file name, if you want to decide on it in advance -void Logger::setFileName(String fileName) +void Logger::setFileName(String& fileName) { _fileName = fileName; _autoFileName = false; } // Same as above, with a character array (overload function) -void Logger::setFileName(char *fileName) +void Logger::setFileName(char& fileName) { - setFileName(String(fileName)); + String StrName = String(fileName); + setFileName(StrName); } @@ -745,7 +746,7 @@ bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) // If specified, it will also write a header to the file based on // the sensors in the group. // This can be used to force a logger to create a file with a secondary file name. -bool Logger::createLogFile(String filename, bool writeDefaultHeader) +bool Logger::createLogFile(String& filename, bool writeDefaultHeader) { // Attempt to create and open a file if (openFile(filename, true, writeDefaultHeader)) @@ -769,7 +770,7 @@ bool Logger::createLogFile(bool writeDefaultHeader) // or can be specified in the function. // If the file does not already exist, the file will be created. // This can be used to force a logger to write to a file with a secondary file name. -bool Logger::logToSD(String filename, String rec) +bool Logger::logToSD(String& filename, String& rec) { // First attempt to open the file without creating a new one if (openFile(filename, false, false)) goto writeRecord; @@ -797,7 +798,7 @@ bool Logger::logToSD(String filename, String rec) return true; } } -bool Logger::logToSD(String rec) +bool Logger::logToSD(String& rec) { return logToSD(_fileName, rec); } diff --git a/src/LoggerBase.h b/src/LoggerBase.h index a548c2ccf..f03c7f5d9 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -123,9 +123,9 @@ class Logger // Public functions for logging data to an SD card // ===================================================================== // // This sets a file name, if you want to decide on it in advance - void setFileName(char *fileName); + void setFileName(char& fileName); // Same as above, with a string (overload function) - void setFileName(String fileName); + void setFileName(String& fileName); // This returns the current filename. Must be run after setFileName. String getFileName(void){return _fileName;} @@ -150,7 +150,7 @@ class Logger // If asked to, these functions will also write a header to the file based // on the variable information from the variable array. // This can be used to force a logger to create a file with a secondary file name. - bool createLogFile(String filename, bool writeDefaultHeader = false); + bool createLogFile(String& filename, bool writeDefaultHeader = false); bool createLogFile(bool writeDefaultHeader = false); // These functions create a file on an SD card and set the modified/accessed @@ -162,8 +162,8 @@ class Logger // The line to be written to the file can either be specified or will be // a comma separated list of the current values of all variables in the // variable array. - bool logToSD(String filename, String rec); - bool logToSD(String rec); + bool logToSD(String& filename, String& rec); + bool logToSD(String& rec); bool logToSD(void); @@ -225,7 +225,7 @@ class Logger static char markedISO8601Time[26]; // Initialization variables - const char *_loggerID; + const char* _loggerID; uint16_t _loggingIntervalMinutes; int8_t _SDCardPin; int8_t _mcuWakePin; diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index 531065746..b4c899ffa 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -79,7 +79,7 @@ void LoggerDreamHost::streamSensorDataDreamHost(Stream *stream) // This prints a fully structured GET request for DreamHost to the // specified stream using the specified url. -void LoggerDreamHost::streamDreamHostRequest(Stream *stream, String fullURL) +void LoggerDreamHost::streamDreamHostRequest(Stream *stream, String& fullURL) { stream->print(String(F("GET "))); stream->print(fullURL); @@ -117,7 +117,7 @@ int LoggerDreamHost::postDataDreamHost(String fullURL) int did_respond = 0; // Open a TCP/IP connection to DreamHost - if(_logModem->openTCP("swrcsensors.dreamhosters.com", 80)) + if(_logModem.openTCP("swrcsensors.dreamhosters.com", 80)) { // Send the request to the serial for debugging #if defined(STANDARD_SERIAL_OUTPUT) @@ -128,23 +128,23 @@ int LoggerDreamHost::postDataDreamHost(String fullURL) #endif // Send the request to the modem stream - if (fullURL.length() > 1) streamDreamHostRequest(_logModem->_client, fullURL); - else streamDreamHostRequest(_logModem->_client); - _logModem->_client->flush(); // wait for sending to finish + if (fullURL.length() > 1) streamDreamHostRequest(_logModem._client, fullURL); + else streamDreamHostRequest(_logModem._client); + _logModem._client->flush(); // wait for sending to finish uint32_t start_timer = millis(); - while ((millis() - start_timer) < 10000L && _logModem->_client->available() < 12) + while ((millis() - start_timer) < 10000L && _logModem._client->available() < 12) {delay(10);} // Read only the first 12 characters of the response // We're only reading as far as the http code, anything beyond that // we don't care about so we're not reading to save on total // data used for transmission. - did_respond = _logModem->_client->readBytes(response_buffer, 12); + did_respond = _logModem._client->readBytes(response_buffer, 12); // Close the TCP/IP connection as soon as the first 12 characters are read // We don't need anything else and stoping here should save data use. - _logModem->closeTCP(); + _logModem.closeTCP(); } else PRINTOUT(F("\n -- Unable to Establish Connection to DreamHost -- \n")); @@ -197,7 +197,7 @@ void LoggerDreamHost::log(void) if (_modemAttached) { // Turn on the modem to let it start searching for the network - _logModem->modemPowerUp(); + _logModem.modemPowerUp(); } // Send power to all of the sensors @@ -220,7 +220,7 @@ void LoggerDreamHost::log(void) { // Connect to the network MS_DBG(F(" Connecting to the Internet...\n")); - if (_logModem->connectInternet()) + if (_logModem.connectInternet()) { if(_dualPost) { @@ -235,15 +235,15 @@ void LoggerDreamHost::log(void) MS_DBG(F(" Running a daily clock sync...\n")); if (_numTimepointsLogged % 288 == 0) { - syncRTClock(_logModem->getNISTTime()); + syncRTClock(_logModem.getNISTTime()); } // Disconnect from the network MS_DBG(F(" Disconnecting from the Internet...\n")); - _logModem->disconnectInternet(); + _logModem.disconnectInternet(); } // Turn the modem off - _logModem->modemPowerDown(); + _logModem.modemPowerDown(); } // Create a csv data record and save it to the log file diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index 617062414..00610a424 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -45,7 +45,7 @@ class LoggerDreamHost : public LoggerEnviroDIY // This prints a fully structured GET request for DreamHost to the // specified stream using the specified url. // This may be necessary to work around very long strings for the post request. - void streamDreamHostRequest(Stream *stream, String fullURL); + void streamDreamHostRequest(Stream *stream, String& fullURL); // This prints a fully structured GET request for DreamHost to the // specified stream with the default url. void streamDreamHostRequest(Stream *stream); diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index 0b3c07c4f..b4ef4458f 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -33,7 +33,7 @@ LoggerEnviroDIY::LoggerEnviroDIY(const char *loggerID, uint16_t loggingIntervalM // Set up communications // Adds a loggerModem objct to the logger // loggerModem = TinyGSM modem + TinyGSM client + Modem On Off -void LoggerEnviroDIY::attachModem(loggerModem *modem) +void LoggerEnviroDIY::attachModem(loggerModem& modem) { _logModem = modem; _modemAttached = true; @@ -140,7 +140,7 @@ void LoggerEnviroDIY::streamSensorDataJSON(Stream *stream) // This prints a fully structured post request for EnviroDIY to the // specified stream using the specified json. -void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream, String enviroDIYjson) +void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream, String& enviroDIYjson) { stream->print(String(F("POST /api/data-stream/ HTTP/1.1"))); stream->print(String(F("\r\nHost: data.envirodiy.org"))); @@ -205,7 +205,7 @@ int LoggerEnviroDIY::postDataEnviroDIY(String enviroDIYjson) int did_respond = 0; // Open a TCP/IP connection to the Enviro DIY Data Portal (WebSDL) - if(_logModem->openTCP("data.envirodiy.org", 80)) + if(_logModem.openTCP("data.envirodiy.org", 80)) { // Send the request to the serial for debugging #if defined(STANDARD_SERIAL_OUTPUT) @@ -217,23 +217,23 @@ int LoggerEnviroDIY::postDataEnviroDIY(String enviroDIYjson) #endif // Send the request to the modem stream - if (enviroDIYjson.length() > 1) streamEnviroDIYRequest(_logModem->_client, enviroDIYjson); - else streamEnviroDIYRequest(_logModem->_client); - _logModem->_client->flush(); // wait for sending to finish + if (enviroDIYjson.length() > 1) streamEnviroDIYRequest(_logModem._client, enviroDIYjson); + else streamEnviroDIYRequest(_logModem._client); + _logModem._client->flush(); // wait for sending to finish uint32_t start_timer = millis(); - while ((millis() - start_timer) < 10000L && _logModem->_client->available() < 12) + while ((millis() - start_timer) < 10000L && _logModem._client->available() < 12) {delay(10);} // Read only the first 12 characters of the response // We're only reading as far as the http code, anything beyond that // we don't care about so we're not reading to save on total // data used for transmission. - did_respond = _logModem->_client->readBytes(response_buffer, 12); + did_respond = _logModem._client->readBytes(response_buffer, 12); // Close the TCP/IP connection as soon as the first 12 characters are read // We don't need anything else and stoping here should save data use. - _logModem->closeTCP(); + _logModem.closeTCP(); } else PRINTOUT(F("\n -- Unable to Establish Connection to EnviroDIY Data Portal -- \n")); @@ -277,9 +277,9 @@ void LoggerEnviroDIY::testingMode() { // Turn on the modem to let it start searching for the network // Turn on the modem - _logModem->modemPowerUp(); + _logModem.modemPowerUp(); // Connect to the network to make sure we have signal (only try for 10sec) - _logModem->connectInternet(10000L); + _logModem.connectInternet(10000L); } // Power up all of the sensors @@ -307,9 +307,9 @@ void LoggerEnviroDIY::testingMode() if (_modemAttached) { // Specially highlight the modem signal quality in the debug mode - _logModem->update(); + _logModem.update(); PRINTOUT(F("Current modem signal is ")); - PRINTOUT(_logModem->getSignalPercent()); + PRINTOUT(_logModem.getSignalPercent()); PRINTOUT(F("%\n")); } @@ -323,9 +323,9 @@ void LoggerEnviroDIY::testingMode() if (_modemAttached) { // Disconnect from the network - _logModem->disconnectInternet(); + _logModem.disconnectInternet(); // Turn off the modem - _logModem->modemPowerDown(); + _logModem.modemPowerDown(); } // Unset testing mode flag @@ -375,9 +375,9 @@ void LoggerEnviroDIY::begin(void) { // Print out the modem info PRINTOUT(F("This logger is also tied to a ")); - PRINTOUT(_logModem->getSensorName(), F(" for internet connectivity.\n")); + PRINTOUT(_logModem.getSensorName(), F(" for internet connectivity.\n")); // Turn on the modem to let it start searching for the network - _logModem->modemPowerUp(); + _logModem.modemPowerUp(); } // Set up the sensors @@ -389,14 +389,14 @@ void LoggerEnviroDIY::begin(void) PRINTOUT(F("Attempting to synchronize RTC with NIST\n")); PRINTOUT(F("This may take up to two minutes!\n")); // Connect to the network - if (_logModem->connectInternet(120000L)) + if (_logModem.connectInternet(120000L)) { - syncRTClock(_logModem->getNISTTime()); + syncRTClock(_logModem.getNISTTime()); // Disconnect from the network - _logModem->disconnectInternet(); + _logModem.disconnectInternet(); } // Turn off the modem - _logModem->modemPowerDown(); + _logModem.modemPowerDown(); } // Setup sleep mode @@ -437,7 +437,7 @@ void LoggerEnviroDIY::log(void) if (_modemAttached) { // Turn on the modem to let it start searching for the network - _logModem->modemPowerUp(); + _logModem.modemPowerUp(); } // Send power to all of the sensors @@ -460,7 +460,7 @@ void LoggerEnviroDIY::log(void) { // Connect to the network MS_DBG(F(" Connecting to the Internet...\n")); - if (_logModem->connectInternet()) + if (_logModem.connectInternet()) { // Post the data to the WebSDL postDataEnviroDIY(); @@ -469,15 +469,15 @@ void LoggerEnviroDIY::log(void) MS_DBG(F(" Running a daily clock sync...\n")); if (_numTimepointsLogged % 288 == 0) { - syncRTClock(_logModem->getNISTTime()); + syncRTClock(_logModem.getNISTTime()); } // Disconnect from the network MS_DBG(F(" Disconnecting from the Internet...\n")); - _logModem->disconnectInternet(); + _logModem.disconnectInternet(); } // Turn the modem off - _logModem->modemPowerDown(); + _logModem.modemPowerDown(); } // Create a csv data record and save it to the log file diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index efcbf28a7..1995d1a78 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -32,7 +32,7 @@ class LoggerEnviroDIY : public Logger // Adds a loggerModem objct to the logger // loggerModem = TinyGSM modem + TinyGSM client + Modem On Off - void attachModem(loggerModem *modem); + void attachModem(loggerModem& modem); // Adds the site registration token void setToken(const char *registrationToken); @@ -57,7 +57,7 @@ class LoggerEnviroDIY : public Logger // This prints a fully structured post request for EnviroDIY to the // specified stream using the specified json. // This may be necessary to work around very long strings for the post request. - void streamEnviroDIYRequest(Stream *stream, String enviroDIYjson); + void streamEnviroDIYRequest(Stream *stream, String& enviroDIYjson); // This prints a fully structured post request for EnviroDIY to the // specified stream with the default json. void streamEnviroDIYRequest(Stream *stream); @@ -85,7 +85,7 @@ class LoggerEnviroDIY : public Logger // The internal modem instance bool _modemAttached; - loggerModem *_logModem; + loggerModem _logModem; private: From c5414ee84df7e6ac966e37d93dea980c776b32cb Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 13:26:45 -0400 Subject: [PATCH 42/54] Fix broken example --- src/LoggerBase.cpp | 2 +- src/LoggerBase.h | 2 +- src/LoggerModem.h | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 8fb719993..5369f399d 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -495,7 +495,7 @@ void Logger::setFileName(String& fileName) _autoFileName = false; } // Same as above, with a character array (overload function) -void Logger::setFileName(char& fileName) +void Logger::setFileName(char* fileName) { String StrName = String(fileName); setFileName(StrName); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index f03c7f5d9..9389a8f75 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -123,7 +123,7 @@ class Logger // Public functions for logging data to an SD card // ===================================================================== // // This sets a file name, if you want to decide on it in advance - void setFileName(char& fileName); + void setFileName(char* fileName); // Same as above, with a string (overload function) void setFileName(String& fileName); diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 16da0a612..719fcaafc 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -456,7 +456,8 @@ class loggerModem : public Sensor { bool connectionMade = false; // bail if not connected to the internet - // TODO: Figure out why _model->isNetworkConnected() isn't working here + // TODO: Figure out why _modem->isNetworkConnected() isn't working here + // if (!_modem->isNetworkConnected()) if (!(connectInternet(1000))) { MS_MOD_DBG(F("No internet connection, cannot connect to NIST.\n")); From 1c7376253ee305bc8238fe4b02ed478d55e388de Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 15:04:11 -0400 Subject: [PATCH 43/54] More pointers to refs --- src/AOSongAM2315.h | 4 ++-- src/AOSongDHT.h | 6 +++--- src/ApogeeSQ212.h | 2 +- src/BoschBME280.h | 8 ++++---- src/CampbellOBS3.h | 2 +- src/Decagon5TM.h | 6 +++--- src/DecagonCTD.h | 6 +++--- src/DecagonES2.h | 4 ++-- src/ExternalVoltage.h | 2 +- src/FreescaleMPL115A2.h | 4 ++-- src/KellerAcculevel.h | 6 +++--- src/LoggerBase.cpp | 6 +++--- src/LoggerBase.h | 6 +++--- src/LoggerDreamHost.cpp | 2 +- src/LoggerDreamHost.h | 2 +- src/LoggerEnviroDIY.cpp | 2 +- src/LoggerEnviroDIY.h | 2 +- src/LoggerModem.h | 4 ++-- src/MaxBotixSonar.h | 2 +- src/MaximDS18.h | 2 +- src/MaximDS3231.h | 2 +- src/MeaSpecMS5803.h | 4 ++-- src/ProcessorStats.h | 4 ++-- src/RainCounterI2C.h | 4 ++-- src/VariableBase.cpp | 6 +++--- src/VariableBase.h | 13 ++++++++----- src/YosemitechY4000.h | 16 ++++++++-------- src/YosemitechY504.h | 6 +++--- src/YosemitechY510.h | 4 ++-- src/YosemitechY511.h | 4 ++-- src/YosemitechY514.h | 4 ++-- src/YosemitechY520.h | 4 ++-- src/YosemitechY532.h | 6 +++--- src/YosemitechY533.h | 6 +++--- src/YosemitechY550.h | 6 +++--- src/ZebraTechDOpto.h | 6 +++--- 36 files changed, 88 insertions(+), 85 deletions(-) diff --git a/src/AOSongAM2315.h b/src/AOSongAM2315.h index fdbd80dc6..8ca5127fd 100644 --- a/src/AOSongAM2315.h +++ b/src/AOSongAM2315.h @@ -65,7 +65,7 @@ class AOSongAM2315_Humidity : public Variable { public: AOSongAM2315_Humidity(Sensor *parentSense, - String UUID = "", String customVarCode = "") : + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, AM2315_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), AM2315_HUMIDITY_RESOLUTION, @@ -79,7 +79,7 @@ class AOSongAM2315_Temp : public Variable { public: AOSongAM2315_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") : + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, AM2315_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), AM2315_TEMP_RESOLUTION, diff --git a/src/AOSongDHT.h b/src/AOSongDHT.h index a693e86ae..68f2ac7f8 100644 --- a/src/AOSongDHT.h +++ b/src/AOSongDHT.h @@ -90,7 +90,7 @@ class AOSongDHT_Humidity : public Variable { public: AOSongDHT_Humidity(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DHT_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), DHT_HUMIDITY_RESOLUTION, @@ -104,7 +104,7 @@ class AOSongDHT_Temp : public Variable { public: AOSongDHT_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DHT_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DHT_TEMP_RESOLUTION, @@ -118,7 +118,7 @@ class AOSongDHT_HI : public Variable { public: AOSongDHT_HI(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DHT_HI_VAR_NUM, F("heatIndex"), F("degreeCelsius"), DHT_HI_RESOLUTION, diff --git a/src/ApogeeSQ212.h b/src/ApogeeSQ212.h index ae773a136..ec99d539f 100644 --- a/src/ApogeeSQ212.h +++ b/src/ApogeeSQ212.h @@ -74,7 +74,7 @@ class ApogeeSQ212_PAR : public Variable { public: ApogeeSQ212_PAR(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, SQ212_PAR_VAR_NUM, F("radiationIncomingPAR"), F("microeinsteinPerSquareMeterPerSecond"), SQ212_PAR_RESOLUTION, diff --git a/src/BoschBME280.h b/src/BoschBME280.h index 949b1275e..6373e78ce 100644 --- a/src/BoschBME280.h +++ b/src/BoschBME280.h @@ -84,7 +84,7 @@ class BoschBME280_Temp : public Variable { public: BoschBME280_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BME280_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), BME280_TEMP_RESOLUTION, @@ -98,7 +98,7 @@ class BoschBME280_Humidity : public Variable { public: BoschBME280_Humidity(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BME280_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), BME280_HUMIDITY_RESOLUTION, @@ -112,7 +112,7 @@ class BoschBME280_Pressure : public Variable { public: BoschBME280_Pressure(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BME280_PRESSURE_VAR_NUM, F("barometricPressure"), F("pascal"), BME280_PRESSURE_RESOLUTION, @@ -126,7 +126,7 @@ class BoschBME280_Altitude : public Variable { public: BoschBME280_Altitude(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BME280_ALTITUDE_VAR_NUM, F("heightAboveSeaFloor"), F("meter"), BME280_ALTITUDE_RESOLUTION, diff --git a/src/CampbellOBS3.h b/src/CampbellOBS3.h index b64a9e2ba..2a8bf524f 100644 --- a/src/CampbellOBS3.h +++ b/src/CampbellOBS3.h @@ -74,7 +74,7 @@ class CampbellOBS3_Turbidity : public Variable { public: CampbellOBS3_Turbidity(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, OBS3_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), OBS3_RESOLUTION, diff --git a/src/Decagon5TM.h b/src/Decagon5TM.h index 4c25f05cc..e3ebcbda1 100644 --- a/src/Decagon5TM.h +++ b/src/Decagon5TM.h @@ -75,7 +75,7 @@ class Decagon5TM : public SDI12Sensors class Decagon5TM_Ea : public Variable { public: - Decagon5TM_Ea(Sensor *parentSense, String UUID = "", String customVarCode = "") + Decagon5TM_Ea(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, TM_EA_VAR_NUM, F("permittivity"), F("faradPerMeter"), TM_EA_RESOLUTION, @@ -88,7 +88,7 @@ class Decagon5TM_Ea : public Variable class Decagon5TM_Temp : public Variable { public: - Decagon5TM_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + Decagon5TM_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, TM_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), TM_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class Decagon5TM_Temp : public Variable class Decagon5TM_VWC : public Variable { public: - Decagon5TM_VWC(Sensor *parentSense, String UUID = "", String customVarCode = "") + Decagon5TM_VWC(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, TM_VWC_VAR_NUM, F("volumetricWaterContent"), F("percent"), TM_VWC_RESOLUTION, diff --git a/src/DecagonCTD.h b/src/DecagonCTD.h index 812f96ba1..a7a160915 100644 --- a/src/DecagonCTD.h +++ b/src/DecagonCTD.h @@ -78,7 +78,7 @@ class DecagonCTD : public SDI12Sensors class DecagonCTD_Cond : public Variable { public: - DecagonCTD_Cond(Sensor *parentSense, String UUID = "", String customVarCode = "") + DecagonCTD_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, CTD_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), CTD_COND_RESOLUTION, @@ -91,7 +91,7 @@ class DecagonCTD_Cond : public Variable class DecagonCTD_Temp : public Variable { public: - DecagonCTD_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + DecagonCTD_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, CTD_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), CTD_TEMP_RESOLUTION, @@ -104,7 +104,7 @@ class DecagonCTD_Temp : public Variable class DecagonCTD_Depth : public Variable { public: - DecagonCTD_Depth(Sensor *parentSense, String UUID = "", String customVarCode = "") + DecagonCTD_Depth(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, CTD_DEPTH_VAR_NUM, F("waterDepth"), F("millimeter"), CTD_DEPTH_RESOLUTION, diff --git a/src/DecagonES2.h b/src/DecagonES2.h index 3d83dc98b..0f6344f33 100644 --- a/src/DecagonES2.h +++ b/src/DecagonES2.h @@ -69,7 +69,7 @@ class DecagonES2 : public SDI12Sensors class DecagonES2_Cond : public Variable { public: - DecagonES2_Cond(Sensor *parentSense, String UUID = "", String customVarCode = "") + DecagonES2_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, ES2_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), ES2_COND_RESOLUTION, @@ -81,7 +81,7 @@ class DecagonES2_Cond : public Variable class DecagonES2_Temp : public Variable { public: - DecagonES2_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + DecagonES2_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, ES2_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), ES2_TEMP_RESOLUTION, diff --git a/src/ExternalVoltage.h b/src/ExternalVoltage.h index 75cca75ce..eddfa7f8d 100644 --- a/src/ExternalVoltage.h +++ b/src/ExternalVoltage.h @@ -81,7 +81,7 @@ class ExternalVoltage_Volt : public Variable { public: ExternalVoltage_Volt(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, EXT_VOLT_VAR_NUM, F("voltage"), F("volt"), EXT_VOLT_RESOLUTION, diff --git a/src/FreescaleMPL115A2.h b/src/FreescaleMPL115A2.h index e2260d3cc..c5dd53451 100644 --- a/src/FreescaleMPL115A2.h +++ b/src/FreescaleMPL115A2.h @@ -67,7 +67,7 @@ class MPL115A2_Temp : public Variable { public: MPL115A2_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, MPL115A2_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), MPL115A2_TEMP_RESOLUTION, @@ -81,7 +81,7 @@ class MPL115A2_Pressure : public Variable { public: MPL115A2_Pressure(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, MPL115A2_PRESSURE_VAR_NUM, F("atmosphericPressure"), F("kPa"), MPL115A2_PRESSURE_RESOLUTION, diff --git a/src/KellerAcculevel.h b/src/KellerAcculevel.h index b2c0f7298..5052f779b 100644 --- a/src/KellerAcculevel.h +++ b/src/KellerAcculevel.h @@ -55,7 +55,7 @@ class KellerAcculevel : public KellerParent class KellerAcculevel_Pressure : public Variable { public: - KellerAcculevel_Pressure(Sensor *parentSense, String UUID = "", String customVarCode = "") + KellerAcculevel_Pressure(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, KELLER_PRESSURE_VAR_NUM, F("pressureGauge"), F("millibar"), KellerAcculevel_PRESSURE_RESOLUTION, @@ -68,7 +68,7 @@ class KellerAcculevel_Pressure : public Variable class KellerAcculevel_Temp : public Variable { public: - KellerAcculevel_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + KellerAcculevel_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, KELLER_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), KellerAcculevel_TEMP_RESOLUTION, @@ -80,7 +80,7 @@ class KellerAcculevel_Temp : public Variable class KellerAcculevel_Height : public Variable { public: - KellerAcculevel_Height(Sensor *parentSense, String UUID = "", String customVarCode = "") + KellerAcculevel_Height(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, KELLER_HEIGHT_VAR_NUM, F("gaugeHeight"), F("meter"), KellerAcculevel_HEIGHT_RESOLUTION, diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 5369f399d..880e2be75 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -7,7 +7,7 @@ *This file is for the basic logging functions - ie, saving to an SD card. */ -#include "LoggerBase.h" // To communicate with the internet +#include "LoggerBase.h" // To prevent compiler/linker crashes with Enable interrupt #define LIBCALL_ENABLEINTERRUPT @@ -151,7 +151,7 @@ DateTime Logger::dtFromEpoch(uint32_t epochTime) } // This converts a date-time object into a ISO8601 formatted string -String Logger::formatDateTime_ISO8601(DateTime dt) +String Logger::formatDateTime_ISO8601(DateTime& dt) { // Set up an inital string String dateTimeStr; @@ -495,7 +495,7 @@ void Logger::setFileName(String& fileName) _autoFileName = false; } // Same as above, with a character array (overload function) -void Logger::setFileName(char* fileName) +void Logger::setFileName(char *fileName) { String StrName = String(fileName); setFileName(StrName); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 9389a8f75..a241d4819 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -77,7 +77,7 @@ class Logger static DateTime dtFromEpoch(uint32_t epochTime); // This converts a date-time object into a ISO8601 formatted string - static String formatDateTime_ISO8601(DateTime dt); + static String formatDateTime_ISO8601(DateTime& dt); // This converts an epoch time (unix time) into a ISO8601 formatted string static String formatDateTime_ISO8601(uint32_t epochTime); @@ -123,7 +123,7 @@ class Logger // Public functions for logging data to an SD card // ===================================================================== // // This sets a file name, if you want to decide on it in advance - void setFileName(char* fileName); + void setFileName(char *fileName); // Same as above, with a string (overload function) void setFileName(String& fileName); @@ -225,7 +225,7 @@ class Logger static char markedISO8601Time[26]; // Initialization variables - const char* _loggerID; + const char *_loggerID; uint16_t _loggingIntervalMinutes; int8_t _SDCardPin; int8_t _mcuWakePin; diff --git a/src/LoggerDreamHost.cpp b/src/LoggerDreamHost.cpp index b4c899ffa..db751b036 100644 --- a/src/LoggerDreamHost.cpp +++ b/src/LoggerDreamHost.cpp @@ -103,7 +103,7 @@ void LoggerDreamHost::streamDreamHostRequest(Stream *stream) // Post the data to dream host. -int LoggerDreamHost::postDataDreamHost(String fullURL) +int LoggerDreamHost::postDataDreamHost(String& fullURL) { // do not continue if no modem! if (!_modemAttached) diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index 00610a424..efad0822a 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -54,7 +54,7 @@ class LoggerDreamHost : public LoggerEnviroDIY // DreamHost URL and then streams out a get request // over that connection. // The return is the http status code of the response. - int postDataDreamHost(String fullURL = ""); + int postDataDreamHost(String& fullURL = VAR_BASE_EMPTY); // This prevents the logging function from dual-posting to EnviroDIY void disableDualPost(void); diff --git a/src/LoggerEnviroDIY.cpp b/src/LoggerEnviroDIY.cpp index b4ef4458f..d1358cd2b 100644 --- a/src/LoggerEnviroDIY.cpp +++ b/src/LoggerEnviroDIY.cpp @@ -191,7 +191,7 @@ void LoggerEnviroDIY::streamEnviroDIYRequest(Stream *stream) // EnviroDIY/ODM2DataSharingPortal and then streams out a post request // over that connection. // The return is the http status code of the response. -int LoggerEnviroDIY::postDataEnviroDIY(String enviroDIYjson) +int LoggerEnviroDIY::postDataEnviroDIY(String& enviroDIYjson) { // do not continue if no modem! if (!_modemAttached) diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index 1995d1a78..8e24a3edb 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -66,7 +66,7 @@ class LoggerEnviroDIY : public Logger // EnviroDIY/ODM2DataSharingPortal and then streams out a post request // over that connection. // The return is the http status code of the response. - int postDataEnviroDIY(String enviroDIYjson = ""); + int postDataEnviroDIY(String& enviroDIYjson = VAR_BASE_EMPTY); // ===================================================================== // // Convience functions to call several of the above functions diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 719fcaafc..4c02e8106 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -690,7 +690,7 @@ class loggerModem : public Sensor class Modem_RSSI : public Variable { public: - Modem_RSSI(Sensor *parentSense, String UUID = "", String customVarCode = "") + Modem_RSSI(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, RSSI_VAR_NUM, F("RSSI"), F("decibelMiliWatt"), RSSI_RESOLUTION, @@ -703,7 +703,7 @@ class Modem_RSSI : public Variable class Modem_SignalPercent : public Variable { public: - Modem_SignalPercent(Sensor *parentSense, String UUID = "", String customVarCode = "") + Modem_SignalPercent(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, PERCENT_SIGNAL_VAR_NUM, F("signalPercent"), F("percent"), PERCENT_SIGNAL_RESOLUTION, diff --git a/src/MaxBotixSonar.h b/src/MaxBotixSonar.h index aea38fa60..6fb727496 100644 --- a/src/MaxBotixSonar.h +++ b/src/MaxBotixSonar.h @@ -56,7 +56,7 @@ class MaxBotixSonar_Range : public Variable { public: MaxBotixSonar_Range(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, HRXL_VAR_NUM, F("distance"), F("millimeter"), HRXL_RESOLUTION, diff --git a/src/MaximDS18.h b/src/MaximDS18.h index 1215937ee..5e21334c0 100644 --- a/src/MaximDS18.h +++ b/src/MaximDS18.h @@ -72,7 +72,7 @@ class MaximDS18_Temp : public Variable { public: MaximDS18_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DS18_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DS18_TEMP_RESOLUTION, diff --git a/src/MaximDS3231.h b/src/MaximDS3231.h index a93af80ec..87bb4b16e 100644 --- a/src/MaximDS3231.h +++ b/src/MaximDS3231.h @@ -67,7 +67,7 @@ class MaximDS3231_Temp : public Variable { public: MaximDS3231_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DS3231_TEMP_VAR_NUM, F("temperatureRTC"), F("degreeCelsius"), DS3231_TEMP_RESOLUTION, diff --git a/src/MeaSpecMS5803.h b/src/MeaSpecMS5803.h index ff6082495..69a606ddd 100644 --- a/src/MeaSpecMS5803.h +++ b/src/MeaSpecMS5803.h @@ -89,7 +89,7 @@ class MeaSpecMS5803_Temp : public Variable { public: MeaSpecMS5803_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, MS5803_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), MS5803_TEMP_RESOLUTION, @@ -103,7 +103,7 @@ class MeaSpecMS5803_Pressure : public Variable { public: MeaSpecMS5803_Pressure(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, MS5803_PRESSURE_VAR_NUM, F("barometricPressure"), F("Millibar"), MS5803_PRESSURE_RESOLUTION, diff --git a/src/ProcessorStats.h b/src/ProcessorStats.h index d1cf35c4d..f2345cc70 100644 --- a/src/ProcessorStats.h +++ b/src/ProcessorStats.h @@ -61,7 +61,7 @@ class ProcessorStats_Batt : public Variable { public: ProcessorStats_Batt(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, PROCESSOR_BATTERY_VAR_NUM, F("batteryVoltage"), F("Volt"), PROCESSOR_BATTERY_RESOLUTION, @@ -75,7 +75,7 @@ class ProcessorStats_FreeRam : public Variable { public: ProcessorStats_FreeRam(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, PROCESSOR_RAM_VAR_NUM, F("Free SRAM"), F("Bit"), PROCESSOR_RAM_RESOLUTION, diff --git a/src/RainCounterI2C.h b/src/RainCounterI2C.h index 11ac0f3c3..394470a20 100644 --- a/src/RainCounterI2C.h +++ b/src/RainCounterI2C.h @@ -64,7 +64,7 @@ class RainCounterI2C_Tips : public Variable { public: RainCounterI2C_Tips(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BUCKET_TIPS_VAR_NUM, F("precipitation"), F("event"), BUCKET_TIPS_RESOLUTION, @@ -77,7 +77,7 @@ class RainCounterI2C_Depth : public Variable { public: RainCounterI2C_Depth(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, BUCKET_RAIN_VAR_NUM, F("precipitation"), F("millimeter"), BUCKET_RAIN_RESOLUTION, diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 2cb99d49a..ad3afd2ef 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -20,7 +20,7 @@ Variable::Variable(Sensor *parentSense, int varNum, String varName, String varUnit, unsigned int decimalResolution, String defaultVarCode, - String UUID, String customVarCode) + String& UUID, String& customVarCode) { isCalculated = false; _calcFxn = NULL; @@ -42,9 +42,9 @@ Variable::Variable(Sensor *parentSense, int varNum, // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable::Variable(float (*calcFxn)(), - String varName, String varUnit, + String& varName, String& varUnit, unsigned int decimalResolution, - String UUID, String customVarCode) + String& UUID, String& customVarCode) { isCalculated = true; _calcFxn = calcFxn; diff --git a/src/VariableBase.h b/src/VariableBase.h index 35934bfa6..b32b06ccb 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -15,6 +15,9 @@ // #define DEBUGGING_SERIAL_OUTPUT Serial #include "ModSensorDebugger.h" +static String VAR_BASE_UNKNOWN = "Unknown"; +static String VAR_BASE_EMPTY = ""; + class Sensor; // Forward declaration class Variable @@ -23,18 +26,18 @@ class Variable // The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable(Sensor *parentSense, int varNum, - String varName = "Unknown", String varUnit = "Unknown", + String varName = VAR_BASE_UNKNOWN, String varUnit = VAR_BASE_UNKNOWN, unsigned int decimalResolution = 0, - String defaultVarCode = "Unknown", - String UUID = "", String customVarCode = ""); + String defaultVarCode = VAR_BASE_UNKNOWN, + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY); // The constructor for a measured variable - that is, one whose value is // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable(float (*calcFxn)(), - String varName, String varUnit, + String& varName, String& varUnit, unsigned int decimalResolution, - String UUID, String customVarCode); + String& UUID, String& customVarCode); // These functions tie the variable and sensor together // They should never be called for a calculated variable diff --git a/src/YosemitechY4000.h b/src/YosemitechY4000.h index 6c85ab9ab..da9710fb8 100644 --- a/src/YosemitechY4000.h +++ b/src/YosemitechY4000.h @@ -123,7 +123,7 @@ class YosemitechY4000_DOmgL : public Variable { public: YosemitechY4000_DOmgL(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), Y4000_DOMGL_RESOLUTION, @@ -135,7 +135,7 @@ class YosemitechY4000_DOmgL : public Variable class YosemitechY4000_Turbidity : public Variable { public: - YosemitechY4000_Turbidity(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY4000_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y4000_TURB_RESOLUTION, @@ -147,7 +147,7 @@ class YosemitechY4000_Turbidity : public Variable class YosemitechY4000_Cond : public Variable { public: - YosemitechY4000_Cond(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY4000_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), Y4000_COND_RESOLUTION, @@ -160,7 +160,7 @@ class YosemitechY4000_pH : public Variable { public: YosemitechY4000_pH(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_PH_VAR_NUM, F("pH"), F("pH"), Y4000_PH_RESOLUTION, @@ -173,7 +173,7 @@ class YosemitechY4000_Temp : public Variable { public: YosemitechY4000_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y4000_TEMP_RESOLUTION, @@ -186,7 +186,7 @@ class YosemitechY4000_ORP : public Variable { public: YosemitechY4000_ORP(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_ORP_VAR_NUM, F("ORP"), F("millivolt"), Y4000_ORP_RESOLUTION, @@ -199,7 +199,7 @@ class YosemitechY4000_Chlorophyll : public Variable { public: YosemitechY4000_Chlorophyll(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_CHLORO_VAR_NUM, F("chlorophyllFluorescence"), F("microgramPerLiter"), Y4000_CHLORO_RESOLUTION, @@ -212,7 +212,7 @@ class YosemitechY4000_BGA : public Variable { public: YosemitechY4000_BGA(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y4000_BGA_VAR_NUM, F("blueGreenAlgaeCyanobacteriaPhycocyanin"), F("microgramPerLiter"), Y4000_BGA_RESOLUTION, diff --git a/src/YosemitechY504.h b/src/YosemitechY504.h index bd4c08747..bc10cf89c 100644 --- a/src/YosemitechY504.h +++ b/src/YosemitechY504.h @@ -72,7 +72,7 @@ class YosemitechY504_DOpct : public Variable { public: YosemitechY504_DOpct(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y504_DOPCT_VAR_NUM, F("oxygenDissolvedPercentOfSaturation"), F("percent"), Y504_DOPCT_RESOLUTION, @@ -86,7 +86,7 @@ class YosemitechY504_Temp : public Variable { public: YosemitechY504_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y504_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y504_TEMP_RESOLUTION, @@ -100,7 +100,7 @@ class YosemitechY504_DOmgL : public Variable { public: YosemitechY504_DOmgL(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y504_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), Y504_DOMGL_RESOLUTION, diff --git a/src/YosemitechY510.h b/src/YosemitechY510.h index 887c411ee..91c898e0f 100644 --- a/src/YosemitechY510.h +++ b/src/YosemitechY510.h @@ -68,7 +68,7 @@ class YosemitechY510 : public YosemitechParent class YosemitechY510_Turbidity : public Variable { public: - YosemitechY510_Turbidity(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY510_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y510_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y510_TURB_RESOLUTION, @@ -81,7 +81,7 @@ class YosemitechY510_Turbidity : public Variable class YosemitechY510_Temp : public Variable { public: - YosemitechY510_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY510_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y510_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y510_TEMP_RESOLUTION, diff --git a/src/YosemitechY511.h b/src/YosemitechY511.h index b0e2f6bb3..82c8d77f1 100644 --- a/src/YosemitechY511.h +++ b/src/YosemitechY511.h @@ -68,7 +68,7 @@ class YosemitechY511 : public YosemitechParent class YosemitechY511_Turbidity : public Variable { public: - YosemitechY511_Turbidity(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY511_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y511_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y511_TURB_RESOLUTION, @@ -81,7 +81,7 @@ class YosemitechY511_Turbidity : public Variable class YosemitechY511_Temp : public Variable { public: - YosemitechY511_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY511_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y511_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y511_TEMP_RESOLUTION, diff --git a/src/YosemitechY514.h b/src/YosemitechY514.h index 40f3944e9..d2704acf2 100644 --- a/src/YosemitechY514.h +++ b/src/YosemitechY514.h @@ -70,7 +70,7 @@ class YosemitechY514_Chlorophyll : public Variable { public: YosemitechY514_Chlorophyll(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y514_CHLORO_VAR_NUM, F("chlorophyllFluorescence"), F("microgramPerLiter"), Y514_CHLORO_RESOLUTION, @@ -84,7 +84,7 @@ class YosemitechY514_Temp : public Variable { public: YosemitechY514_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y514_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y514_TEMP_RESOLUTION, diff --git a/src/YosemitechY520.h b/src/YosemitechY520.h index 027deb7e5..42d839082 100644 --- a/src/YosemitechY520.h +++ b/src/YosemitechY520.h @@ -69,7 +69,7 @@ class YosemitechY520 : public YosemitechParent class YosemitechY520_Cond : public Variable { public: - YosemitechY520_Cond(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY520_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y520_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), Y520_COND_RESOLUTION, @@ -82,7 +82,7 @@ class YosemitechY520_Cond : public Variable class YosemitechY520_Temp : public Variable { public: - YosemitechY520_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY520_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y520_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y520_TEMP_RESOLUTION, diff --git a/src/YosemitechY532.h b/src/YosemitechY532.h index f59423984..d679bf764 100644 --- a/src/YosemitechY532.h +++ b/src/YosemitechY532.h @@ -73,7 +73,7 @@ class YosemitechY532_pH : public Variable { public: YosemitechY532_pH(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y532_PH_VAR_NUM, F("pH"), F("pH"), Y532_PH_RESOLUTION, @@ -87,7 +87,7 @@ class YosemitechY532_Temp : public Variable { public: YosemitechY532_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y532_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y532_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class YosemitechY532_Voltage : public Variable { public: YosemitechY532_Voltage(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y532_VOLT_VAR_NUM, F("voltage"), F("millivolt"), Y532_VOLT_RESOLUTION, diff --git a/src/YosemitechY533.h b/src/YosemitechY533.h index 9cfe07935..1c7bebe7d 100644 --- a/src/YosemitechY533.h +++ b/src/YosemitechY533.h @@ -78,7 +78,7 @@ class YosemitechY533_pH : public Variable { public: YosemitechY533_pH(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y533_PH_VAR_NUM, F("pH"), F("pH"), Y533_PH_RESOLUTION, @@ -92,7 +92,7 @@ class YosemitechY533_Temp : public Variable { public: YosemitechY533_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y533_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y533_TEMP_RESOLUTION, @@ -106,7 +106,7 @@ class YosemitechY533_Voltage : public Variable { public: YosemitechY533_Voltage(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y533_VOLT_VAR_NUM, F("voltage"), F("millivolt"), Y533_VOLT_RESOLUTION, diff --git a/src/YosemitechY550.h b/src/YosemitechY550.h index 0427478d1..35104c0df 100644 --- a/src/YosemitechY550.h +++ b/src/YosemitechY550.h @@ -75,7 +75,7 @@ class YosemitechY550 : public YosemitechParent class YosemitechY550_COD : public Variable { public: - YosemitechY550_COD(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY550_COD(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y550_COD_VAR_NUM, F("COD"), F("milligramPerLiter"), Y550_COD_RESOLUTION, @@ -88,7 +88,7 @@ class YosemitechY550_COD : public Variable class YosemitechY550_Temp : public Variable { public: - YosemitechY550_Temp(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY550_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y550_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y550_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class YosemitechY550_Temp : public Variable class YosemitechY550_Turbidity : public Variable { public: - YosemitechY550_Turbidity(Sensor *parentSense, String UUID = "", String customVarCode = "") + YosemitechY550_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, Y550_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y550_TURB_RESOLUTION, diff --git a/src/ZebraTechDOpto.h b/src/ZebraTechDOpto.h index 8a39b5d5f..05df6f794 100644 --- a/src/ZebraTechDOpto.h +++ b/src/ZebraTechDOpto.h @@ -82,7 +82,7 @@ class ZebraTechDOpto_Temp : public Variable { public: ZebraTechDOpto_Temp(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DOPTO_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DOPTO_TEMP_RESOLUTION, @@ -96,7 +96,7 @@ class ZebraTechDOpto_DOpct : public Variable { public: ZebraTechDOpto_DOpct(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DOPTO_DOPCT_VAR_NUM, F("oxygenDissolvedPercentOfSaturation"), F("percent"), DOPTO_DOPCT_RESOLUTION, @@ -110,7 +110,7 @@ class ZebraTechDOpto_DOmgL : public Variable { public: ZebraTechDOpto_DOmgL(Sensor *parentSense, - String UUID = "", String customVarCode = "") + String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : Variable(parentSense, DOPTO_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), DOPTO_DOMGL_RESOLUTION, From 15df45fed0c975e1419d9271f6a23e4520104f49 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 15:34:28 -0400 Subject: [PATCH 44/54] Strings to character arrays --- .../baro_rho_correction/baro_rho_correction.ino | 12 ++++++------ examples/data_saving/data_saving.ino | 2 +- src/AOSongAM2315.h | 4 ++-- src/AOSongDHT.h | 6 +++--- src/ApogeeSQ212.h | 2 +- src/BoschBME280.h | 8 ++++---- src/CampbellOBS3.h | 2 +- src/Decagon5TM.h | 6 +++--- src/DecagonCTD.h | 6 +++--- src/DecagonES2.h | 4 ++-- src/ExternalVoltage.h | 2 +- src/FreescaleMPL115A2.h | 4 ++-- src/KellerAcculevel.h | 6 +++--- src/LoggerBase.h | 2 ++ src/LoggerDreamHost.h | 2 +- src/LoggerEnviroDIY.h | 2 +- src/LoggerModem.h | 4 ++-- src/MaxBotixSonar.h | 2 +- src/MaximDS18.h | 2 +- src/MaximDS3231.h | 2 +- src/MeaSpecMS5803.h | 4 ++-- src/ProcessorStats.h | 4 ++-- src/RainCounterI2C.h | 4 ++-- src/VariableBase.cpp | 4 ++-- src/VariableBase.h | 11 +++++------ src/YosemitechY4000.h | 16 ++++++++-------- src/YosemitechY504.h | 6 +++--- src/YosemitechY510.h | 4 ++-- src/YosemitechY511.h | 4 ++-- src/YosemitechY514.h | 4 ++-- src/YosemitechY520.h | 4 ++-- src/YosemitechY532.h | 6 +++--- src/YosemitechY533.h | 6 +++--- src/YosemitechY550.h | 6 +++--- src/ZebraTechDOpto.h | 6 +++--- 35 files changed, 85 insertions(+), 84 deletions(-) diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index ef6fdd5bc..8ac9f4c51 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -197,8 +197,8 @@ float calculateWaterPressure(void) String waterPresureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ String waterPresureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ int waterPresureVarResolution = 3; -String waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; -String waterPresureVarCode = "CorrectedPressure"; +const char *waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; +const char *waterPresureVarCode = "CorrectedPressure"; // Create the calculated water pressure variable objects and return a variable pointer to it Variable *calcWaterPress = new Variable(calculateWaterPressure, waterPresureVarName, waterPresureVarUnit, waterPresureVarResolution, @@ -219,8 +219,8 @@ float calculateWaterDepthRaw(void) String waterDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ String waterDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ int waterDepthVarResolution = 3; -String waterDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; -String waterDepthVarCode = "CalcDepth"; +const char *waterDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; +const char *waterDepthVarCode = "CalcDepth"; // Create the calculated raw water depth variable objects and return a variable pointer to it Variable *calcRawDepth = new Variable(calculateWaterDepthRaw, waterDepthVarName, waterDepthVarUnit, waterDepthVarResolution, @@ -255,8 +255,8 @@ float calculateWaterDepthTempCorrected(void) String rhoDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ String rhoDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ int rhoDepthVarResolution = 3; -String rhoDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; -String rhoDepthVarCode = "DensityDepth"; +const char *rhoDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; +const char *rhoDepthVarCode = "DensityDepth"; // Create the temperature corrected water depth variable objects and return a variable pointer to it Variable *calcCorrDepth = new Variable(calculateWaterDepthTempCorrected, rhoDepthVarName, rhoDepthVarUnit, rhoDepthVarResolution, diff --git a/examples/data_saving/data_saving.ino b/examples/data_saving/data_saving.ino index 7fc23e233..c6fae0733 100644 --- a/examples/data_saving/data_saving.ino +++ b/examples/data_saving/data_saving.ino @@ -59,7 +59,7 @@ const int8_t sdCardPin = 12; // SD Card Chip Select/Slave Select Pin (must be d // Create and return the processor "sensor" const char *MFVersion = "v0.5"; -ProcessorStats mayfly(MFVersion) ; +ProcessorStats mayfly(MFVersion); // Create the battery voltage and free RAM variable objects for the Y504 and return variable-type pointers to them Variable *mayflyBatt = new ProcessorStats_Batt(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"); Variable *mayflyRAM = new ProcessorStats_FreeRam(&mayfly, "12345678-abcd-1234-efgh-1234567890ab"); diff --git a/src/AOSongAM2315.h b/src/AOSongAM2315.h index 8ca5127fd..164dc8d0d 100644 --- a/src/AOSongAM2315.h +++ b/src/AOSongAM2315.h @@ -65,7 +65,7 @@ class AOSongAM2315_Humidity : public Variable { public: AOSongAM2315_Humidity(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, AM2315_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), AM2315_HUMIDITY_RESOLUTION, @@ -79,7 +79,7 @@ class AOSongAM2315_Temp : public Variable { public: AOSongAM2315_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) : + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, AM2315_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), AM2315_TEMP_RESOLUTION, diff --git a/src/AOSongDHT.h b/src/AOSongDHT.h index 68f2ac7f8..802f2f243 100644 --- a/src/AOSongDHT.h +++ b/src/AOSongDHT.h @@ -90,7 +90,7 @@ class AOSongDHT_Humidity : public Variable { public: AOSongDHT_Humidity(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), DHT_HUMIDITY_RESOLUTION, @@ -104,7 +104,7 @@ class AOSongDHT_Temp : public Variable { public: AOSongDHT_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DHT_TEMP_RESOLUTION, @@ -118,7 +118,7 @@ class AOSongDHT_HI : public Variable { public: AOSongDHT_HI(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_HI_VAR_NUM, F("heatIndex"), F("degreeCelsius"), DHT_HI_RESOLUTION, diff --git a/src/ApogeeSQ212.h b/src/ApogeeSQ212.h index ec99d539f..548115418 100644 --- a/src/ApogeeSQ212.h +++ b/src/ApogeeSQ212.h @@ -74,7 +74,7 @@ class ApogeeSQ212_PAR : public Variable { public: ApogeeSQ212_PAR(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, SQ212_PAR_VAR_NUM, F("radiationIncomingPAR"), F("microeinsteinPerSquareMeterPerSecond"), SQ212_PAR_RESOLUTION, diff --git a/src/BoschBME280.h b/src/BoschBME280.h index 6373e78ce..dfab7ff71 100644 --- a/src/BoschBME280.h +++ b/src/BoschBME280.h @@ -84,7 +84,7 @@ class BoschBME280_Temp : public Variable { public: BoschBME280_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), BME280_TEMP_RESOLUTION, @@ -98,7 +98,7 @@ class BoschBME280_Humidity : public Variable { public: BoschBME280_Humidity(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_HUMIDITY_VAR_NUM, F("relativeHumidity"), F("percent"), BME280_HUMIDITY_RESOLUTION, @@ -112,7 +112,7 @@ class BoschBME280_Pressure : public Variable { public: BoschBME280_Pressure(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_PRESSURE_VAR_NUM, F("barometricPressure"), F("pascal"), BME280_PRESSURE_RESOLUTION, @@ -126,7 +126,7 @@ class BoschBME280_Altitude : public Variable { public: BoschBME280_Altitude(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_ALTITUDE_VAR_NUM, F("heightAboveSeaFloor"), F("meter"), BME280_ALTITUDE_RESOLUTION, diff --git a/src/CampbellOBS3.h b/src/CampbellOBS3.h index 2a8bf524f..41b576958 100644 --- a/src/CampbellOBS3.h +++ b/src/CampbellOBS3.h @@ -74,7 +74,7 @@ class CampbellOBS3_Turbidity : public Variable { public: CampbellOBS3_Turbidity(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, OBS3_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), OBS3_RESOLUTION, diff --git a/src/Decagon5TM.h b/src/Decagon5TM.h index e3ebcbda1..dfcbd1d5e 100644 --- a/src/Decagon5TM.h +++ b/src/Decagon5TM.h @@ -75,7 +75,7 @@ class Decagon5TM : public SDI12Sensors class Decagon5TM_Ea : public Variable { public: - Decagon5TM_Ea(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + Decagon5TM_Ea(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_EA_VAR_NUM, F("permittivity"), F("faradPerMeter"), TM_EA_RESOLUTION, @@ -88,7 +88,7 @@ class Decagon5TM_Ea : public Variable class Decagon5TM_Temp : public Variable { public: - Decagon5TM_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + Decagon5TM_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), TM_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class Decagon5TM_Temp : public Variable class Decagon5TM_VWC : public Variable { public: - Decagon5TM_VWC(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + Decagon5TM_VWC(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_VWC_VAR_NUM, F("volumetricWaterContent"), F("percent"), TM_VWC_RESOLUTION, diff --git a/src/DecagonCTD.h b/src/DecagonCTD.h index a7a160915..7de3dbe31 100644 --- a/src/DecagonCTD.h +++ b/src/DecagonCTD.h @@ -78,7 +78,7 @@ class DecagonCTD : public SDI12Sensors class DecagonCTD_Cond : public Variable { public: - DecagonCTD_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + DecagonCTD_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), CTD_COND_RESOLUTION, @@ -91,7 +91,7 @@ class DecagonCTD_Cond : public Variable class DecagonCTD_Temp : public Variable { public: - DecagonCTD_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + DecagonCTD_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), CTD_TEMP_RESOLUTION, @@ -104,7 +104,7 @@ class DecagonCTD_Temp : public Variable class DecagonCTD_Depth : public Variable { public: - DecagonCTD_Depth(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + DecagonCTD_Depth(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_DEPTH_VAR_NUM, F("waterDepth"), F("millimeter"), CTD_DEPTH_RESOLUTION, diff --git a/src/DecagonES2.h b/src/DecagonES2.h index 0f6344f33..d83097eaa 100644 --- a/src/DecagonES2.h +++ b/src/DecagonES2.h @@ -69,7 +69,7 @@ class DecagonES2 : public SDI12Sensors class DecagonES2_Cond : public Variable { public: - DecagonES2_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + DecagonES2_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, ES2_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), ES2_COND_RESOLUTION, @@ -81,7 +81,7 @@ class DecagonES2_Cond : public Variable class DecagonES2_Temp : public Variable { public: - DecagonES2_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + DecagonES2_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, ES2_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), ES2_TEMP_RESOLUTION, diff --git a/src/ExternalVoltage.h b/src/ExternalVoltage.h index eddfa7f8d..8a0cfba05 100644 --- a/src/ExternalVoltage.h +++ b/src/ExternalVoltage.h @@ -81,7 +81,7 @@ class ExternalVoltage_Volt : public Variable { public: ExternalVoltage_Volt(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, EXT_VOLT_VAR_NUM, F("voltage"), F("volt"), EXT_VOLT_RESOLUTION, diff --git a/src/FreescaleMPL115A2.h b/src/FreescaleMPL115A2.h index c5dd53451..408ff1de1 100644 --- a/src/FreescaleMPL115A2.h +++ b/src/FreescaleMPL115A2.h @@ -67,7 +67,7 @@ class MPL115A2_Temp : public Variable { public: MPL115A2_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MPL115A2_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), MPL115A2_TEMP_RESOLUTION, @@ -81,7 +81,7 @@ class MPL115A2_Pressure : public Variable { public: MPL115A2_Pressure(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MPL115A2_PRESSURE_VAR_NUM, F("atmosphericPressure"), F("kPa"), MPL115A2_PRESSURE_RESOLUTION, diff --git a/src/KellerAcculevel.h b/src/KellerAcculevel.h index 5052f779b..ff971154d 100644 --- a/src/KellerAcculevel.h +++ b/src/KellerAcculevel.h @@ -55,7 +55,7 @@ class KellerAcculevel : public KellerParent class KellerAcculevel_Pressure : public Variable { public: - KellerAcculevel_Pressure(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + KellerAcculevel_Pressure(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_PRESSURE_VAR_NUM, F("pressureGauge"), F("millibar"), KellerAcculevel_PRESSURE_RESOLUTION, @@ -68,7 +68,7 @@ class KellerAcculevel_Pressure : public Variable class KellerAcculevel_Temp : public Variable { public: - KellerAcculevel_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + KellerAcculevel_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), KellerAcculevel_TEMP_RESOLUTION, @@ -80,7 +80,7 @@ class KellerAcculevel_Temp : public Variable class KellerAcculevel_Height : public Variable { public: - KellerAcculevel_Height(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + KellerAcculevel_Height(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_HEIGHT_VAR_NUM, F("gaugeHeight"), F("meter"), KellerAcculevel_HEIGHT_RESOLUTION, diff --git a/src/LoggerBase.h b/src/LoggerBase.h index a241d4819..538cc4918 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -35,6 +35,8 @@ #include // To communicate with the SD card +static String LOGGER_EMPTY = ""; + // Defines the "Logger" Class class Logger { diff --git a/src/LoggerDreamHost.h b/src/LoggerDreamHost.h index efad0822a..ef0805ec6 100644 --- a/src/LoggerDreamHost.h +++ b/src/LoggerDreamHost.h @@ -54,7 +54,7 @@ class LoggerDreamHost : public LoggerEnviroDIY // DreamHost URL and then streams out a get request // over that connection. // The return is the http status code of the response. - int postDataDreamHost(String& fullURL = VAR_BASE_EMPTY); + int postDataDreamHost(String& fullURL = LOGGER_EMPTY); // This prevents the logging function from dual-posting to EnviroDIY void disableDualPost(void); diff --git a/src/LoggerEnviroDIY.h b/src/LoggerEnviroDIY.h index 8e24a3edb..a67eea951 100644 --- a/src/LoggerEnviroDIY.h +++ b/src/LoggerEnviroDIY.h @@ -66,7 +66,7 @@ class LoggerEnviroDIY : public Logger // EnviroDIY/ODM2DataSharingPortal and then streams out a post request // over that connection. // The return is the http status code of the response. - int postDataEnviroDIY(String& enviroDIYjson = VAR_BASE_EMPTY); + int postDataEnviroDIY(String& enviroDIYjson = LOGGER_EMPTY); // ===================================================================== // // Convience functions to call several of the above functions diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 4c02e8106..0601042be 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -690,7 +690,7 @@ class loggerModem : public Sensor class Modem_RSSI : public Variable { public: - Modem_RSSI(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + Modem_RSSI(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, RSSI_VAR_NUM, F("RSSI"), F("decibelMiliWatt"), RSSI_RESOLUTION, @@ -703,7 +703,7 @@ class Modem_RSSI : public Variable class Modem_SignalPercent : public Variable { public: - Modem_SignalPercent(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + Modem_SignalPercent(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PERCENT_SIGNAL_VAR_NUM, F("signalPercent"), F("percent"), PERCENT_SIGNAL_RESOLUTION, diff --git a/src/MaxBotixSonar.h b/src/MaxBotixSonar.h index 6fb727496..985dce623 100644 --- a/src/MaxBotixSonar.h +++ b/src/MaxBotixSonar.h @@ -56,7 +56,7 @@ class MaxBotixSonar_Range : public Variable { public: MaxBotixSonar_Range(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, HRXL_VAR_NUM, F("distance"), F("millimeter"), HRXL_RESOLUTION, diff --git a/src/MaximDS18.h b/src/MaximDS18.h index 5e21334c0..0e1a65ce3 100644 --- a/src/MaximDS18.h +++ b/src/MaximDS18.h @@ -72,7 +72,7 @@ class MaximDS18_Temp : public Variable { public: MaximDS18_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DS18_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DS18_TEMP_RESOLUTION, diff --git a/src/MaximDS3231.h b/src/MaximDS3231.h index 87bb4b16e..fc275d9c2 100644 --- a/src/MaximDS3231.h +++ b/src/MaximDS3231.h @@ -67,7 +67,7 @@ class MaximDS3231_Temp : public Variable { public: MaximDS3231_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DS3231_TEMP_VAR_NUM, F("temperatureRTC"), F("degreeCelsius"), DS3231_TEMP_RESOLUTION, diff --git a/src/MeaSpecMS5803.h b/src/MeaSpecMS5803.h index 69a606ddd..e3556cdf8 100644 --- a/src/MeaSpecMS5803.h +++ b/src/MeaSpecMS5803.h @@ -89,7 +89,7 @@ class MeaSpecMS5803_Temp : public Variable { public: MeaSpecMS5803_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MS5803_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), MS5803_TEMP_RESOLUTION, @@ -103,7 +103,7 @@ class MeaSpecMS5803_Pressure : public Variable { public: MeaSpecMS5803_Pressure(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MS5803_PRESSURE_VAR_NUM, F("barometricPressure"), F("Millibar"), MS5803_PRESSURE_RESOLUTION, diff --git a/src/ProcessorStats.h b/src/ProcessorStats.h index f2345cc70..6a02516f2 100644 --- a/src/ProcessorStats.h +++ b/src/ProcessorStats.h @@ -61,7 +61,7 @@ class ProcessorStats_Batt : public Variable { public: ProcessorStats_Batt(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PROCESSOR_BATTERY_VAR_NUM, F("batteryVoltage"), F("Volt"), PROCESSOR_BATTERY_RESOLUTION, @@ -75,7 +75,7 @@ class ProcessorStats_FreeRam : public Variable { public: ProcessorStats_FreeRam(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PROCESSOR_RAM_VAR_NUM, F("Free SRAM"), F("Bit"), PROCESSOR_RAM_RESOLUTION, diff --git a/src/RainCounterI2C.h b/src/RainCounterI2C.h index 394470a20..f9ab0bad5 100644 --- a/src/RainCounterI2C.h +++ b/src/RainCounterI2C.h @@ -64,7 +64,7 @@ class RainCounterI2C_Tips : public Variable { public: RainCounterI2C_Tips(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BUCKET_TIPS_VAR_NUM, F("precipitation"), F("event"), BUCKET_TIPS_RESOLUTION, @@ -77,7 +77,7 @@ class RainCounterI2C_Depth : public Variable { public: RainCounterI2C_Depth(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BUCKET_RAIN_VAR_NUM, F("precipitation"), F("millimeter"), BUCKET_RAIN_RESOLUTION, diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index ad3afd2ef..637d32845 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -20,7 +20,7 @@ Variable::Variable(Sensor *parentSense, int varNum, String varName, String varUnit, unsigned int decimalResolution, String defaultVarCode, - String& UUID, String& customVarCode) + const char *UUID, const char *customVarCode) { isCalculated = false; _calcFxn = NULL; @@ -44,7 +44,7 @@ Variable::Variable(Sensor *parentSense, int varNum, Variable::Variable(float (*calcFxn)(), String& varName, String& varUnit, unsigned int decimalResolution, - String& UUID, String& customVarCode) + const char *UUID, const char *customVarCode) { isCalculated = true; _calcFxn = calcFxn; diff --git a/src/VariableBase.h b/src/VariableBase.h index b32b06ccb..a568e0b6b 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -15,8 +15,7 @@ // #define DEBUGGING_SERIAL_OUTPUT Serial #include "ModSensorDebugger.h" -static String VAR_BASE_UNKNOWN = "Unknown"; -static String VAR_BASE_EMPTY = ""; +const char* VAR_BASE_UNKNOWN = "Unknown"; class Sensor; // Forward declaration @@ -29,7 +28,7 @@ class Variable String varName = VAR_BASE_UNKNOWN, String varUnit = VAR_BASE_UNKNOWN, unsigned int decimalResolution = 0, String defaultVarCode = VAR_BASE_UNKNOWN, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY); + const char *UUID = "", const char *customVarCode = ""); // The constructor for a measured variable - that is, one whose value is // calculated by the calcFxn which returns a float. @@ -37,7 +36,7 @@ class Variable Variable(float (*calcFxn)(), String& varName, String& varUnit, unsigned int decimalResolution, - String& UUID, String& customVarCode); + const char *UUID, const char *customVarCode); // These functions tie the variable and sensor together // They should never be called for a calculated variable @@ -84,8 +83,8 @@ class Variable String _varUnit; unsigned int _decimalResolution; String _defaultVarCode; - String _customCode; - String _UUID; + const char *_customCode; + const char *_UUID; }; #endif diff --git a/src/YosemitechY4000.h b/src/YosemitechY4000.h index da9710fb8..d84720b21 100644 --- a/src/YosemitechY4000.h +++ b/src/YosemitechY4000.h @@ -123,7 +123,7 @@ class YosemitechY4000_DOmgL : public Variable { public: YosemitechY4000_DOmgL(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), Y4000_DOMGL_RESOLUTION, @@ -135,7 +135,7 @@ class YosemitechY4000_DOmgL : public Variable class YosemitechY4000_Turbidity : public Variable { public: - YosemitechY4000_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY4000_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y4000_TURB_RESOLUTION, @@ -147,7 +147,7 @@ class YosemitechY4000_Turbidity : public Variable class YosemitechY4000_Cond : public Variable { public: - YosemitechY4000_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY4000_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), Y4000_COND_RESOLUTION, @@ -160,7 +160,7 @@ class YosemitechY4000_pH : public Variable { public: YosemitechY4000_pH(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_PH_VAR_NUM, F("pH"), F("pH"), Y4000_PH_RESOLUTION, @@ -173,7 +173,7 @@ class YosemitechY4000_Temp : public Variable { public: YosemitechY4000_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y4000_TEMP_RESOLUTION, @@ -186,7 +186,7 @@ class YosemitechY4000_ORP : public Variable { public: YosemitechY4000_ORP(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_ORP_VAR_NUM, F("ORP"), F("millivolt"), Y4000_ORP_RESOLUTION, @@ -199,7 +199,7 @@ class YosemitechY4000_Chlorophyll : public Variable { public: YosemitechY4000_Chlorophyll(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_CHLORO_VAR_NUM, F("chlorophyllFluorescence"), F("microgramPerLiter"), Y4000_CHLORO_RESOLUTION, @@ -212,7 +212,7 @@ class YosemitechY4000_BGA : public Variable { public: YosemitechY4000_BGA(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_BGA_VAR_NUM, F("blueGreenAlgaeCyanobacteriaPhycocyanin"), F("microgramPerLiter"), Y4000_BGA_RESOLUTION, diff --git a/src/YosemitechY504.h b/src/YosemitechY504.h index bc10cf89c..63585be79 100644 --- a/src/YosemitechY504.h +++ b/src/YosemitechY504.h @@ -72,7 +72,7 @@ class YosemitechY504_DOpct : public Variable { public: YosemitechY504_DOpct(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_DOPCT_VAR_NUM, F("oxygenDissolvedPercentOfSaturation"), F("percent"), Y504_DOPCT_RESOLUTION, @@ -86,7 +86,7 @@ class YosemitechY504_Temp : public Variable { public: YosemitechY504_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y504_TEMP_RESOLUTION, @@ -100,7 +100,7 @@ class YosemitechY504_DOmgL : public Variable { public: YosemitechY504_DOmgL(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), Y504_DOMGL_RESOLUTION, diff --git a/src/YosemitechY510.h b/src/YosemitechY510.h index 91c898e0f..708c24d60 100644 --- a/src/YosemitechY510.h +++ b/src/YosemitechY510.h @@ -68,7 +68,7 @@ class YosemitechY510 : public YosemitechParent class YosemitechY510_Turbidity : public Variable { public: - YosemitechY510_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY510_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y510_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y510_TURB_RESOLUTION, @@ -81,7 +81,7 @@ class YosemitechY510_Turbidity : public Variable class YosemitechY510_Temp : public Variable { public: - YosemitechY510_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY510_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y510_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y510_TEMP_RESOLUTION, diff --git a/src/YosemitechY511.h b/src/YosemitechY511.h index 82c8d77f1..0c82e8fe5 100644 --- a/src/YosemitechY511.h +++ b/src/YosemitechY511.h @@ -68,7 +68,7 @@ class YosemitechY511 : public YosemitechParent class YosemitechY511_Turbidity : public Variable { public: - YosemitechY511_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY511_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y511_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y511_TURB_RESOLUTION, @@ -81,7 +81,7 @@ class YosemitechY511_Turbidity : public Variable class YosemitechY511_Temp : public Variable { public: - YosemitechY511_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY511_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y511_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y511_TEMP_RESOLUTION, diff --git a/src/YosemitechY514.h b/src/YosemitechY514.h index d2704acf2..5682fd369 100644 --- a/src/YosemitechY514.h +++ b/src/YosemitechY514.h @@ -70,7 +70,7 @@ class YosemitechY514_Chlorophyll : public Variable { public: YosemitechY514_Chlorophyll(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y514_CHLORO_VAR_NUM, F("chlorophyllFluorescence"), F("microgramPerLiter"), Y514_CHLORO_RESOLUTION, @@ -84,7 +84,7 @@ class YosemitechY514_Temp : public Variable { public: YosemitechY514_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y514_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y514_TEMP_RESOLUTION, diff --git a/src/YosemitechY520.h b/src/YosemitechY520.h index 42d839082..c3e7ca18a 100644 --- a/src/YosemitechY520.h +++ b/src/YosemitechY520.h @@ -69,7 +69,7 @@ class YosemitechY520 : public YosemitechParent class YosemitechY520_Cond : public Variable { public: - YosemitechY520_Cond(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY520_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y520_COND_VAR_NUM, F("specificConductance"), F("microsiemenPerCentimeter"), Y520_COND_RESOLUTION, @@ -82,7 +82,7 @@ class YosemitechY520_Cond : public Variable class YosemitechY520_Temp : public Variable { public: - YosemitechY520_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY520_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y520_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y520_TEMP_RESOLUTION, diff --git a/src/YosemitechY532.h b/src/YosemitechY532.h index d679bf764..c1305da3c 100644 --- a/src/YosemitechY532.h +++ b/src/YosemitechY532.h @@ -73,7 +73,7 @@ class YosemitechY532_pH : public Variable { public: YosemitechY532_pH(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_PH_VAR_NUM, F("pH"), F("pH"), Y532_PH_RESOLUTION, @@ -87,7 +87,7 @@ class YosemitechY532_Temp : public Variable { public: YosemitechY532_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y532_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class YosemitechY532_Voltage : public Variable { public: YosemitechY532_Voltage(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_VOLT_VAR_NUM, F("voltage"), F("millivolt"), Y532_VOLT_RESOLUTION, diff --git a/src/YosemitechY533.h b/src/YosemitechY533.h index 1c7bebe7d..a38cff30f 100644 --- a/src/YosemitechY533.h +++ b/src/YosemitechY533.h @@ -78,7 +78,7 @@ class YosemitechY533_pH : public Variable { public: YosemitechY533_pH(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_PH_VAR_NUM, F("pH"), F("pH"), Y533_PH_RESOLUTION, @@ -92,7 +92,7 @@ class YosemitechY533_Temp : public Variable { public: YosemitechY533_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y533_TEMP_RESOLUTION, @@ -106,7 +106,7 @@ class YosemitechY533_Voltage : public Variable { public: YosemitechY533_Voltage(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_VOLT_VAR_NUM, F("voltage"), F("millivolt"), Y533_VOLT_RESOLUTION, diff --git a/src/YosemitechY550.h b/src/YosemitechY550.h index 35104c0df..496282409 100644 --- a/src/YosemitechY550.h +++ b/src/YosemitechY550.h @@ -75,7 +75,7 @@ class YosemitechY550 : public YosemitechParent class YosemitechY550_COD : public Variable { public: - YosemitechY550_COD(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY550_COD(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_COD_VAR_NUM, F("COD"), F("milligramPerLiter"), Y550_COD_RESOLUTION, @@ -88,7 +88,7 @@ class YosemitechY550_COD : public Variable class YosemitechY550_Temp : public Variable { public: - YosemitechY550_Temp(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY550_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), Y550_TEMP_RESOLUTION, @@ -101,7 +101,7 @@ class YosemitechY550_Temp : public Variable class YosemitechY550_Turbidity : public Variable { public: - YosemitechY550_Turbidity(Sensor *parentSense, String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + YosemitechY550_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_TURB_VAR_NUM, F("turbidity"), F("nephelometricTurbidityUnit"), Y550_TURB_RESOLUTION, diff --git a/src/ZebraTechDOpto.h b/src/ZebraTechDOpto.h index 05df6f794..22020d48a 100644 --- a/src/ZebraTechDOpto.h +++ b/src/ZebraTechDOpto.h @@ -82,7 +82,7 @@ class ZebraTechDOpto_Temp : public Variable { public: ZebraTechDOpto_Temp(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_TEMP_VAR_NUM, F("temperature"), F("degreeCelsius"), DOPTO_TEMP_RESOLUTION, @@ -96,7 +96,7 @@ class ZebraTechDOpto_DOpct : public Variable { public: ZebraTechDOpto_DOpct(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_DOPCT_VAR_NUM, F("oxygenDissolvedPercentOfSaturation"), F("percent"), DOPTO_DOPCT_RESOLUTION, @@ -110,7 +110,7 @@ class ZebraTechDOpto_DOmgL : public Variable { public: ZebraTechDOpto_DOmgL(Sensor *parentSense, - String& UUID = VAR_BASE_EMPTY, String& customVarCode = VAR_BASE_EMPTY) + const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_DOMGL_VAR_NUM, F("oxygenDissolved"), F("milligramPerLiter"), DOPTO_DOMGL_RESOLUTION, From 70846cb61ca0816181d9e70b6a163d58d5a1d5b1 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 16:15:42 -0400 Subject: [PATCH 45/54] Lots more string to char --- src/AOSongAM2315.cpp | 2 +- src/AOSongAM2315.h | 8 ++++---- src/AOSongDHT.cpp | 2 +- src/AOSongDHT.h | 12 ++++++------ src/ApogeeSQ212.cpp | 2 +- src/ApogeeSQ212.h | 4 ++-- src/BoschBME280.cpp | 2 +- src/BoschBME280.h | 16 ++++++++-------- src/CampbellOBS3.cpp | 2 +- src/CampbellOBS3.h | 4 ++-- src/Decagon5TM.h | 18 +++++++++--------- src/DecagonCTD.h | 18 +++++++++--------- src/DecagonES2.h | 14 +++++++------- src/ExternalVoltage.cpp | 2 +- src/ExternalVoltage.h | 6 +++--- src/FreescaleMPL115A2.cpp | 2 +- src/FreescaleMPL115A2.h | 8 ++++---- src/KellerAcculevel.h | 16 ++++++++-------- src/KellerParent.cpp | 4 ++-- src/KellerParent.h | 4 ++-- src/LoggerModem.h | 2 +- src/MaxBotixSonar.cpp | 4 ++-- src/MaxBotixSonar.h | 4 ++-- src/MaximDS18.cpp | 4 ++-- src/MaximDS18.h | 4 ++-- src/MaximDS3231.h | 6 +++--- src/MeaSpecMS5803.cpp | 2 +- src/MeaSpecMS5803.h | 8 ++++---- src/ProcessorStats.cpp | 2 +- src/ProcessorStats.h | 8 ++++---- src/RainCounterI2C.cpp | 2 +- src/RainCounterI2C.h | 8 ++++---- src/SDI12Sensors.cpp | 6 +++--- src/SDI12Sensors.h | 6 +++--- src/SensorBase.cpp | 2 +- src/SensorBase.h | 4 ++-- src/VariableBase.cpp | 8 ++++---- src/VariableBase.h | 12 ++++++------ src/YosemitechParent.cpp | 4 ++-- src/YosemitechParent.h | 4 ++-- src/YosemitechY4000.h | 36 ++++++++++++++++++------------------ src/YosemitechY504.h | 16 ++++++++-------- src/YosemitechY510.h | 12 ++++++------ src/YosemitechY511.h | 12 ++++++------ src/YosemitechY514.h | 12 ++++++------ src/YosemitechY520.h | 12 ++++++------ src/YosemitechY532.h | 16 ++++++++-------- src/YosemitechY533.h | 16 ++++++++-------- src/YosemitechY550.h | 16 ++++++++-------- src/ZebraTechDOpto.h | 18 +++++++++--------- 50 files changed, 206 insertions(+), 206 deletions(-) diff --git a/src/AOSongAM2315.cpp b/src/AOSongAM2315.cpp index a1168d3f9..c7d012d74 100644 --- a/src/AOSongAM2315.cpp +++ b/src/AOSongAM2315.cpp @@ -27,7 +27,7 @@ // The constructor - because this is I2C, only need the power pin // This sensor has a set I2C address of 0XB8 AOSongAM2315::AOSongAM2315(int8_t powerPin, uint8_t measurementsToAverage) - : Sensor(F("AOSongAM2315"), AM2315_NUM_VARIABLES, + : Sensor("AOSongAM2315", AM2315_NUM_VARIABLES, AM2315_WARM_UP_TIME_MS, AM2315_STABILIZATION_TIME_MS, AM2315_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) {} diff --git a/src/AOSongAM2315.h b/src/AOSongAM2315.h index 164dc8d0d..c5623d2af 100644 --- a/src/AOSongAM2315.h +++ b/src/AOSongAM2315.h @@ -67,9 +67,9 @@ class AOSongAM2315_Humidity : public Variable AOSongAM2315_Humidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, AM2315_HUMIDITY_VAR_NUM, - F("relativeHumidity"), F("percent"), + "relativeHumidity", "percent", AM2315_HUMIDITY_RESOLUTION, - F("AM2315Humidity"), UUID, customVarCode) + "AM2315Humidity", UUID, customVarCode) {} }; @@ -81,9 +81,9 @@ class AOSongAM2315_Temp : public Variable AOSongAM2315_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, AM2315_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", AM2315_TEMP_RESOLUTION, - F("AM2315Temp"), UUID, customVarCode) + "AM2315Temp", UUID, customVarCode) {} }; diff --git a/src/AOSongDHT.cpp b/src/AOSongDHT.cpp index 4d69c9a2c..3d8ccaf05 100644 --- a/src/AOSongDHT.cpp +++ b/src/AOSongDHT.cpp @@ -28,7 +28,7 @@ // The constructor - need the power pin, data pin, and type of DHT AOSongDHT::AOSongDHT(int8_t powerPin, int8_t dataPin, DHTtype type, uint8_t measurementsToAverage) - : Sensor(F("AOSongDHT"), DHT_NUM_VARIABLES, + : Sensor("AOSongDHT", DHT_NUM_VARIABLES, DHT_WARM_UP_TIME_MS, DHT_STABILIZATION_TIME_MS, DHT_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage), dht_internal(dataPin, type) diff --git a/src/AOSongDHT.h b/src/AOSongDHT.h index 802f2f243..ef740855c 100644 --- a/src/AOSongDHT.h +++ b/src/AOSongDHT.h @@ -92,9 +92,9 @@ class AOSongDHT_Humidity : public Variable AOSongDHT_Humidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_HUMIDITY_VAR_NUM, - F("relativeHumidity"), F("percent"), + "relativeHumidity", "percent", DHT_HUMIDITY_RESOLUTION, - F("DHTHumidity"), UUID, customVarCode) + "DHTHumidity", UUID, customVarCode) {} }; @@ -106,9 +106,9 @@ class AOSongDHT_Temp : public Variable AOSongDHT_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", DHT_TEMP_RESOLUTION, - F("DHTTemp"), UUID, customVarCode) + "DHTTemp", UUID, customVarCode) {} }; @@ -120,9 +120,9 @@ class AOSongDHT_HI : public Variable AOSongDHT_HI(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DHT_HI_VAR_NUM, - F("heatIndex"), F("degreeCelsius"), + "heatIndex", "degreeCelsius", DHT_HI_RESOLUTION, - F("DHTHI"), UUID, customVarCode) + "DHTHI", UUID, customVarCode) {} }; diff --git a/src/ApogeeSQ212.cpp b/src/ApogeeSQ212.cpp index c950a2ba6..37d95d296 100644 --- a/src/ApogeeSQ212.cpp +++ b/src/ApogeeSQ212.cpp @@ -36,7 +36,7 @@ // The constructor - need the power pin and the data pin ApogeeSQ212::ApogeeSQ212(int8_t powerPin, int8_t dataPin, uint8_t i2cAddress, uint8_t measurementsToAverage) - : Sensor(F("ApogeeSQ212"), SQ212_NUM_VARIABLES, + : Sensor("ApogeeSQ212", SQ212_NUM_VARIABLES, SQ212_WARM_UP_TIME_MS, SQ212_STABILIZATION_TIME_MS, SQ212_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage) { diff --git a/src/ApogeeSQ212.h b/src/ApogeeSQ212.h index 548115418..85dd28b48 100644 --- a/src/ApogeeSQ212.h +++ b/src/ApogeeSQ212.h @@ -76,9 +76,9 @@ class ApogeeSQ212_PAR : public Variable ApogeeSQ212_PAR(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, SQ212_PAR_VAR_NUM, - F("radiationIncomingPAR"), F("microeinsteinPerSquareMeterPerSecond"), + "radiationIncomingPAR", "microeinsteinPerSquareMeterPerSecond", SQ212_PAR_RESOLUTION, - F("photosyntheticallyActiveRadiation"), UUID, customVarCode) + "photosyntheticallyActiveRadiation", UUID, customVarCode) {} }; diff --git a/src/BoschBME280.cpp b/src/BoschBME280.cpp index d0eab7812..54d9d4b20 100644 --- a/src/BoschBME280.cpp +++ b/src/BoschBME280.cpp @@ -33,7 +33,7 @@ // The constructor - because this is I2C, only need the power pin BoschBME280::BoschBME280(int8_t powerPin, uint8_t i2cAddressHex, uint8_t measurementsToAverage) - : Sensor(F("BoschBME280"), BME280_NUM_VARIABLES, + : Sensor("BoschBME280", BME280_NUM_VARIABLES, BME280_WARM_UP_TIME_MS, BME280_STABILIZATION_TIME_MS, BME280_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) { diff --git a/src/BoschBME280.h b/src/BoschBME280.h index dfab7ff71..196ddffd6 100644 --- a/src/BoschBME280.h +++ b/src/BoschBME280.h @@ -86,9 +86,9 @@ class BoschBME280_Temp : public Variable BoschBME280_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", BME280_TEMP_RESOLUTION, - F("BoschBME280Temp"), UUID, customVarCode) + "BoschBME280Temp", UUID, customVarCode) {} }; @@ -100,9 +100,9 @@ class BoschBME280_Humidity : public Variable BoschBME280_Humidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_HUMIDITY_VAR_NUM, - F("relativeHumidity"), F("percent"), + "relativeHumidity", "percent", BME280_HUMIDITY_RESOLUTION, - F("BoschBME280Humidity"), UUID, customVarCode) + "BoschBME280Humidity", UUID, customVarCode) {} }; @@ -114,9 +114,9 @@ class BoschBME280_Pressure : public Variable BoschBME280_Pressure(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_PRESSURE_VAR_NUM, - F("barometricPressure"), F("pascal"), + "barometricPressure", "pascal", BME280_PRESSURE_RESOLUTION, - F("BoschBME280Pressure"), UUID, customVarCode) + "BoschBME280Pressure", UUID, customVarCode) {} }; @@ -128,9 +128,9 @@ class BoschBME280_Altitude : public Variable BoschBME280_Altitude(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BME280_ALTITUDE_VAR_NUM, - F("heightAboveSeaFloor"), F("meter"), + "heightAboveSeaFloor", "meter", BME280_ALTITUDE_RESOLUTION, - F("BoschBME280Altitude"), UUID, customVarCode) + "BoschBME280Altitude", UUID, customVarCode) {} }; diff --git a/src/CampbellOBS3.cpp b/src/CampbellOBS3.cpp index b05bbbd9e..18f3cba52 100644 --- a/src/CampbellOBS3.cpp +++ b/src/CampbellOBS3.cpp @@ -34,7 +34,7 @@ CampbellOBS3::CampbellOBS3(int8_t powerPin, int8_t dataPin, float x2_coeff_A, float x1_coeff_B, float x0_coeff_C, uint8_t i2cAddress, uint8_t measurementsToAverage) - : Sensor(F("CampbellOBS3"), OBS3_NUM_VARIABLES, + : Sensor("CampbellOBS3", OBS3_NUM_VARIABLES, OBS3_WARM_UP_TIME_MS, OBS3_STABILIZATION_TIME_MS, OBS3_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage) { diff --git a/src/CampbellOBS3.h b/src/CampbellOBS3.h index 41b576958..61fc4c868 100644 --- a/src/CampbellOBS3.h +++ b/src/CampbellOBS3.h @@ -76,9 +76,9 @@ class CampbellOBS3_Turbidity : public Variable CampbellOBS3_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, OBS3_TURB_VAR_NUM, - F("turbidity"), F("nephelometricTurbidityUnit"), + "turbidity", "nephelometricTurbidityUnit", OBS3_RESOLUTION, - F("Turbidity"), UUID, customVarCode) + "turbidity", UUID, customVarCode) {} }; diff --git a/src/Decagon5TM.h b/src/Decagon5TM.h index dfcbd1d5e..8af5e4261 100644 --- a/src/Decagon5TM.h +++ b/src/Decagon5TM.h @@ -53,17 +53,17 @@ class Decagon5TM : public SDI12Sensors // Constructors with overloads Decagon5TM(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("Decagon5TM"), TM_NUM_VARIABLES, + "Decagon5TM", TM_NUM_VARIABLES, TM_WARM_UP_TIME_MS, TM_STABILIZATION_TIME_MS, TM_MEASUREMENT_TIME_MS) {} Decagon5TM(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("Decagon5TM"), TM_NUM_VARIABLES, + "Decagon5TM", TM_NUM_VARIABLES, TM_WARM_UP_TIME_MS, TM_STABILIZATION_TIME_MS, TM_MEASUREMENT_TIME_MS) {} Decagon5TM(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("Decagon5TM"), TM_NUM_VARIABLES, + "Decagon5TM", TM_NUM_VARIABLES, TM_WARM_UP_TIME_MS, TM_STABILIZATION_TIME_MS, TM_MEASUREMENT_TIME_MS) {} @@ -77,9 +77,9 @@ class Decagon5TM_Ea : public Variable public: Decagon5TM_Ea(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_EA_VAR_NUM, - F("permittivity"), F("faradPerMeter"), + "permittivity", "faradPerMeter", TM_EA_RESOLUTION, - F("SoilEa"), UUID, customVarCode) + "SoilEa", UUID, customVarCode) {} }; @@ -90,9 +90,9 @@ class Decagon5TM_Temp : public Variable public: Decagon5TM_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", TM_TEMP_RESOLUTION, - F("SoilTemp"), UUID, customVarCode) + "SoilTemp", UUID, customVarCode) {} }; @@ -103,9 +103,9 @@ class Decagon5TM_VWC : public Variable public: Decagon5TM_VWC(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, TM_VWC_VAR_NUM, - F("volumetricWaterContent"), F("percent"), + "volumetricWaterContent", "percent", TM_VWC_RESOLUTION, - F("SoilVWC"), UUID, customVarCode) + "SoilVWC", UUID, customVarCode) {} }; diff --git a/src/DecagonCTD.h b/src/DecagonCTD.h index 7de3dbe31..951bb15b5 100644 --- a/src/DecagonCTD.h +++ b/src/DecagonCTD.h @@ -58,17 +58,17 @@ class DecagonCTD : public SDI12Sensors // Constructors with overloads DecagonCTD(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonCTD"), CTD_NUM_VARIABLES, + "DecagonCTD", CTD_NUM_VARIABLES, CTD_WARM_UP_TIME_MS, CTD_STABILIZATION_TIME_MS, CTD_MEASUREMENT_TIME_MS) {} DecagonCTD(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonCTD"), CTD_NUM_VARIABLES, + "DecagonCTD", CTD_NUM_VARIABLES, CTD_WARM_UP_TIME_MS, CTD_STABILIZATION_TIME_MS, CTD_MEASUREMENT_TIME_MS) {} DecagonCTD(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonCTD"), CTD_NUM_VARIABLES, + "DecagonCTD", CTD_NUM_VARIABLES, CTD_WARM_UP_TIME_MS, CTD_STABILIZATION_TIME_MS, CTD_MEASUREMENT_TIME_MS) {} }; @@ -80,9 +80,9 @@ class DecagonCTD_Cond : public Variable public: DecagonCTD_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_COND_VAR_NUM, - F("specificConductance"), F("microsiemenPerCentimeter"), + "specificConductance", "microsiemenPerCentimeter", CTD_COND_RESOLUTION, - F("CTDcond"), UUID, customVarCode) + "CTDcond", UUID, customVarCode) {} }; @@ -93,9 +93,9 @@ class DecagonCTD_Temp : public Variable public: DecagonCTD_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", CTD_TEMP_RESOLUTION, - F("CTDtemp"), UUID, customVarCode) + "CTDtemp", UUID, customVarCode) {} }; @@ -106,9 +106,9 @@ class DecagonCTD_Depth : public Variable public: DecagonCTD_Depth(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, CTD_DEPTH_VAR_NUM, - F("waterDepth"), F("millimeter"), + "waterDepth", "millimeter", CTD_DEPTH_RESOLUTION, - F("CTDdepth"), UUID, customVarCode) + "CTDdepth", UUID, customVarCode) {} }; diff --git a/src/DecagonES2.h b/src/DecagonES2.h index d83097eaa..8134a3e5d 100644 --- a/src/DecagonES2.h +++ b/src/DecagonES2.h @@ -49,17 +49,17 @@ class DecagonES2 : public SDI12Sensors // Constructors with overloads DecagonES2(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonES2"), ES2_NUM_VARIABLES, + "DecagonES2", ES2_NUM_VARIABLES, ES2_WARM_UP_TIME_MS, ES2_STABILIZATION_TIME_MS, ES2_MEASUREMENT_TIME_MS) {} DecagonES2(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonES2"), ES2_NUM_VARIABLES, + "DecagonES2", ES2_NUM_VARIABLES, ES2_WARM_UP_TIME_MS, ES2_STABILIZATION_TIME_MS, ES2_MEASUREMENT_TIME_MS) {} DecagonES2(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("DecagonES2"), ES2_NUM_VARIABLES, + "DecagonES2", ES2_NUM_VARIABLES, ES2_WARM_UP_TIME_MS, ES2_STABILIZATION_TIME_MS, ES2_MEASUREMENT_TIME_MS) {} }; @@ -71,9 +71,9 @@ class DecagonES2_Cond : public Variable public: DecagonES2_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, ES2_COND_VAR_NUM, - F("specificConductance"), F("microsiemenPerCentimeter"), + "specificConductance", "microsiemenPerCentimeter", ES2_COND_RESOLUTION, - F("ES2Cond"), UUID, customVarCode) + "ES2Cond", UUID, customVarCode) {} }; @@ -83,9 +83,9 @@ class DecagonES2_Temp : public Variable public: DecagonES2_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, ES2_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", ES2_TEMP_RESOLUTION, - F("ES2temp"), UUID, customVarCode) + "ES2temp", UUID, customVarCode) {} }; diff --git a/src/ExternalVoltage.cpp b/src/ExternalVoltage.cpp index c7f34d29e..c33a52cd6 100644 --- a/src/ExternalVoltage.cpp +++ b/src/ExternalVoltage.cpp @@ -40,7 +40,7 @@ // The constructor - need the power pin the data pin, and gain if non standard ExternalVoltage::ExternalVoltage(int8_t powerPin, int8_t dataPin, float gain, uint8_t i2cAddress, uint8_t measurementsToAverage) - : Sensor(F("ExternalVoltage"), EXT_VOLT_NUM_VARIABLES, + : Sensor("ExternalVoltage", EXT_VOLT_NUM_VARIABLES, EXT_VOLT_WARM_UP_TIME_MS, EXT_VOLT_STABILIZATION_TIME_MS, EXT_VOLT_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage) { diff --git a/src/ExternalVoltage.h b/src/ExternalVoltage.h index 8a0cfba05..a3353d935 100644 --- a/src/ExternalVoltage.h +++ b/src/ExternalVoltage.h @@ -28,7 +28,7 @@ * http://wiki.seeedstudio.com/Grove-Voltage_Divider * * Technical specifications for the TI ADS1115 can be found at: - * http://www.ti.com/product/ADS1115 + * http://www.ti.com/product/ADS1115 * * Response time: < 1ms * Resample time: max of ADC (860/sec) @@ -83,9 +83,9 @@ class ExternalVoltage_Volt : public Variable ExternalVoltage_Volt(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, EXT_VOLT_VAR_NUM, - F("voltage"), F("volt"), + "voltage", "volt", EXT_VOLT_RESOLUTION, - F("extVoltage"), UUID, customVarCode) + "extVoltage", UUID, customVarCode) {} }; diff --git a/src/FreescaleMPL115A2.cpp b/src/FreescaleMPL115A2.cpp index bb8897825..b5a6ded6f 100644 --- a/src/FreescaleMPL115A2.cpp +++ b/src/FreescaleMPL115A2.cpp @@ -27,7 +27,7 @@ // The constructor - because this is I2C, only need the power pin // This sensor has a set I2C address of 0x60. MPL115A2::MPL115A2(int8_t powerPin, uint8_t measurementsToAverage) - : Sensor(F("MPL115A2"), MPL115A2_NUM_VARIABLES, + : Sensor("MPL115A2", MPL115A2_NUM_VARIABLES, MPL115A2_WARM_UP_TIME_MS, MPL115A2_STABILIZATION_TIME_MS, MPL115A2_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) {} diff --git a/src/FreescaleMPL115A2.h b/src/FreescaleMPL115A2.h index 408ff1de1..3a3a6ad95 100644 --- a/src/FreescaleMPL115A2.h +++ b/src/FreescaleMPL115A2.h @@ -69,9 +69,9 @@ class MPL115A2_Temp : public Variable MPL115A2_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MPL115A2_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", MPL115A2_TEMP_RESOLUTION, - F("MPL115A2_Temp"), UUID, customVarCode) + "MPL115A2_Temp", UUID, customVarCode) {} }; @@ -83,9 +83,9 @@ class MPL115A2_Pressure : public Variable MPL115A2_Pressure(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MPL115A2_PRESSURE_VAR_NUM, - F("atmosphericPressure"), F("kPa"), + "atmosphericPressure", "kilopascal", MPL115A2_PRESSURE_RESOLUTION, - F("MPL115A2_Pressure"), UUID, customVarCode) + "MPL115A2_Pressure", UUID, customVarCode) {} }; diff --git a/src/KellerAcculevel.h b/src/KellerAcculevel.h index ff971154d..4d3e16c5c 100644 --- a/src/KellerAcculevel.h +++ b/src/KellerAcculevel.h @@ -39,13 +39,13 @@ class KellerAcculevel : public KellerParent KellerAcculevel(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : KellerParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Acculevel, F("KellerAcculevel"), KELLER_NUM_VARIABLES, + Acculevel, "KellerAcculevel", KELLER_NUM_VARIABLES, KellerAcculevel_WARM_UP_TIME_MS, KellerAcculevel_STABILIZATION_TIME_MS, KellerAcculevel_MEASUREMENT_TIME_MS) {} KellerAcculevel(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : KellerParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Acculevel, F("KellerAcculevel"), KELLER_NUM_VARIABLES, + Acculevel, "KellerAcculevel", KELLER_NUM_VARIABLES, KellerAcculevel_WARM_UP_TIME_MS, KellerAcculevel_STABILIZATION_TIME_MS, KellerAcculevel_MEASUREMENT_TIME_MS) {} }; @@ -57,9 +57,9 @@ class KellerAcculevel_Pressure : public Variable public: KellerAcculevel_Pressure(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_PRESSURE_VAR_NUM, - F("pressureGauge"), F("millibar"), + "pressureGauge", "millibar", KellerAcculevel_PRESSURE_RESOLUTION, - F("kellerPress"), UUID, customVarCode) + "kellerPress", UUID, customVarCode) {} }; @@ -70,9 +70,9 @@ class KellerAcculevel_Temp : public Variable public: KellerAcculevel_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", KellerAcculevel_TEMP_RESOLUTION, - F("kellerTemp"), UUID, customVarCode) + "kellerTemp", UUID, customVarCode) {} }; @@ -82,9 +82,9 @@ class KellerAcculevel_Height : public Variable public: KellerAcculevel_Height(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, KELLER_HEIGHT_VAR_NUM, - F("gaugeHeight"), F("meter"), + "gaugeHeight", "meter", KellerAcculevel_HEIGHT_RESOLUTION, - F("kellerHeight"), UUID, customVarCode) + "kellerHeight", UUID, customVarCode) {} }; diff --git a/src/KellerParent.cpp b/src/KellerParent.cpp index 80a244af1..e09907204 100644 --- a/src/KellerParent.cpp +++ b/src/KellerParent.cpp @@ -20,7 +20,7 @@ // The constructor - need the sensor type, modbus address, power pin, stream for data, and number of readings to average KellerParent::KellerParent(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin, uint8_t measurementsToAverage, - kellerModel model, String sensName, int numVariables, + kellerModel model, const char *sensName, int numVariables, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensName, numVariables, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, @@ -33,7 +33,7 @@ KellerParent::KellerParent(byte modbusAddress, Stream* stream, } KellerParent::KellerParent(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin, uint8_t measurementsToAverage, - kellerModel model, String sensName, int numVariables, + kellerModel model, const char *sensName, int numVariables, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensName, numVariables, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, diff --git a/src/KellerParent.h b/src/KellerParent.h index 2a1c572cb..aa69ef975 100644 --- a/src/KellerParent.h +++ b/src/KellerParent.h @@ -38,11 +38,11 @@ class KellerParent : public Sensor public: KellerParent(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1, - kellerModel model = OTHER, String sensName = "Keller-Sensor", int numVariables = 3, + kellerModel model = OTHER, const char *sensName = "Keller-Sensor", int numVariables = 3, uint32_t warmUpTime_ms = 500, uint32_t stabilizationTime_ms = 5000, uint32_t measurementTime_ms = 1500); KellerParent(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1, - kellerModel model = OTHER, String sensName = "Keller-Sensor", int numVariables = 3, + kellerModel model = OTHER, const char *sensName = "Keller-Sensor", int numVariables = 3, uint32_t warmUpTime_ms = 500, uint32_t stabilizationTime_ms = 5000, uint32_t measurementTime_ms = 1500); String getSensorLocation(void) override; diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 0601042be..239528e5b 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -705,7 +705,7 @@ class Modem_SignalPercent : public Variable public: Modem_SignalPercent(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PERCENT_SIGNAL_VAR_NUM, - F("signalPercent"), F("percent"), + F("signalPercent"), "percent", PERCENT_SIGNAL_RESOLUTION, F("signalPercent"), UUID, customVarCode) {} diff --git a/src/MaxBotixSonar.cpp b/src/MaxBotixSonar.cpp index 1d2f50f51..6f344b495 100644 --- a/src/MaxBotixSonar.cpp +++ b/src/MaxBotixSonar.cpp @@ -15,7 +15,7 @@ MaxBotixSonar::MaxBotixSonar(Stream* stream, int8_t powerPin, int8_t triggerPin, uint8_t measurementsToAverage) - : Sensor(F("MaxBotixMaxSonar"), HRXL_NUM_VARIABLES, + : Sensor("MaxBotixMaxSonar", HRXL_NUM_VARIABLES, HRXL_WARM_UP_TIME_MS, HRXL_STABILIZATION_TIME_MS, HRXL_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) { @@ -23,7 +23,7 @@ MaxBotixSonar::MaxBotixSonar(Stream* stream, int8_t powerPin, int8_t triggerPin, _stream = stream; } MaxBotixSonar::MaxBotixSonar(Stream& stream, int8_t powerPin, int8_t triggerPin, uint8_t measurementsToAverage) - : Sensor(F("MaxBotixMaxSonar"), HRXL_NUM_VARIABLES, + : Sensor("MaxBotixMaxSonar", HRXL_NUM_VARIABLES, HRXL_WARM_UP_TIME_MS, HRXL_STABILIZATION_TIME_MS, HRXL_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) { diff --git a/src/MaxBotixSonar.h b/src/MaxBotixSonar.h index 985dce623..4e6e19b19 100644 --- a/src/MaxBotixSonar.h +++ b/src/MaxBotixSonar.h @@ -58,9 +58,9 @@ class MaxBotixSonar_Range : public Variable MaxBotixSonar_Range(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, HRXL_VAR_NUM, - F("distance"), F("millimeter"), + "distance", "millimeter", HRXL_RESOLUTION, - F("SonarRange"), UUID, customVarCode) + "SonarRange", UUID, customVarCode) {} }; diff --git a/src/MaximDS18.cpp b/src/MaximDS18.cpp index 409c6ce2e..dd47834db 100644 --- a/src/MaximDS18.cpp +++ b/src/MaximDS18.cpp @@ -22,7 +22,7 @@ // The constructor - if the hex address is known - also need the power pin and the data pin MaximDS18::MaximDS18(DeviceAddress OneWireAddress, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage) - : Sensor(F("MaximDS18"), DS18_NUM_VARIABLES, + : Sensor("MaximDS18", DS18_NUM_VARIABLES, DS18_WARM_UP_TIME_MS, DS18_STABILIZATION_TIME_MS, DS18_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage), oneWire(dataPin), tempSensors(&oneWire) @@ -34,7 +34,7 @@ MaximDS18::MaximDS18(DeviceAddress OneWireAddress, int8_t powerPin, int8_t dataP // The constructor - if the hex address is NOT known - only need the power pin and the data pin // Can only use this if there is only a single sensor on the pin MaximDS18::MaximDS18(int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage) - : Sensor(F("MaximDS18"), DS18_NUM_VARIABLES, + : Sensor("MaximDS18", DS18_NUM_VARIABLES, DS18_WARM_UP_TIME_MS, DS18_STABILIZATION_TIME_MS, DS18_MEASUREMENT_TIME_MS, powerPin, dataPin, measurementsToAverage), oneWire(dataPin), tempSensors(&oneWire) diff --git a/src/MaximDS18.h b/src/MaximDS18.h index 0e1a65ce3..d6ec01629 100644 --- a/src/MaximDS18.h +++ b/src/MaximDS18.h @@ -74,9 +74,9 @@ class MaximDS18_Temp : public Variable MaximDS18_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DS18_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", DS18_TEMP_RESOLUTION, - F("DS18Temp"), UUID, customVarCode) + "DS18Temp", UUID, customVarCode) {} }; diff --git a/src/MaximDS3231.h b/src/MaximDS3231.h index fc275d9c2..87551fbfd 100644 --- a/src/MaximDS3231.h +++ b/src/MaximDS3231.h @@ -44,7 +44,7 @@ class MaximDS3231 : public Sensor public: // Only input is the number of readings to average MaximDS3231(uint8_t measurementsToAverage = 1) - : Sensor(F("MaximDS3231"), DS3231_NUM_VARIABLES, + : Sensor("MaximDS3231", DS3231_NUM_VARIABLES, DS3231_WARM_UP_TIME_MS, DS3231_STABILIZATION_TIME_MS, DS3231_MEASUREMENT_TIME_MS, -1, -1, measurementsToAverage) {} @@ -69,9 +69,9 @@ class MaximDS3231_Temp : public Variable MaximDS3231_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DS3231_TEMP_VAR_NUM, - F("temperatureRTC"), F("degreeCelsius"), + "temperatureDatalogger", "degreeCelsius", DS3231_TEMP_RESOLUTION, - F("BoardTemp"), UUID, customVarCode) + "BoardTemp", UUID, customVarCode) {} }; diff --git a/src/MeaSpecMS5803.cpp b/src/MeaSpecMS5803.cpp index af17f46cf..451ce69e1 100644 --- a/src/MeaSpecMS5803.cpp +++ b/src/MeaSpecMS5803.cpp @@ -39,7 +39,7 @@ // The constructor - because this is I2C, only need the power pin MeaSpecMS5803::MeaSpecMS5803(int8_t powerPin, uint8_t i2cAddressHex, int maxPressure, uint8_t measurementsToAverage) - : Sensor(F("MeaSpecMS5803"), MS5803_NUM_VARIABLES, + : Sensor("MeaSpecMS5803", MS5803_NUM_VARIABLES, MS5803_WARM_UP_TIME_MS, MS5803_STABILIZATION_TIME_MS, MS5803_MEASUREMENT_TIME_MS, powerPin, -1, measurementsToAverage) { diff --git a/src/MeaSpecMS5803.h b/src/MeaSpecMS5803.h index e3556cdf8..9c096611d 100644 --- a/src/MeaSpecMS5803.h +++ b/src/MeaSpecMS5803.h @@ -91,9 +91,9 @@ class MeaSpecMS5803_Temp : public Variable MeaSpecMS5803_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MS5803_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", MS5803_TEMP_RESOLUTION, - F("MeaSpecMS5803Temp"), UUID, customVarCode) + "MeaSpecMS5803Temp", UUID, customVarCode) {} }; @@ -105,9 +105,9 @@ class MeaSpecMS5803_Pressure : public Variable MeaSpecMS5803_Pressure(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, MS5803_PRESSURE_VAR_NUM, - F("barometricPressure"), F("Millibar"), + "barometricPressure", "millibar", MS5803_PRESSURE_RESOLUTION, - F("MeaSpecMS5803Pressure"), UUID, customVarCode) + "MeaSpecMS5803Pressure", UUID, customVarCode) {} }; diff --git a/src/ProcessorStats.cpp b/src/ProcessorStats.cpp index abc9fdf76..8c62150e9 100644 --- a/src/ProcessorStats.cpp +++ b/src/ProcessorStats.cpp @@ -97,7 +97,7 @@ // Need to know the Mayfly version because the battery resistor depends on it ProcessorStats::ProcessorStats(const char *version) - : Sensor(F(BOARD), PROCESSOR_NUM_VARIABLES, + : Sensor(BOARD, PROCESSOR_NUM_VARIABLES, PROCESSOR_WARM_UP_TIME_MS, PROCESSOR_STABILIZATION_TIME_MS, PROCESSOR_MEASUREMENT_TIME_MS, -1, -1, 1) { diff --git a/src/ProcessorStats.h b/src/ProcessorStats.h index 6a02516f2..15e70dd12 100644 --- a/src/ProcessorStats.h +++ b/src/ProcessorStats.h @@ -63,9 +63,9 @@ class ProcessorStats_Batt : public Variable ProcessorStats_Batt(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PROCESSOR_BATTERY_VAR_NUM, - F("batteryVoltage"), F("Volt"), + "batteryVoltage", "volt", PROCESSOR_BATTERY_RESOLUTION, - F("Battery"), UUID, customVarCode) + "Battery", UUID, customVarCode) {} }; @@ -77,9 +77,9 @@ class ProcessorStats_FreeRam : public Variable ProcessorStats_FreeRam(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PROCESSOR_RAM_VAR_NUM, - F("Free SRAM"), F("Bit"), + "Free SRAM", "Bit", PROCESSOR_RAM_RESOLUTION, - F("FreeRam"), UUID, customVarCode) + "FreeRam", UUID, customVarCode) {} }; diff --git a/src/RainCounterI2C.cpp b/src/RainCounterI2C.cpp index 1b8ee30e9..ca2b06f53 100644 --- a/src/RainCounterI2C.cpp +++ b/src/RainCounterI2C.cpp @@ -22,7 +22,7 @@ // The constructor - because this is I2C, only need the power pin and rain per event if a non-standard value is used RainCounterI2C::RainCounterI2C(uint8_t i2cAddressHex, float rainPerTip) - : Sensor(F("RainCounterI2C"), BUCKET_NUM_VARIABLES, + : Sensor("RainCounterI2C", BUCKET_NUM_VARIABLES, BUCKET_WARM_UP_TIME_MS, BUCKET_STABILIZATION_TIME_MS, BUCKET_MEASUREMENT_TIME_MS, -1, -1, 1) { diff --git a/src/RainCounterI2C.h b/src/RainCounterI2C.h index f9ab0bad5..438602a21 100644 --- a/src/RainCounterI2C.h +++ b/src/RainCounterI2C.h @@ -66,9 +66,9 @@ class RainCounterI2C_Tips : public Variable RainCounterI2C_Tips(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BUCKET_TIPS_VAR_NUM, - F("precipitation"), F("event"), + "precipitation", "event", BUCKET_TIPS_RESOLUTION, - F("RainCounterI2CTips"), UUID, customVarCode) + "RainCounterI2CTips", UUID, customVarCode) {} }; @@ -79,9 +79,9 @@ class RainCounterI2C_Depth : public Variable RainCounterI2C_Depth(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, BUCKET_RAIN_VAR_NUM, - F("precipitation"), F("millimeter"), + "precipitation", "millimeter", BUCKET_RAIN_RESOLUTION, - F("RainCounterI2CVol"), UUID, customVarCode) + "RainCounterI2CVol", UUID, customVarCode) {} }; diff --git a/src/SDI12Sensors.cpp b/src/SDI12Sensors.cpp index 6278204a3..1819bff66 100644 --- a/src/SDI12Sensors.cpp +++ b/src/SDI12Sensors.cpp @@ -16,7 +16,7 @@ // The constructor - need the number of measurements the sensor will return, SDI-12 address, the power pin, and the data pin SDI12Sensors::SDI12Sensors(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage, - String sensorName, uint8_t numReturnedVars, + const char *sensorName, uint8_t numReturnedVars, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensorName, numReturnedVars, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, @@ -26,7 +26,7 @@ SDI12Sensors::SDI12Sensors(char SDI12address, int8_t powerPin, int8_t dataPin, u _SDI12address = SDI12address; } SDI12Sensors::SDI12Sensors(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage, - String sensorName, uint8_t numReturnedVars, + const char *sensorName, uint8_t numReturnedVars, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensorName, numReturnedVars, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, @@ -36,7 +36,7 @@ SDI12Sensors::SDI12Sensors(char *SDI12address, int8_t powerPin, int8_t dataPin, _SDI12address = *SDI12address; } SDI12Sensors::SDI12Sensors(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage, - String sensorName, uint8_t numReturnedVars, + const char *sensorName, uint8_t numReturnedVars, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensorName, numReturnedVars, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, diff --git a/src/SDI12Sensors.h b/src/SDI12Sensors.h index 7334fdbae..37e7fb5f1 100644 --- a/src/SDI12Sensors.h +++ b/src/SDI12Sensors.h @@ -33,13 +33,13 @@ class SDI12Sensors : public Sensor public: SDI12Sensors(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1, - String sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, + const char *sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, uint32_t warmUpTime_ms = 0, uint32_t stabilizationTime_ms = 0, uint32_t measurementTime_ms = 0); SDI12Sensors(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1, - String sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, + const char *sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, uint32_t warmUpTime_ms = 0, uint32_t stabilizationTime_ms = 0, uint32_t measurementTime_ms = 0); SDI12Sensors(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1, - String sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, + const char *sensorName = "SDI12-Sensor", uint8_t numReturnedVars = 1, uint32_t warmUpTime_ms = 0, uint32_t stabilizationTime_ms = 0, uint32_t measurementTime_ms = 0); String getSensorVendor(void); diff --git a/src/SensorBase.cpp b/src/SensorBase.cpp index a8c0d655c..cddbca16b 100644 --- a/src/SensorBase.cpp +++ b/src/SensorBase.cpp @@ -15,7 +15,7 @@ // ============================================================================ // The constructor -Sensor::Sensor(String sensorName, uint8_t numReturnedVars, +Sensor::Sensor(const char *sensorName, uint8_t numReturnedVars, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage) { diff --git a/src/SensorBase.h b/src/SensorBase.h index f17225f97..56d676318 100644 --- a/src/SensorBase.h +++ b/src/SensorBase.h @@ -27,7 +27,7 @@ class Sensor { public: - Sensor(String sensorName = "Unknown", uint8_t numReturnedVars = 1, + Sensor(const char *sensorName = "Unknown", uint8_t numReturnedVars = 1, uint32_t warmUpTime_ms = 0, uint32_t stabilizationTime_ms = 0, uint32_t measurementTime_ms = 0, int8_t powerPin = -1, int8_t dataPin = -1, uint8_t measurementsToAverage = 1); @@ -143,7 +143,7 @@ class Sensor int8_t _dataPin; // SIGNED int, to allow negative numbers for unused pins int8_t _powerPin; // SIGNED int, to allow negative numbers for unused pins - String _sensorName; + const char *_sensorName; uint8_t _numReturnedVars; uint8_t _measurementsToAverage; uint8_t numberGoodMeasurementsMade[MAX_NUMBER_VARS]; diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index 637d32845..d67229fc8 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -17,9 +17,9 @@ // The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable::Variable(Sensor *parentSense, int varNum, - String varName, String varUnit, + const char *varName, const char *varUnit, unsigned int decimalResolution, - String defaultVarCode, + const char *defaultVarCode, const char *UUID, const char *customVarCode) { isCalculated = false; @@ -42,7 +42,7 @@ Variable::Variable(Sensor *parentSense, int varNum, // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable::Variable(float (*calcFxn)(), - String& varName, String& varUnit, + const char *varName, const char *varUnit, unsigned int decimalResolution, const char *UUID, const char *customVarCode) { @@ -123,7 +123,7 @@ String Variable::getVarUnit(void){return _varUnit;} // This returns a customized code for the variable, if one is given, and a default if not String Variable::getVarCode(void) { - if (_customCode != "") return _customCode; + if (strcmp(_customCode,"") != 0) return _customCode; else return _defaultVarCode; } diff --git a/src/VariableBase.h b/src/VariableBase.h index a568e0b6b..fc3c871d6 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -25,16 +25,16 @@ class Variable // The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable(Sensor *parentSense, int varNum, - String varName = VAR_BASE_UNKNOWN, String varUnit = VAR_BASE_UNKNOWN, + const char *varName = VAR_BASE_UNKNOWN, const char *varUnit = VAR_BASE_UNKNOWN, unsigned int decimalResolution = 0, - String defaultVarCode = VAR_BASE_UNKNOWN, + const char *defaultVarCode = VAR_BASE_UNKNOWN, const char *UUID = "", const char *customVarCode = ""); // The constructor for a measured variable - that is, one whose value is // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable(float (*calcFxn)(), - String& varName, String& varUnit, + const char *varName, const char *varUnit, unsigned int decimalResolution, const char *UUID, const char *customVarCode); @@ -79,10 +79,10 @@ class Variable private: float (*_calcFxn)(void); uint8_t _varNum; - String _varName; - String _varUnit; + const char *_varName; + const char *_varUnit; unsigned int _decimalResolution; - String _defaultVarCode; + const char *_defaultVarCode; const char *_customCode; const char *_UUID; }; diff --git a/src/YosemitechParent.cpp b/src/YosemitechParent.cpp index 8120a3f8f..43848ca0f 100644 --- a/src/YosemitechParent.cpp +++ b/src/YosemitechParent.cpp @@ -18,7 +18,7 @@ // The constructor - need the sensor type, modbus address, power pin, stream for data, and number of readings to average YosemitechParent::YosemitechParent(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin, uint8_t measurementsToAverage, - yosemitechModel model, String sensName, int numVariables, + yosemitechModel model, const char *sensName, int numVariables, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensName, numVariables, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, @@ -31,7 +31,7 @@ YosemitechParent::YosemitechParent(byte modbusAddress, Stream* stream, } YosemitechParent::YosemitechParent(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin, uint8_t measurementsToAverage, - yosemitechModel model, String sensName, int numVariables, + yosemitechModel model, const char *sensName, int numVariables, uint32_t warmUpTime_ms, uint32_t stabilizationTime_ms, uint32_t measurementTime_ms) : Sensor(sensName, numVariables, warmUpTime_ms, stabilizationTime_ms, measurementTime_ms, diff --git a/src/YosemitechParent.h b/src/YosemitechParent.h index 036d8f809..b176aa0f5 100644 --- a/src/YosemitechParent.h +++ b/src/YosemitechParent.h @@ -31,11 +31,11 @@ class YosemitechParent : public Sensor public: YosemitechParent(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1, - yosemitechModel model = UNKNOWN, String sensName = "Yosemitech-Sensor", int numVariables = 2, + yosemitechModel model = UNKNOWN, const char *sensName = "Yosemitech-Sensor", int numVariables = 2, uint32_t warmUpTime_ms = 1500, uint32_t stabilizationTime_ms = 20000, uint32_t measurementTime_ms = 2000); YosemitechParent(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1, - yosemitechModel model = UNKNOWN, String sensName = "Yosemitech-Sensor", int numVariables = 2, + yosemitechModel model = UNKNOWN, const char *sensName = "Yosemitech-Sensor", int numVariables = 2, uint32_t warmUpTime_ms = 1500, uint32_t stabilizationTime_ms = 20000, uint32_t measurementTime_ms = 2000); String getSensorLocation(void) override; diff --git a/src/YosemitechY4000.h b/src/YosemitechY4000.h index d84720b21..b3d31a2ea 100644 --- a/src/YosemitechY4000.h +++ b/src/YosemitechY4000.h @@ -106,13 +106,13 @@ class YosemitechY4000 : public YosemitechParent YosemitechY4000(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y4000, F("YosemitechY4000"), Y4000_NUM_VARIABLES, + Y4000, "YosemitechY4000", Y4000_NUM_VARIABLES, Y4000_WARM_UP_TIME_MS, Y4000_STABILIZATION_TIME_MS, Y4000_MEASUREMENT_TIME_MS) {} YosemitechY4000(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y4000, F("YosemitechY4000"), Y4000_NUM_VARIABLES, + Y4000, "YosemitechY4000", Y4000_NUM_VARIABLES, Y4000_WARM_UP_TIME_MS, Y4000_STABILIZATION_TIME_MS, Y4000_MEASUREMENT_TIME_MS) {} }; @@ -125,9 +125,9 @@ class YosemitechY4000_DOmgL : public Variable YosemitechY4000_DOmgL(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_DOMGL_VAR_NUM, - F("oxygenDissolved"), F("milligramPerLiter"), + "oxygenDissolved", "milligramPerLiter", Y4000_DOMGL_RESOLUTION, - F("Y4000DOmgL"), UUID, customVarCode) + "Y4000DOmgL", UUID, customVarCode) {} }; @@ -137,9 +137,9 @@ class YosemitechY4000_Turbidity : public Variable public: YosemitechY4000_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_TURB_VAR_NUM, - F("turbidity"), F("nephelometricTurbidityUnit"), + "turbidity", "nephelometricTurbidityUnit", Y4000_TURB_RESOLUTION, - F("Y4000Turbidity"), UUID, customVarCode) + "Y4000Turbidity", UUID, customVarCode) {} }; @@ -149,9 +149,9 @@ class YosemitechY4000_Cond : public Variable public: YosemitechY4000_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_COND_VAR_NUM, - F("specificConductance"), F("microsiemenPerCentimeter"), + "specificConductance", "microsiemenPerCentimeter", Y4000_COND_RESOLUTION, - F("Y4000Cond"), UUID, customVarCode) + "Y4000Cond", UUID, customVarCode) {} }; @@ -162,9 +162,9 @@ class YosemitechY4000_pH : public Variable YosemitechY4000_pH(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_PH_VAR_NUM, - F("pH"), F("pH"), + "pH", "pH", Y4000_PH_RESOLUTION, - F("Y4000pH"), UUID, customVarCode) + "Y4000pH", UUID, customVarCode) {} }; @@ -175,9 +175,9 @@ class YosemitechY4000_Temp : public Variable YosemitechY4000_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y4000_TEMP_RESOLUTION, - F("Y4000temp"), UUID, customVarCode) + "Y4000temp", UUID, customVarCode) {} }; @@ -188,9 +188,9 @@ class YosemitechY4000_ORP : public Variable YosemitechY4000_ORP(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_ORP_VAR_NUM, - F("ORP"), F("millivolt"), + "ORP", "millivolt", Y4000_ORP_RESOLUTION, - F("Y4000Potential"), UUID, customVarCode) + "Y4000Potential", UUID, customVarCode) {} }; @@ -201,9 +201,9 @@ class YosemitechY4000_Chlorophyll : public Variable YosemitechY4000_Chlorophyll(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_CHLORO_VAR_NUM, - F("chlorophyllFluorescence"), F("microgramPerLiter"), + "chlorophyllFluorescence", "microgramPerLiter", Y4000_CHLORO_RESOLUTION, - F("Y4000Chloro"), UUID, customVarCode) + "Y4000Chloro", UUID, customVarCode) {} }; @@ -214,9 +214,9 @@ class YosemitechY4000_BGA : public Variable YosemitechY4000_BGA(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y4000_BGA_VAR_NUM, - F("blueGreenAlgaeCyanobacteriaPhycocyanin"), F("microgramPerLiter"), + "blueGreenAlgaeCyanobacteriaPhycocyanin", "microgramPerLiter", Y4000_BGA_RESOLUTION, - F("Y4000BGA"), UUID, customVarCode) + "Y4000BGA", UUID, customVarCode) {} }; diff --git a/src/YosemitechY504.h b/src/YosemitechY504.h index 63585be79..ca293b40d 100644 --- a/src/YosemitechY504.h +++ b/src/YosemitechY504.h @@ -55,13 +55,13 @@ class YosemitechY504 : public YosemitechParent YosemitechY504(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y504, F("YosemitechY504"), Y504_NUM_VARIABLES, + Y504, "YosemitechY504", Y504_NUM_VARIABLES, Y504_WARM_UP_TIME_MS, Y504_STABILIZATION_TIME_MS, Y504_MEASUREMENT_TIME_MS) {} YosemitechY504(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y504, F("YosemitechY504"), Y504_NUM_VARIABLES, + Y504, "YosemitechY504", Y504_NUM_VARIABLES, Y504_WARM_UP_TIME_MS, Y504_STABILIZATION_TIME_MS, Y504_MEASUREMENT_TIME_MS) {} }; @@ -74,9 +74,9 @@ class YosemitechY504_DOpct : public Variable YosemitechY504_DOpct(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_DOPCT_VAR_NUM, - F("oxygenDissolvedPercentOfSaturation"), F("percent"), + "oxygenDissolvedPercentOfSaturation", "percent", Y504_DOPCT_RESOLUTION, - F("Y504DOpct"), UUID, customVarCode) + "Y504DOpct", UUID, customVarCode) {} }; @@ -88,9 +88,9 @@ class YosemitechY504_Temp : public Variable YosemitechY504_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y504_TEMP_RESOLUTION, - F("Y504temp"), UUID, customVarCode) + "Y504temp", UUID, customVarCode) {} }; @@ -102,9 +102,9 @@ class YosemitechY504_DOmgL : public Variable YosemitechY504_DOmgL(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y504_DOMGL_VAR_NUM, - F("oxygenDissolved"), F("milligramPerLiter"), + "oxygenDissolved", "milligramPerLiter", Y504_DOMGL_RESOLUTION, - F("Y504DOmgL"), UUID, customVarCode) + "Y504DOmgL", UUID, customVarCode) {} }; diff --git a/src/YosemitechY510.h b/src/YosemitechY510.h index 708c24d60..ac1845baa 100644 --- a/src/YosemitechY510.h +++ b/src/YosemitechY510.h @@ -52,13 +52,13 @@ class YosemitechY510 : public YosemitechParent YosemitechY510(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y510, F("YosemitechY510"), Y510_NUM_VARIABLES, + Y510, "YosemitechY510", Y510_NUM_VARIABLES, Y510_WARM_UP_TIME_MS, Y510_STABILIZATION_TIME_MS, Y510_MEASUREMENT_TIME_MS) {} YosemitechY510(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y510, F("YosemitechY510"), Y510_NUM_VARIABLES, + Y510, "YosemitechY510", Y510_NUM_VARIABLES, Y510_WARM_UP_TIME_MS, Y510_STABILIZATION_TIME_MS, Y510_MEASUREMENT_TIME_MS) {} }; @@ -70,9 +70,9 @@ class YosemitechY510_Turbidity : public Variable public: YosemitechY510_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y510_TURB_VAR_NUM, - F("turbidity"), F("nephelometricTurbidityUnit"), + "turbidity", "nephelometricTurbidityUnit", Y510_TURB_RESOLUTION, - F("Y510Turbidity"), UUID, customVarCode) + "Y510Turbidity", UUID, customVarCode) {} }; @@ -83,9 +83,9 @@ class YosemitechY510_Temp : public Variable public: YosemitechY510_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y510_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y510_TEMP_RESOLUTION, - F("Y510temp"), UUID, customVarCode) + "Y510temp", UUID, customVarCode) {} }; diff --git a/src/YosemitechY511.h b/src/YosemitechY511.h index 0c82e8fe5..afa5f9bbf 100644 --- a/src/YosemitechY511.h +++ b/src/YosemitechY511.h @@ -52,13 +52,13 @@ class YosemitechY511 : public YosemitechParent YosemitechY511(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y511, F("YosemitechY511"), Y511_NUM_VARIABLES, + Y511, "YosemitechY511", Y511_NUM_VARIABLES, Y511_WARM_UP_TIME_MS, Y511_STABILIZATION_TIME_MS, Y511_MEASUREMENT_TIME_MS) {} YosemitechY511(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream,powerPin, enablePin, measurementsToAverage, - Y511, F("YosemitechY511"), Y511_NUM_VARIABLES, + Y511, "YosemitechY511", Y511_NUM_VARIABLES, Y511_WARM_UP_TIME_MS, Y511_STABILIZATION_TIME_MS, Y511_MEASUREMENT_TIME_MS) {} }; @@ -70,9 +70,9 @@ class YosemitechY511_Turbidity : public Variable public: YosemitechY511_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y511_TURB_VAR_NUM, - F("turbidity"), F("nephelometricTurbidityUnit"), + "turbidity", "nephelometricTurbidityUnit", Y511_TURB_RESOLUTION, - F("Y511Turbidity"), UUID, customVarCode) + "Y511Turbidity", UUID, customVarCode) {} }; @@ -83,9 +83,9 @@ class YosemitechY511_Temp : public Variable public: YosemitechY511_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y511_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y511_TEMP_RESOLUTION, - F("Y511temp"), UUID, customVarCode) + "Y511temp", UUID, customVarCode) {} }; diff --git a/src/YosemitechY514.h b/src/YosemitechY514.h index 5682fd369..94020ea1e 100644 --- a/src/YosemitechY514.h +++ b/src/YosemitechY514.h @@ -53,13 +53,13 @@ class YosemitechY514 : public YosemitechParent YosemitechY514(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y514, F("YosemitechY514"), Y514_NUM_VARIABLES, + Y514, "YosemitechY514", Y514_NUM_VARIABLES, Y514_WARM_UP_TIME_MS, Y514_STABILIZATION_TIME_MS, Y514_MEASUREMENT_TIME_MS) {} YosemitechY514(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y514, ("YosemitechY514"), Y514_NUM_VARIABLES, + Y514, "YosemitechY514", Y514_NUM_VARIABLES, Y514_WARM_UP_TIME_MS, Y514_STABILIZATION_TIME_MS, Y514_MEASUREMENT_TIME_MS) {} }; @@ -72,9 +72,9 @@ class YosemitechY514_Chlorophyll : public Variable YosemitechY514_Chlorophyll(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y514_CHLORO_VAR_NUM, - F("chlorophyllFluorescence"), F("microgramPerLiter"), + "chlorophyllFluorescence", "microgramPerLiter", Y514_CHLORO_RESOLUTION, - F("Y514Chloro"), UUID, customVarCode) + "Y514Chloro", UUID, customVarCode) {} }; @@ -86,9 +86,9 @@ class YosemitechY514_Temp : public Variable YosemitechY514_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y514_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y514_TEMP_RESOLUTION, - F("Y514temp"), UUID, customVarCode) + "Y514temp", UUID, customVarCode) {} }; #endif diff --git a/src/YosemitechY520.h b/src/YosemitechY520.h index c3e7ca18a..f1d89e8c9 100644 --- a/src/YosemitechY520.h +++ b/src/YosemitechY520.h @@ -53,13 +53,13 @@ class YosemitechY520 : public YosemitechParent YosemitechY520(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y520, F("YosemitechY520"), Y520_NUM_VARIABLES, + Y520, "YosemitechY520", Y520_NUM_VARIABLES, Y520_WARM_UP_TIME_MS, Y520_STABILIZATION_TIME_MS, Y520_MEASUREMENT_TIME_MS) {} YosemitechY520(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y520, F("YosemitechY520"), Y520_NUM_VARIABLES, + Y520, "YosemitechY520", Y520_NUM_VARIABLES, Y520_WARM_UP_TIME_MS, Y520_STABILIZATION_TIME_MS, Y520_MEASUREMENT_TIME_MS) {} }; @@ -71,9 +71,9 @@ class YosemitechY520_Cond : public Variable public: YosemitechY520_Cond(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y520_COND_VAR_NUM, - F("specificConductance"), F("microsiemenPerCentimeter"), + "specificConductance", "microsiemenPerCentimeter", Y520_COND_RESOLUTION, - F("Y520Cond"), UUID, customVarCode) + "Y520Cond", UUID, customVarCode) {} }; @@ -84,9 +84,9 @@ class YosemitechY520_Temp : public Variable public: YosemitechY520_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y520_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y520_TEMP_RESOLUTION, - F("Y520temp"), UUID, customVarCode) + "Y520temp", UUID, customVarCode) {} }; diff --git a/src/YosemitechY532.h b/src/YosemitechY532.h index c1305da3c..7675eb0aa 100644 --- a/src/YosemitechY532.h +++ b/src/YosemitechY532.h @@ -56,13 +56,13 @@ class YosemitechY532 : public YosemitechParent YosemitechY532(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y532, F("YosemitechY532"), Y532_NUM_VARIABLES, + Y532, "YosemitechY532", Y532_NUM_VARIABLES, Y532_WARM_UP_TIME_MS, Y532_STABILIZATION_TIME_MS, Y532_MEASUREMENT_TIME_MS) {} YosemitechY532(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y532, F("YosemitechY532"), Y532_NUM_VARIABLES, + Y532, "YosemitechY532", Y532_NUM_VARIABLES, Y532_WARM_UP_TIME_MS, Y532_STABILIZATION_TIME_MS, Y532_MEASUREMENT_TIME_MS) {} }; @@ -75,9 +75,9 @@ class YosemitechY532_pH : public Variable YosemitechY532_pH(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_PH_VAR_NUM, - F("pH"), F("pH"), + "pH", "pH", Y532_PH_RESOLUTION, - F("Y532pH"), UUID, customVarCode) + "Y532pH", UUID, customVarCode) {} }; @@ -89,9 +89,9 @@ class YosemitechY532_Temp : public Variable YosemitechY532_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y532_TEMP_RESOLUTION, - F("Y532temp"), UUID, customVarCode) + "Y532temp", UUID, customVarCode) {} }; @@ -103,9 +103,9 @@ class YosemitechY532_Voltage : public Variable YosemitechY532_Voltage(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y532_VOLT_VAR_NUM, - F("voltage"), F("millivolt"), + "voltage", "millivolt", Y532_VOLT_RESOLUTION, - F("Y532Potential"), UUID, customVarCode) + "Y532Potential", UUID, customVarCode) {} }; diff --git a/src/YosemitechY533.h b/src/YosemitechY533.h index a38cff30f..8e49e72dd 100644 --- a/src/YosemitechY533.h +++ b/src/YosemitechY533.h @@ -61,13 +61,13 @@ class YosemitechY533 : public YosemitechParent YosemitechY533(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y533, F("YosemitechY533"), Y533_NUM_VARIABLES, + Y533, "YosemitechY533", Y533_NUM_VARIABLES, Y533_WARM_UP_TIME_MS, Y533_STABILIZATION_TIME_MS, Y533_MEASUREMENT_TIME_MS) {} YosemitechY533(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y533, F("YosemitechY533"), Y533_NUM_VARIABLES, + Y533, "YosemitechY533", Y533_NUM_VARIABLES, Y533_WARM_UP_TIME_MS, Y533_STABILIZATION_TIME_MS, Y533_MEASUREMENT_TIME_MS) {} }; @@ -80,9 +80,9 @@ class YosemitechY533_pH : public Variable YosemitechY533_pH(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_PH_VAR_NUM, - F("pH"), F("pH"), + "pH", "pH", Y533_PH_RESOLUTION, - F("Y533pH"), UUID, customVarCode) + "Y533pH", UUID, customVarCode) {} }; @@ -94,9 +94,9 @@ class YosemitechY533_Temp : public Variable YosemitechY533_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y533_TEMP_RESOLUTION, - F("Y533temp"), UUID, customVarCode) + "Y533temp", UUID, customVarCode) {} }; @@ -108,9 +108,9 @@ class YosemitechY533_Voltage : public Variable YosemitechY533_Voltage(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y533_VOLT_VAR_NUM, - F("voltage"), F("millivolt"), + "voltage", "millivolt", Y533_VOLT_RESOLUTION, - F("Y533Potential"), UUID, customVarCode) + "Y533Potential", UUID, customVarCode) {} }; diff --git a/src/YosemitechY550.h b/src/YosemitechY550.h index 496282409..9b246789f 100644 --- a/src/YosemitechY550.h +++ b/src/YosemitechY550.h @@ -59,13 +59,13 @@ class YosemitechY550 : public YosemitechParent YosemitechY550(byte modbusAddress, Stream* stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream, powerPin, enablePin, measurementsToAverage, - Y550, F("YosemitechY550"), Y550_NUM_VARIABLES, + Y550, "YosemitechY550", Y550_NUM_VARIABLES, Y550_WARM_UP_TIME_MS, Y550_STABILIZATION_TIME_MS, Y550_MEASUREMENT_TIME_MS) {} YosemitechY550(byte modbusAddress, Stream& stream, int8_t powerPin, int8_t enablePin = -1, uint8_t measurementsToAverage = 1) : YosemitechParent(modbusAddress, stream,powerPin, enablePin, measurementsToAverage, - Y550, F("YosemitechY550"), Y550_NUM_VARIABLES, + Y550, "YosemitechY550", Y550_NUM_VARIABLES, Y550_WARM_UP_TIME_MS, Y550_STABILIZATION_TIME_MS, Y550_MEASUREMENT_TIME_MS) {} }; @@ -77,9 +77,9 @@ class YosemitechY550_COD : public Variable public: YosemitechY550_COD(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_COD_VAR_NUM, - F("COD"), F("milligramPerLiter"), + "COD", "milligramPerLiter", Y550_COD_RESOLUTION, - F("Y550COD"), UUID, customVarCode) + "Y550COD", UUID, customVarCode) {} }; @@ -90,9 +90,9 @@ class YosemitechY550_Temp : public Variable public: YosemitechY550_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", Y550_TEMP_RESOLUTION, - F("Y550temp"), UUID, customVarCode) + "Y550temp", UUID, customVarCode) {} }; @@ -103,9 +103,9 @@ class YosemitechY550_Turbidity : public Variable public: YosemitechY550_Turbidity(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, Y550_TURB_VAR_NUM, - F("turbidity"), F("nephelometricTurbidityUnit"), + "turbidity", "nephelometricTurbidityUnit", Y550_TURB_RESOLUTION, - F("Y550Turbidity"), UUID, customVarCode) + "Y550Turbidity", UUID, customVarCode) {} }; diff --git a/src/ZebraTechDOpto.h b/src/ZebraTechDOpto.h index 22020d48a..88c525812 100644 --- a/src/ZebraTechDOpto.h +++ b/src/ZebraTechDOpto.h @@ -60,17 +60,17 @@ class ZebraTechDOpto : public SDI12Sensors // Constructors with overloads ZebraTechDOpto(char SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("ZebraTech D-Opto"), DOPTO_NUM_VARIABLES, + "ZebraTech D-Opto", DOPTO_NUM_VARIABLES, DOPTO_WARM_UP_TIME_MS, DOPTO_STABILIZATION_TIME_MS, DOPTO_MEASUREMENT_TIME_MS) {} ZebraTechDOpto(char *SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("ZebraTech D-Opto"), DOPTO_NUM_VARIABLES, + "ZebraTech D-Opto", DOPTO_NUM_VARIABLES, DOPTO_WARM_UP_TIME_MS, DOPTO_STABILIZATION_TIME_MS, DOPTO_MEASUREMENT_TIME_MS) {} ZebraTechDOpto(int SDI12address, int8_t powerPin, int8_t dataPin, uint8_t measurementsToAverage = 1) : SDI12Sensors(SDI12address, powerPin, dataPin, measurementsToAverage, - F("ZebraTech D-Opto"), DOPTO_NUM_VARIABLES, + "ZebraTech D-Opto", DOPTO_NUM_VARIABLES, DOPTO_WARM_UP_TIME_MS, DOPTO_STABILIZATION_TIME_MS, DOPTO_MEASUREMENT_TIME_MS) {} @@ -84,9 +84,9 @@ class ZebraTechDOpto_Temp : public Variable ZebraTechDOpto_Temp(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_TEMP_VAR_NUM, - F("temperature"), F("degreeCelsius"), + "temperature", "degreeCelsius", DOPTO_TEMP_RESOLUTION, - F("DOtempC"), UUID, customVarCode) + "DOtempC", UUID, customVarCode) {} }; @@ -98,9 +98,9 @@ class ZebraTechDOpto_DOpct : public Variable ZebraTechDOpto_DOpct(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_DOPCT_VAR_NUM, - F("oxygenDissolvedPercentOfSaturation"), F("percent"), + "oxygenDissolvedPercentOfSaturation", "percent", DOPTO_DOPCT_RESOLUTION, - F("DOpercent"), UUID, customVarCode) + "DOpercent", UUID, customVarCode) {} }; @@ -112,9 +112,9 @@ class ZebraTechDOpto_DOmgL : public Variable ZebraTechDOpto_DOmgL(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, DOPTO_DOMGL_VAR_NUM, - F("oxygenDissolved"), F("milligramPerLiter"), + "oxygenDissolved", "milligramPerLiter", DOPTO_DOMGL_RESOLUTION, - F("DOppm"), UUID, customVarCode) + "DOppm", UUID, customVarCode) {} }; From de55912908dee42aeb882df6695ac49baa17f25f Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 16:18:18 -0400 Subject: [PATCH 46/54] Tweek examples --- examples/baro_rho_correction/baro_rho_correction.ino | 12 ++++++------ src/LoggerBase.cpp | 2 +- src/LoggerBase.h | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index 8ac9f4c51..f7e2fe33c 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -194,8 +194,8 @@ float calculateWaterPressure(void) return waterPressure; } // Properties of the calculated water pressure variable -String waterPresureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ -String waterPresureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ +const char *waterPresureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ +const char *waterPresureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ int waterPresureVarResolution = 3; const char *waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; const char *waterPresureVarCode = "CorrectedPressure"; @@ -216,8 +216,8 @@ float calculateWaterDepthRaw(void) return waterDepth; } // Properties of the calculated water depth variable -String waterDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ -String waterDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ +const char *waterDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ +const char *waterDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ int waterDepthVarResolution = 3; const char *waterDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; const char *waterDepthVarCode = "CalcDepth"; @@ -252,8 +252,8 @@ float calculateWaterDepthTempCorrected(void) return rhoDepth; } // Properties of the calculated temperature corrected water depth variable -String rhoDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ -String rhoDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ +const char *rhoDepthVarName = "waterDepth"; // This must be a value from http://vocabulary.odm2.org/variablename/ +const char *rhoDepthVarUnit = "millimeter"; // This must be a value from http://vocabulary.odm2.org/units/ int rhoDepthVarResolution = 3; const char *rhoDepthUUID = "12345678-abcd-1234-efgh-1234567890ab"; const char *rhoDepthVarCode = "DensityDepth"; diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 880e2be75..d8dece832 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -495,7 +495,7 @@ void Logger::setFileName(String& fileName) _autoFileName = false; } // Same as above, with a character array (overload function) -void Logger::setFileName(char *fileName) +void Logger::setFileName(const char *fileName) { String StrName = String(fileName); setFileName(StrName); diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 538cc4918..15de33cc2 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -125,7 +125,7 @@ class Logger // Public functions for logging data to an SD card // ===================================================================== // // This sets a file name, if you want to decide on it in advance - void setFileName(char *fileName); + void setFileName(const char *fileName); // Same as above, with a string (overload function) void setFileName(String& fileName); From 8723b1a0a8d0599ba9618403f3366b099a31145e Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Thu, 31 May 2018 16:19:47 -0400 Subject: [PATCH 47/54] Missed loggermodem --- src/LoggerModem.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 239528e5b..318c06e06 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -136,7 +136,7 @@ class loggerModem : public Sensor public: // Constructors loggerModem() - : Sensor(F(MODEM_NAME), MODEM_NUM_VARIABLES, MODEM_WARM_UP_TIME_MS, 0, 0, -1, -1, 1) + : Sensor(MODEM_NAME, MODEM_NUM_VARIABLES, MODEM_WARM_UP_TIME_MS, 0, 0, -1, -1, 1) {_lastNISTrequest = 0;} String getSensorLocation(void) override { return F("modemSerial"); } @@ -692,9 +692,9 @@ class Modem_RSSI : public Variable public: Modem_RSSI(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, RSSI_VAR_NUM, - F("RSSI"), F("decibelMiliWatt"), + "RSSI", "decibelMiliWatt", RSSI_RESOLUTION, - F("RSSI"), UUID, customVarCode) + "RSSI", UUID, customVarCode) {} }; @@ -705,9 +705,9 @@ class Modem_SignalPercent : public Variable public: Modem_SignalPercent(Sensor *parentSense, const char *UUID = "", const char *customVarCode = "") : Variable(parentSense, PERCENT_SIGNAL_VAR_NUM, - F("signalPercent"), "percent", + "signalPercent", "percent", PERCENT_SIGNAL_RESOLUTION, - F("signalPercent"), UUID, customVarCode) + "signalPercent", UUID, customVarCode) {} }; From 5859ef384c5486049f213ec827a3e5cbbaace901 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Fri, 1 Jun 2018 10:20:26 -0400 Subject: [PATCH 48/54] Moved unknown into class to fix multiple declarations --- src/VariableBase.cpp | 2 ++ src/VariableBase.h | 3 +-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/VariableBase.cpp b/src/VariableBase.cpp index d67229fc8..7633361cf 100644 --- a/src/VariableBase.cpp +++ b/src/VariableBase.cpp @@ -14,6 +14,8 @@ // The class and functions for interfacing with a specific variable. // ============================================================================ +const char* Variable::VAR_BASE_UNKNOWN = "Unknown"; + // The constructor for a measured variable - that is, one whose values are // updated by a sensor. Variable::Variable(Sensor *parentSense, int varNum, diff --git a/src/VariableBase.h b/src/VariableBase.h index fc3c871d6..e0152c45f 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -15,8 +15,6 @@ // #define DEBUGGING_SERIAL_OUTPUT Serial #include "ModSensorDebugger.h" -const char* VAR_BASE_UNKNOWN = "Unknown"; - class Sensor; // Forward declaration class Variable @@ -85,6 +83,7 @@ class Variable const char *_defaultVarCode; const char *_customCode; const char *_UUID; + static const char* VAR_BASE_UNKNOWN; }; #endif From af1424812a4f0002b4070e753f30abc383bfb933 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Fri, 1 Jun 2018 10:51:54 -0400 Subject: [PATCH 49/54] Mostly updates to documentation --- .travis.yml | 3 +-- README.md | 12 +++++++----- src/LoggerBase.cpp | 2 +- src/LoggerBase.h | 20 ++++++++++++-------- src/SensorBase.h | 11 +++++++---- 5 files changed, 28 insertions(+), 20 deletions(-) diff --git a/.travis.yml b/.travis.yml index a12b30f7e..6e4b77f9c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,7 +31,6 @@ install: - git rm library.json - pip install -U platformio - pio upgrade - - pio update - pio lib -g install 2079 # DS3231 - pio lib -g install 311 # EnableInterrupt - pio lib -g install 322 # SdFat @@ -53,6 +52,6 @@ install: - pio lib -g install https://github.com/PaulStoffregen/AltSoftSerial.git # #73, but need the git until Paul S. has a new release - pio lib -g install https://github.com/EnviroDIY/SoftwaterSerial_ExternalInts.git # - pio lib -g install https://github.com/todbot/SoftI2CMaster.git - - pio lib -g update + - pio update script: make travis-build diff --git a/README.md b/README.md index a33c2401f..40837c156 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,9 @@ To use a sensor and variable in your sketch, you must separately include xxx.h f Each sensor is implemented as a subclass of the "Sensor" class contained in "SensorBase.h". Each variable is separately implemented as a subclass of the "Variable" class contained in "VariableBase.h". The variables are tied to the sensor using an "[Observer](https://en.wikipedia.org/wiki/Observer_pattern)" software pattern. -The "VariableArray" class contained in "VariableArray.h" defines the logic for iterating through many variable objects. The various "Logger" classes are all sub-classes of variable arrays and add functionality for sleeping the processor, writing to an SD card, and communicating with the internet. +The "VariableArray" class contained in "VariableArray.h" defines the logic for iterating through many variable objects. The VariableArray class takes advantage of various time stamps within the Sensor class to optimize the timing of communcations with many sensors. + +The "Logger" class defines functions for sleeping the processor and writing to an SD card. The logger subclasses add functionality for communicating with the internet and sending data to particular data receivers. @@ -99,12 +101,12 @@ This library is designed for wireless, solar-powered environmental data logging In order to support multiple functions and sensors, there are quite a lot of sub-libraries that this library is dependent on. _Even if you do not use the modules, you must have all of the dependencies installed for the library itself to properly compile._ Please check the [library.json](https://github.com/EnviroDIY/ModularSensors/blob/master/library.json) file for more details on the versions required of each library. If you are using [PlatformIO](https://platformio.org), you can list "EnviroDIY_ModularSensors" in the ```lib_deps``` section of your platformio.ini file and all of these libraries will be installed automatically. If using the "standard" Arduino IDE, you must install each of these libraries individually, or in a bundle from the [EnviroDIY Libraries](https://github.com/EnviroDIY/Libraries) meta-repository. - [EnableInterrupt](https://github.com/GreyGnome/EnableInterrupt) - Administrates and handles pin change interrupts, allowing the logger to sleep and save battery. This also controls the interrupts for the versions of SoftwareSerial and SDI-12 linked below that have been stripped of interrupt control. Because we use this library, _you must always add the line ```#include ``` to the top of your sketch._ -- AVR sleep library - This is for low power sleeping for AVR processors. (This library is built in to the Arduino IDE.) +- AVR sleep library - This is for low power sleeping for AVR processors. (This library is built in to the Arduino and PlatformIO IDEs.) - [EnviroDIY DS-3231](https://github.com/EnviroDIY/Sodaq_DS3231) - For real time clock control - [RTCZero library](https://github.com/arduino-libraries/RTCZero) - This real time clock control and low power sleeping on SAMD processors. (This library may be built in to the Arduino IDE.) NOTE: If using an AVR board, you must explicitly _ignore_ this library when compiling with PlatformIO or you will have compiler errors. - [SdFat library](https://github.com/greiman/SdFat) - This enables communication with the SD card. - [EnviroDIY version of the TinyGSM library](https://github.com/EnviroDIY/TinyGSM) - This provides internet (TCP/IP) connectivity. -- [Adafruit ADS1X15 library](https://github.com/soligen2010/Adafruit_ADS1X15/) - For high-resolution analog to digital conversion. Note that this is soligen2010's fork of the original Adafruit library; it corrects many problems in the Adafruit library such as a bug which gives the same output on all four inputs regardless of their values. Do NOT use the original Adafruit version! +- [Adafruit ADS1X15 library](https://github.com/soligen2010/Adafruit_ADS1X15/) - For high-resolution analog to digital conversion. Note that this is soligen2010's fork of the original Adafruit library; it corrects many problems in the Adafruit library such as a bug which gives the same output on all four inputs regardless of their values. Do _NOT_ use the original Adafruit version! - [EnviroDIY Arduino SDI-12 library](https://github.com/EnviroDIY/Arduino-SDI-12/tree/ExtInts) - For control of SDI-12 based sensors. This modified version is needed so there are no pin change interrupt conflicts with the SoftwareSerial library or the software pin change interrupt library used to wake the processor. - [SensorModbusMaster](https://github.com/EnviroDIY/SensorModbusMaster) - for easy communication with Modbus devices. - [OneWire](https://github.com/PaulStoffregen/OneWire) - This enables communication with Maxim/Dallas OneWire devices. @@ -125,7 +127,7 @@ Generally useful functions: - **Constructor** - Each sensor has a unique constructor, the exact format of which is dependent on the individual sensor. - **getSensorName()** - This gets the name of the sensor and returns it as a string. - **getSensorLocation()** - This returns the Arduino pin sending and receiving data or other sensor installation information as a string. This is the location where the sensor is connected to the data logger, NOT the position of the sensor in the environment. Generally this value is set in the constructor for the sensor. -- **setNumberMeasurementsToAverage(int nReadings)** - Sets the number of readings for the sensor to take. This value can also be set by the constructor. +- **setNumberMeasurementsToAverage(int nReadings)** - Sets the number of readings for the sensor to take. This value can also be set by the constructor. NOTE: This will beome the number of readings actually taken by a sensor prior to data averaging. Any "bad" (-9999) values returned by the sensor will not be included in the final averaging. This the actual number of "good" values that are averaged may be less than what is set by setNumberMeasurementsToAverage or in the sensor constructor. - **getNumberMeasurementsToAverage()** - Returns an unsigned 8-bit integer with the number of readings the sensor will be taking before averaging and giving a final result. - **getStatus()** - This returns the 8-bit code for the current status of the sensor: - Bit 0 - 0=Not powered, 1=Powered @@ -162,7 +164,7 @@ These functions are also available for each sensor, but should be used with caut ### Functions for Each Variable - **Constructor** - There are two forms of the constructor, one for measured variables (ie, ones whose values come directly from a senor) and another for calculated variables (ie, ones whose values are calculated from other vales). - - For _measured_ variables, the base variable constructor should not be used, but instead the constructor for the specific type of variable tied to a sensor should be used. (That is, use the constructor for the MaxBotixSonar_Range variable sub-object, not the raw variable constructor.) The sensor-measured variable constructors require a pointer to its parent sensor as the first argument of the constructor. There are also two optional string entries, for a universally unique identifier (UUID or GUID) and a custom variable code. _The UUID must always be listed first!_ In cases where you would like a custom variable code, but do not have a UUID, you **must** enter '""' as your UUID. + - For _measured_ variables, the base variable constructor should not be used, but instead the constructor for the specific type of variable tied to a sensor should be used. (That is, use the constructor for the MaxBotixSonar_Range variable sub-object, not the raw variable constructor.) Each sensor-measured variable constructor requires a pointer to its parent sensor as the first argument of the constructor. There are also two optional string entries, for a universally unique identifier (UUID or GUID) and a custom variable code. _The UUID must always be listed first!_ In cases where you would like a custom variable code, but do not have a UUID, you **must** enter '""' as your UUID. - For _calculated_ variables, you use the base variable object constructor. The constructor requires a function which returns a float as its first argument, followed by Strings from the variable's name and unit. Both of these strings should be values from the [ODM2 controlled vocabularies](http://vocabulary.odm2.org/). Next an integer variable resolution is required. Then two Strings for the variable UUID and variable code. _All arguments are required in the calculated variable constructor!_ - **getVarName()** - This returns the variable's name, using http://vocabulary.odm2.org/variablename/, as a String. - **getVarUnit()** - This returns the variable's unit, using http://vocabulary.odm2.org/units/, as a String. diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index d8dece832..09c5a0872 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -676,7 +676,7 @@ void Logger::setFileTimestamp(File fileToStamp, uint8_t stampFlag) // Private helper function - This opens or creates a file, converting a string // file name to a character file name -bool Logger::openFile(String filename, bool createFile, bool writeDefaultHeader) +bool Logger::openFile(String& filename, bool createFile, bool writeDefaultHeader) { // Initialise the SD card // skip everything else if there's no SD card, otherwise it might hang diff --git a/src/LoggerBase.h b/src/LoggerBase.h index 15de33cc2..7075694b9 100644 --- a/src/LoggerBase.h +++ b/src/LoggerBase.h @@ -29,9 +29,11 @@ // Bring in the library to commuinicate with an external high-precision real time clock // This also implements a needed date/time class #include -#define EPOCH_TIME_OFF 946684800 // This is 2000-jan-01 00:00:00 in epoch time -// Need this b/c the date/time class in Sodaq_DS3231 treats a 32-bit long timestamp -// as time from 2000-jan-01 00:00:00 instead of the standard epoch of 1970-jan-01 00:00:00 +#define EPOCH_TIME_OFF 946684800 +// This is 2000-jan-01 00:00:00 in "epoch" time +// Need this b/c the date/time class in Sodaq_DS3231 treats a 32-bit long +// timestamp as time from 2000-jan-01 00:00:00 instead of the standard (unix) +// epoch beginning 1970-jan-01 00:00:00. #include // To communicate with the SD card @@ -198,8 +200,8 @@ class Logger static uint32_t markedEpochTime; // These are flag fariables noting the current state (logging/testing) - // NOTE: if the logger isn't currently logging or testing or in the middle of set-up, - // it's probably sleeping + // NOTE: if the logger isn't currently logging or testing or in the middle + // of set-up, it's probably sleeping // Setting these as volatile because the flags can be changed in ISR's static volatile bool isLoggingNow; static volatile bool isTestingNow; @@ -238,18 +240,20 @@ class Logger int8_t _buttonPin; // This checks if the SD card is available and ready + // We run this check before every communication with the SD card to prevent + // hanging. bool initializeSDCard(void); // This generates a file name from the logger id and the current date - // NOTE: This cannot be called until the set-up after the RTC is started + // NOTE: This cannot be called until *after* the RTC is started void generateAutoFileName(void); // This sets a timestamp on a file void setFileTimestamp(File fileToStamp, uint8_t stampFlag); // This opens or creates a file, converting a string file name to a - // characterd file name - bool openFile(String filename, bool createFile, bool writeDefaultHeader); + // character file name + bool openFile(String& filename, bool createFile, bool writeDefaultHeader); }; #endif diff --git a/src/SensorBase.h b/src/SensorBase.h index 56d676318..585cbf94a 100644 --- a/src/SensorBase.h +++ b/src/SensorBase.h @@ -61,9 +61,9 @@ class Sensor virtual bool setup(void); // This updates the sensor's values - // This includes clears the values array, starts and averages as many - // measurement readings as requested, and then notifies the registerd - // variables of the new resutls. + // This clears the values array, starts and averages as many measurement + // readings as requested, and then notifies the registered variables + // of the new results. All possible waits are included in this function! virtual bool update(void); // This turns on the sensor power, if applicable @@ -76,6 +76,7 @@ class Sensor // This wakes the sensor up, if necessary - that is, does whatever it takes to // get a sensor in the proper state to begin a measurement after the power is on. // This *may* require a waitForWarmUp() before wake commands can be sent. + // The wait is NOT included in this function! // This also sets the _millisSensorActivated timestamp. // By default, verifies the power is on and returns true virtual bool wake(void); @@ -88,6 +89,7 @@ class Sensor // This also sets the _millisMeasurementRequested timestamp. // This *may* require a waitForWarmUp() before measurement commands can be sent. // This *may* also require a waitForStability() before returned measurements will be any good. + // The waits are NOT included in this function! virtual bool startSingleMeasurement(void); // This next function must be implemented for ever sensor!! @@ -95,13 +97,14 @@ class Sensor // This also un-sets the _millisMeasurementRequested timestamp. // This *may* also require a waitForStability() before returned measurements will be any good. // This will often require a waitForMeasurementCompletion() to ensure a measurement is done. + // The waits are NOT included in this function! virtual bool addSingleMeasurementResult(void) = 0; // This is the array of result values for each sensor float sensorValues[MAX_NUMBER_VARS]; // Clears the values array void clearValues(); - // This verifies that a measurement is OK before adding it to the array + // This verifies that a measurement is OK (ie, not -9999) before adding it to the array void verifyAndAddMeasurementResult(int resultNumber, float resultValue); void verifyAndAddMeasurementResult(int resultNumber, int resultValue); void averageMeasurements(void); From d5b5efc1082e5f7dcfe67d6671e2e6884598f825 Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Mon, 4 Jun 2018 15:11:31 -0400 Subject: [PATCH 50/54] Slimmed modem on/off methods --- README.md | 2 +- src/LoggerModem.h | 11 +- src/ModemOnOff.cpp | 260 +++++++++++++++++++++++++-------------------- src/ModemOnOff.h | 30 ++---- 4 files changed, 158 insertions(+), 145 deletions(-) diff --git a/README.md b/README.md index 40837c156..c47809ab6 100644 --- a/README.md +++ b/README.md @@ -389,7 +389,7 @@ Before creating a loggerModem instance, _you must define your modem at top of yo - ```#define TINY_GSM_MODEM_SIM800``` - for a SIMCom SIM800 or variant thereof (including current [Sodaq GPRSBees](https://shop.sodaq.com/en/gprsbee.html)) - ```#define TINY_GSM_MODEM_SIM808``` - for a SIMCom SIM808 (essentially a SIMCom SIM800 with GPS support) - ```#define TINY_GSM_MODEM_SIM868``` - for a SIMCom SIM868 (another SIM800 variant with GPS support) -- ```#define TINY_GSM_MODEM_UBLOX``` - for most u-blox cellular modems ((LEON-G100, LISA-U2xx, SARA-G3xx, SARA-U2xx, TOBY-L2xx, LARA-R2xx, MPCI-L2xx, or a Digi 3G XBee running in bypass mode) +- ```#define TINY_GSM_MODEM_UBLOX``` - for most u-blox cellular modems (LEON-G100, LISA-U2xx, SARA-G3xx, SARA-U2xx, TOBY-L2xx, LARA-R2xx, MPCI-L2xx, or a Digi 3G XBee running in bypass mode) - ```#define TINY_GSM_MODEM_M95``` - for an Quectel M95 - ```#define TINY_GSM_MODEM_BG96``` - for an Quectel BG96 - ```#define TINY_GSM_MODEM_A6``` - for an AI-Thinker A6 diff --git a/src/LoggerModem.h b/src/LoggerModem.h index 318c06e06..b4458ef64 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -321,6 +321,7 @@ class loggerModem : public Sensor } // Check that the modem is responding to AT commands. If not, give up. + MS_MOD_DBG(F("\nWaiting up to 5 seconds for modem to respond to AT commands...\n")); if (!_modem->testAT(5000)) { MS_MOD_DBG(F("\nModem does not respond to AT commands!\n")); @@ -548,7 +549,7 @@ class loggerModem : public Sensor F(" and on/off via 2.5 second pulse on pin "), modemSleepRqPin, F(".\n")); static pulsedOnOff modem_sleep_pulsed; modemOnOff = &modem_sleep_pulsed; - modem_sleep_pulsed.init(vcc33Pin, modemSleepRqPin, modemStatusPin); + modem_sleep_pulsed.init(vcc33Pin, modemSleepRqPin, modemStatusPin, true); break; } case modem_sleep_held: @@ -559,7 +560,7 @@ class loggerModem : public Sensor F(" and on/off by holding pin "), modemSleepRqPin, F(" high.\n")); static heldOnOff modem_sleep_held; modemOnOff = &modem_sleep_held; - modem_sleep_held.init(vcc33Pin, modemSleepRqPin, modemStatusPin); + modem_sleep_held.init(vcc33Pin, modemSleepRqPin, modemStatusPin, true); break; } case modem_sleep_reverse: @@ -568,9 +569,9 @@ class loggerModem : public Sensor F(" with power on pin "), vcc33Pin, F(" status on pin "), modemStatusPin, F(" and on/off by holding pin "), modemSleepRqPin, F(" low.\n")); - static reverseOnOff modem_sleep_reverse; - modemOnOff = &modem_sleep_reverse; - modem_sleep_reverse.init(vcc33Pin, modemSleepRqPin, modemStatusPin); + static heldOnOff modem_sleep_held; + modemOnOff = &modem_sleep_held; + modem_sleep_held.init(vcc33Pin, modemSleepRqPin, modemStatusPin, false); break; } default: diff --git a/src/ModemOnOff.cpp b/src/ModemOnOff.cpp index a331cc0d5..ce7bf0eca 100644 --- a/src/ModemOnOff.cpp +++ b/src/ModemOnOff.cpp @@ -29,47 +29,64 @@ ModemOnOff::ModemOnOff() } // Initializes the instance -void ModemOnOff::init(int vcc33Pin, int modemSleepRqPin, int modemStatusPin) +void ModemOnOff::init(int vcc33Pin, int modemSleepRqPin, int modemStatusPin, + bool isHighWhenOn) { MS_DBG(F("Initializing modem on/off...")); - if (vcc33Pin >= 0) { - _vcc33Pin = vcc33Pin; - // First write the output value, and only then set the output mode. - digitalWrite(_vcc33Pin, LOW); - pinMode(_vcc33Pin, OUTPUT); + + // Set whether using high or low to turn on + _isHighWhenOn = isHighWhenOn; + + // Set pin modes + _vcc33Pin = vcc33Pin; + if (vcc33Pin >= 0) + { + pinMode(_vcc33Pin, OUTPUT); // Set pin mode + digitalWrite(_vcc33Pin, LOW); // Set power off } - if (modemSleepRqPin >= 0) { - _modemSleepRqPin = modemSleepRqPin; - // First write the output value, and only then set the output mode. - digitalWrite(_modemSleepRqPin, LOW); - pinMode(_modemSleepRqPin, OUTPUT); + _modemSleepRqPin = modemSleepRqPin; + if (modemSleepRqPin >= 0) + { + pinMode(_modemSleepRqPin, OUTPUT); // Set pin mode + digitalWrite(_modemSleepRqPin, !isHighWhenOn); // Set to off } - if (modemStatusPin >= 0) { - _modemStatusPin = modemStatusPin; + _modemStatusPin = modemStatusPin; + if (modemStatusPin >= 0) + { pinMode(_modemStatusPin, INPUT_PULLUP); } + + // Initialize assuming modem is off + _isNowOn = false; + MS_DBG(F(" ... Success!\n")); } +// Function to check if the modem is currently on bool ModemOnOff::isOn(void) { - if (_modemStatusPin >= 0) { + if (_modemStatusPin >= 0) + { bool status = digitalRead(_modemStatusPin); + if (!_isHighWhenOn) status = !status; // MS_DBG(F("Is modem on? "), status, F("\n")); return status; } - // No status pin. Let's assume it is on. - return true; + // No status pin. Return the "internal" status code. + return _isNowOn; } +// Function to supply power to the modem - sets power pin high void ModemOnOff::powerOn(void) { - if (_vcc33Pin >= 0) { + if (_vcc33Pin >= 0) + { digitalWrite(_vcc33Pin, HIGH); MS_DBG(F("Sending power to modem.\n")); } } +// Function to cut power from the modem - sets power pin low void ModemOnOff::powerOff(void) { if (_vcc33Pin >= 0) { @@ -88,170 +105,172 @@ void ModemOnOff::powerOff(void) * ========================================================================= */ // Turns the modem on and off by pulsing the onoff/DTR/Key pin on for 2 seconds - bool pulsedOnOff::on(void) - { - powerOn(); - MS_DBG(F("Pulsing modem to on with pin ")); - MS_DBG(_modemSleepRqPin, F("\n")); - if (!isOn()) {pulse();} - // Wait until is actually on - for (uint32_t start = millis(); millis() - start < 5000; ) - { - if (isOn()) - { - MS_DBG(F("Modem now on.\n")); - return true; - } - delay(5); - } - MS_DBG(F("Failed to turn modem on.\n")); - return false; - } - -bool pulsedOnOff::off(void) +bool pulsedOnOff::on(void) { - if (isOn()) - { - MS_DBG(F("Pulsing modem off with pin ")); - MS_DBG(_modemSleepRqPin, F("\n")); - pulse(); - } - else MS_DBG(F("Modem was not ever on.\n")); - // Wait until is off - for (uint32_t start = millis(); millis() - start < 5000; ) + // Power up + powerOn(); + + // If no pin assigned to turn it on or off, assume it's on and return + if (_modemSleepRqPin <= 0) { - if (!isOn()) - { - MS_DBG(F("Modem now off.\n")); - powerOff(); - return true; - } - delay(5); + MS_DBG(F("No modem on/sleep pin assigned, assuming modem is on/awake.")); + _isNowOn = true; + return true; } - MS_DBG(F("Failed to turn modem off.\n")); - powerOff(); - return false; -} -void pulsedOnOff::pulse(void) -{ - if (_modemSleepRqPin >= 0) + // Check if it's already on before sending pulse + if (isOn()) { - digitalWrite(_modemSleepRqPin, LOW); - delay(200); - digitalWrite(_modemSleepRqPin, HIGH); - delay(2500); - digitalWrite(_modemSleepRqPin, LOW); + MS_DBG(F("Modem was already on.\n")); + _isNowOn = true; + return true; } -} - - -/* =========================================================================== -* Functions for the held on-off method. -* This turns the modem on by setting the onoff/DTR/Key pin high and off by -* setting it low. -* This is used by the Sodaq GPRSBee v0.6. -* ========================================================================= */ - -// Turns the modem on by setting the onoff/DTR/Key high and off by setting it low -bool heldOnOff::on(void) -{ - powerOn(); - if (_modemSleepRqPin <= 0) {return true;} else { - MS_DBG(F("Turning modem on by setting pin ")); - MS_DBG(_modemSleepRqPin); - MS_DBG(F(" high\n")); - digitalWrite(_modemSleepRqPin, HIGH); + MS_DBG(F("Turning modem on with a "), _isHighWhenOn, F(" pulse on pin "), + _modemSleepRqPin, F(".\n")); + pulse(); + // Wait until is actually on for (uint32_t start = millis(); millis() - start < 5000; ) { if (isOn()) { MS_DBG(F("Modem now on.\n")); + _isNowOn = true; return true; } delay(5); } - MS_DBG(F("Failed to turn modem on.\n")); + + // If the modem doesn't show it's on within 5 seconds, return false + MS_DBG(F("Failed to turn modem on!\n")); + _isNowOn = false; return false; } } -bool heldOnOff::off(void) +bool pulsedOnOff::off(void) { - if (_modemSleepRqPin <= 0) {return true;} + // If no pin assigned to turn it on or off, assume it's pff and return + if (_modemSleepRqPin <= 0) + { + MS_DBG(F("No modem on/sleep pin assigned, assuming modem is off/asleep.")); + _isNowOn = false; + return true; + } + + // Check if it's already off before sending pulse + if (!isOn()) + { + MS_DBG(F("Modem was not ever on.\n")); + _isNowOn = false; + return true; + } else { - if (!isOn()) MS_DBG(F("Modem was not ever on.\n")); - digitalWrite(_modemSleepRqPin, LOW); + MS_DBG(F("Turning modem off with a "), !_isHighWhenOn, F(" pulse on pin "), + _modemSleepRqPin, F(".\n")); + pulse(); + // Wait until is off for (uint32_t start = millis(); millis() - start < 5000; ) { if (!isOn()) { MS_DBG(F("Modem now off.\n")); + _isNowOn = false; powerOff(); return true; } delay(5); } - MS_DBG(F("Failed to turn modem off.\n")); + + // If the modem doesn't show it's off within 5 seconds, cut the power + // anyway and return true + MS_DBG(F("Failed to turn modem off with on/sleep pin!\n")); + // Power down anyway powerOff(); - return false; + _isNowOn = false; + return true; } } - -/* =========================================================================== -* Functions for the reverse on-off method. -* This turns the modem on by setting the onoff/DTR/Key pin LOW and off by -* setting it HIGH. -* This is used by the XBee's -* ========================================================================= */ - -// Turns the modem on by setting the onoff/DTR/Key LOW and off by setting it HIGH -bool reverseOnOff::isOn(void) +void pulsedOnOff::pulse(void) { - if (_modemStatusPin >= 0) { - bool status = digitalRead(_modemStatusPin); - // MS_DBG(F("Is modem on? "), status, F("\n")); - return !status; + if (_modemSleepRqPin >= 0) + { + digitalWrite(_modemSleepRqPin, !_isHighWhenOn); + delay(200); + digitalWrite(_modemSleepRqPin, _isHighWhenOn); + delay(2500); + digitalWrite(_modemSleepRqPin, !_isHighWhenOn); } - // No status pin. Let's assume it is on. - return true; } -bool reverseOnOff::on(void) + +/* =========================================================================== +* Functions for the held on-off method. +* This turns the modem on by setting and holding the onoff/DTR/Key pin to +* either high or low. +* A "high" on is used by the Sodaq GPRSBee v0.6 and Sodaq 3GBee. +* A "low" on is used by the all Digi XBee's. +* ========================================================================= */ + +// Turns the modem on by setting the onoff/DTR/Key high and off by setting it low +bool heldOnOff::on(void) { + // Power up powerOn(); - MS_DBG(F("Turning modem on on by setting pin ")); - MS_DBG(_modemSleepRqPin); - MS_DBG(F(" low\n")); - if (_modemSleepRqPin >= 0) { - digitalWrite(_modemSleepRqPin, LOW); + + // If no pin assigned to turn it on or off, assume it's on and return + if (_modemSleepRqPin <= 0) + { + MS_DBG(F("No modem on/sleep pin assigned, assuming modem is on/awake.")); + _isNowOn = true; + return true; } + + // Do not check if on or off; just set the pin to whatever it should be held + // at to turn the modem on + MS_DBG(F("Turning modem on by setting pin "), _modemSleepRqPin, F(" to "), + _isHighWhenOn, F(".\n")); + digitalWrite(_modemSleepRqPin, HIGH); + // Wait until is actually on for (uint32_t start = millis(); millis() - start < 5000; ) { if (isOn()) { MS_DBG(F("Modem now on.\n")); + _isNowOn = true; return true; } delay(5); } + + // If the modem doesn't show it's on within 5 seconds, return false MS_DBG(F("Failed to turn modem on.\n")); + _isNowOn = false; return false; } -bool reverseOnOff::off(void) +bool heldOnOff::off(void) { - if (!isOn()) MS_DBG(F("Modem was not ever on.\n")); - if (_modemSleepRqPin >= 0) { - digitalWrite(_modemSleepRqPin, HIGH); + // If no pin assigned to turn it on or off, assume it's off and return + if (_modemSleepRqPin <= 0) + { + MS_DBG(F("No modem on/sleep pin assigned, assuming modem is off/asleep.")); + _isNowOn = false; + return true; } + + // Do not check if on or off; just set the pin to whatever it should be held + // at to turn the modem off + MS_DBG(F("Turning modem off by setting pin "), _modemSleepRqPin, F(" to "), + !_isHighWhenOn, F(".\n")); + digitalWrite(_modemSleepRqPin, LOW); + // Wait until is off for (uint32_t start = millis(); millis() - start < 5000; ) { @@ -263,7 +282,12 @@ bool reverseOnOff::off(void) } delay(5); } + + // If the modem doesn't show it's off within 5 seconds, cut the power + // anyway and return true MS_DBG(F("Failed to turn modem off.\n")); + // Power down powerOff(); + _isNowOn = false; return false; } diff --git a/src/ModemOnOff.h b/src/ModemOnOff.h index 6cc311073..2a00e77fa 100644 --- a/src/ModemOnOff.h +++ b/src/ModemOnOff.h @@ -32,7 +32,8 @@ class ModemOnOff ModemOnOff(); // Initializes the instance - virtual void init(int vcc33Pin, int modemSleepRqPin, int modemStatusPin); + virtual void init(int vcc33Pin, int modemSleepRqPin, int modemStatusPin, + bool isHighWhenOn = true); virtual bool isOn(void); virtual bool on(void) = 0; @@ -42,6 +43,8 @@ class ModemOnOff int8_t _vcc33Pin; int8_t _modemSleepRqPin; int8_t _modemStatusPin; + bool _isNowOn; + bool _isHighWhenOn; void powerOn(void); void powerOff(void); @@ -58,6 +61,7 @@ class ModemOnOff * ========================================================================= */ // Turns the modem on and off by pulsing the onoff/DTR/Key pin on for 2 seconds +// "On" can either be a high or low pulse class pulsedOnOff : public ModemOnOff { public: @@ -72,9 +76,10 @@ class pulsedOnOff : public ModemOnOff /* =========================================================================== * Functions for the held on-off method. -* This turns the modem on by setting the onoff/DTR/Key pin high and off by -* setting it low. -* This is used by the Sodaq GPRSBee v0.6. +* This turns the modem on by setting and holding the onoff/DTR/Key pin to +* either high or low. +* A "high" on is used by the Sodaq GPRSBee v0.6 and Sodaq 3GBee. +* A "low" on is used by the all Digi XBee's. * ========================================================================= */ // Turns the modem on by setting the onoff/DTR/Key high and off by setting it low @@ -85,21 +90,4 @@ class heldOnOff : public ModemOnOff bool off(void) override; }; - -/* =========================================================================== -* Functions for the reverse on-off method. -* This turns the modem on by setting the onoff/DTR/Key pin LOW and off by -* setting it HIGH. -* This is used by the XBee's -* ========================================================================= */ - -// Turns the modem on by setting the onoff/DTR/Key LOW and off by setting it HIGH -class reverseOnOff : public ModemOnOff -{ -public: - bool isOn(void) override; - bool on(void) override; - bool off(void) override; -}; - #endif /* ModemOnOff_h */ From 4a10279e1031513391ce03d1914684ce5db812ff Mon Sep 17 00:00:00 2001 From: SRGDamia1 Date: Mon, 4 Jun 2018 17:18:30 -0400 Subject: [PATCH 51/54] Not trying to register to network before asking for CSQ Except for XBee's, which do not return a signal strength until after a full TCP connection is made. Other modems can ask for CSQ even without being registered to the network. Need to verify this for ESP8266's. --- src/LoggerBase.cpp | 2 +- src/LoggerModem.h | 157 ++++++++++++++++++++++++--------------------- src/ModemOnOff.cpp | 2 +- 3 files changed, 87 insertions(+), 74 deletions(-) diff --git a/src/LoggerBase.cpp b/src/LoggerBase.cpp index 09c5a0872..980c1bd58 100644 --- a/src/LoggerBase.cpp +++ b/src/LoggerBase.cpp @@ -958,7 +958,7 @@ void Logger::testingMode() // Create the log file, adding the default header to it if (createLogFile(true)) PRINTOUT(F("Data will be saved as "), _fileName, '\n'); - else PRINTOUT(F("Unable to create a file to save data to!")); + else PRINTOUT(F("Unable to create a file to save data to!\n")); // Set up the sensors _internalArray->setupSensors(); diff --git a/src/LoggerModem.h b/src/LoggerModem.h index b4458ef64..25a64ed3e 100644 --- a/src/LoggerModem.h +++ b/src/LoggerModem.h @@ -158,84 +158,101 @@ class loggerModem : public Sensor MS_MOD_DBG(F("Skipping modem in sensor power down!\n")); } - bool startSingleMeasurement(void) override - { - bool success = true; - - // Check if activated, only go on if it is - if (_millisSensorActivated > 0 && bitRead(_sensorStatus, 3)) - { - // Connect to the network before asking for quality - // Only waiting for up to 5 seconds here for the internet! - if (!(_modem->isNetworkConnected())) - { - MS_MOD_DBG(F("No prior internet connection, attempting to make a connection.")); - success &= connectInternet(5000L); - } - if (success == false) return false; - - // Mark the time that a measurement was requested - _millisMeasurementRequested = millis(); - } - // Make sure that the time of a measurement request is not set - else _millisMeasurementRequested = 0; - - // Even if we failed to start a measurement, we still want to set the status - // bit to show that we attempted to start the measurement. - // Set the status bits for measurement requested (bit 5) - _sensorStatus |= 0b00100000; - // Verify that the status bit for a single measurement completion is not set (bit 6) - _sensorStatus &= 0b10111111; - - return success; - } + // bool startSingleMeasurement(void) override + // { + // bool success = true; + // + // // Check if activated, only go on if it is + // if (_millisSensorActivated > 0 && bitRead(_sensorStatus, 3)) + // { + // // Connect to the network before asking for quality + // // Only waiting for up to 5 seconds here for the internet! + // if (!(_modem->isNetworkConnected())) + // { + // MS_MOD_DBG(F("No prior internet connection, attempting to make a connection.")); + // success &= connectInternet(2000L); + // } + // if (success == false) return false; + // + // // Mark the time that a measurement was requested + // _millisMeasurementRequested = millis(); + // } + // // Make sure that the time of a measurement request is not set + // else _millisMeasurementRequested = 0; + // + // // Even if we failed to start a measurement, we still want to set the status + // // bit to show that we attempted to start the measurement. + // // Set the status bits for measurement requested (bit 5) + // _sensorStatus |= 0b00100000; + // // Verify that the status bit for a single measurement completion is not set (bit 6) + // _sensorStatus &= 0b10111111; + // + // return success; + // } bool addSingleMeasurementResult(void) override { - // The XBee needs to make a connection and have that connection return a - // value before it knows the signal quality - // Connecting to the NIST daytime server, which immediately returns a - // 4 byte response and then closes the connection - if (loggerModemChip == sim_chip_XBeeWifi || loggerModemChip == sim_chip_XBeeCell) - { - // Must ensure that we do not ping the daylight more than once every 4 seconds - // NIST clearly specifies here that this is a requirement for all software - /// that accesses its servers: https://tf.nist.gov/tf-cgi/servers.cgi - while (millis() < _lastNISTrequest + 4000) {} - MS_MOD_DBG("Connecting to NIST daytime server to check connection strength...\n"); - IPAddress ip(129, 6, 15, 30); // This is the IP address of time-c-g.nist.gov - openTCP(ip, 37); - _client->print(F("Hi!")); // Need to send something before connection is made - delay(100); // Need this delay! Can get away with 50, but 100 is safer. - while (_client->available()) _client->read(); // Delete anything returned - _lastNISTrequest = millis(); - } - int signalQual = 0; int percent = 0; int rssi = -9999; - // Get signal quality - if (_modem->isNetworkConnected()) - { - MS_MOD_DBG("Getting signal quality:\n"); - signalQual = _modem->getSignalQuality(); - // Convert signal quality to RSSI, if necessary - if (loggerModemChip == sim_chip_XBeeWifi || - loggerModemChip == sim_chip_XBeeCell || - loggerModemChip == sim_chip_ESP8266) - { - rssi = signalQual; - percent = getPctFromRSSI(signalQual); - } - else + // Check that the modem is responding to AT commands. If not, give up. + MS_MOD_DBG(F("\nWaiting up to 5 seconds for modem to respond to AT commands...\n")); + if (_modem->testAT(5000)) + { + // The XBee needs to make an actual TCP connection and get some sort + // of response on that connection before it knows the signal quality. + // Connecting to the NIST daytime server, which immediately returns a + // 4 byte response and then closes the connection + if (loggerModemChip == sim_chip_XBeeWifi || loggerModemChip == sim_chip_XBeeCell) { - rssi = getRSSIFromCSQ(signalQual); - percent = getPctFromCSQ(signalQual); + // Connect to the network + // Only waiting for up to 5 seconds here for the internet! + if (!(_modem->isNetworkConnected())) + { + MS_MOD_DBG(F("No prior internet connection, attempting to make a connection.")); + connectInternet(5000L); + } + // Must ensure that we do not ping the daylight more than once every 4 seconds + // NIST clearly specifies here that this is a requirement for all software + /// that accesses its servers: https://tf.nist.gov/tf-cgi/servers.cgi + while (millis() < _lastNISTrequest + 4000) {} + MS_MOD_DBG("Connecting to NIST daytime server to check connection strength...\n"); + IPAddress ip(129, 6, 15, 30); // This is the IP address of time-c-g.nist.gov + openTCP(ip, 37); + _client->print(F("Hi!")); // Need to send something before connection is made + delay(100); // Need this delay! Can get away with 50, but 100 is safer. + while (_client->available()) _client->read(); // Delete anything returned + _lastNISTrequest = millis(); } + + // Get signal quality + // Non XBee's do not need to be registered or "connnected" to the + // network to get quality + // if (_modem->isNetworkConnected()) + // { + + MS_MOD_DBG("Getting signal quality:\n"); + signalQual = _modem->getSignalQuality(); + + // Convert signal quality to RSSI, if necessary + if (loggerModemChip == sim_chip_XBeeWifi || + loggerModemChip == sim_chip_XBeeCell || + loggerModemChip == sim_chip_ESP8266) + { + rssi = signalQual; + percent = getPctFromRSSI(signalQual); + } + else + { + rssi = getRSSIFromCSQ(signalQual); + percent = getPctFromCSQ(signalQual); + } + // } + // else MS_MOD_DBG("Insufficient signal to connect to the internet!\n"); } - else MS_MOD_DBG("Insufficient signal to connect to the internet!\n"); + else MS_MOD_DBG(F("\nModem does not respond to AT commands!\n")); MS_MOD_DBG(F("RSSI: "), rssi, F("\n")); MS_MOD_DBG(F("Percent signal strength: "), percent, F("\n")); @@ -433,21 +450,17 @@ class loggerModem : public Sensor bool modemPowerDown(void) { MS_MOD_DBG(F("Turning modem off.\n")); - bool retVal = true; // Wait for any sending to complete _client->flush(); // Turn the modem off .. whether it was on or not // Need to turn off no matter what because some modems don't have an // effective way of telling us whether they're on or not modemOnOff->off(); - // Double check if the modem is on; turn it off if so - if(modemOnOff->isOn()) retVal = modemOnOff->off(); - else retVal = true; // Unset the status bits for sensor power (bit 0), warm-up (bit 2), // activation (bit 3), stability (bit 4), measurement request (bit 5), and // measurement completion (bit 6) _sensorStatus &= 0b10000010; - return retVal; + return true; } // Get the time from NIST via TIME protocol (rfc868) diff --git a/src/ModemOnOff.cpp b/src/ModemOnOff.cpp index ce7bf0eca..9c982e40d 100644 --- a/src/ModemOnOff.cpp +++ b/src/ModemOnOff.cpp @@ -174,7 +174,7 @@ bool pulsedOnOff::off(void) pulse(); // Wait until is off - for (uint32_t start = millis(); millis() - start < 5000; ) + for (uint32_t start = millis(); millis() - start < 1000; ) { if (!isOn()) { From 67955c48885379b10b74e84b77b1d1273b885274 Mon Sep 17 00:00:00 2001 From: Beth Fisher Date: Mon, 30 Jul 2018 15:58:12 -0500 Subject: [PATCH 52/54] Tiny edit for clarity of the unassigned sensor option for DS18 --- examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index 6f50866c5..40af6a510 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -279,8 +279,8 @@ MaximDS18 ds18_2(OneWireAddress2, OneWirePower, OneWireBus); MaximDS18 ds18_3(OneWireAddress3, OneWirePower, OneWireBus); MaximDS18 ds18_4(OneWireAddress4, OneWirePower, OneWireBus); MaximDS18 ds18_5(OneWireAddress5, OneWirePower, OneWireBus); -// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknow address) -// MaximDS18 ds18_5(OneWirePower, OneWireBus); +// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknown/unassigned address) +// MaximDS18 ds18_u(OneWirePower, OneWireBus); // ========================================================================== @@ -458,6 +458,7 @@ Variable *variableList[] = { new MaximDS18_Temp(&ds18_3, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_4, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_5, "12345678-abcd-1234-efgh-1234567890ab"), + new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Temp(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Pressure(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MPL115A2_Temp(&mpl115a2, "12345678-abcd-1234-efgh-1234567890ab"), From 6892a0f9fb13f131447b377f9c383443daa8d683 Mon Sep 17 00:00:00 2001 From: Anthony Aufdenkampe Date: Thu, 6 Sep 2018 16:52:11 -0500 Subject: [PATCH 53/54] Correct typos in code --- .../baro_rho_correction.ino | 18 +++++++++--------- src/VariableBase.h | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/baro_rho_correction/baro_rho_correction.ino b/examples/baro_rho_correction/baro_rho_correction.ino index f7e2fe33c..3591f5c29 100644 --- a/examples/baro_rho_correction/baro_rho_correction.ino +++ b/examples/baro_rho_correction/baro_rho_correction.ino @@ -113,7 +113,7 @@ loggerModem modem; // Create the RSSI and signal strength variable objects for the modem and return // variable-type pointers to them Variable *modemRSSI = new Modem_RSSI(&modem, "12345678-abcd-1234-efgh-1234567890ab"); -Variable *modemSinalPct = new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"); +Variable *modemSignalPct = new Modem_SignalPercent(&modem, "12345678-abcd-1234-efgh-1234567890ab"); // ========================================================================== @@ -194,15 +194,15 @@ float calculateWaterPressure(void) return waterPressure; } // Properties of the calculated water pressure variable -const char *waterPresureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ -const char *waterPresureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ -int waterPresureVarResolution = 3; +const char *waterPressureVarName = "pressureGauge"; // This must be a value from http://vocabulary.odm2.org/variablename/ +const char *waterPressureVarUnit = "millibar"; // This must be a value from http://vocabulary.odm2.org/units/ +int waterPressureVarResolution = 3; const char *waterPressureUUID = "12345678-abcd-1234-efgh-1234567890ab"; -const char *waterPresureVarCode = "CorrectedPressure"; +const char *waterPressureVarCode = "CorrectedPressure"; // Create the calculated water pressure variable objects and return a variable pointer to it -Variable *calcWaterPress = new Variable(calculateWaterPressure, waterPresureVarName, - waterPresureVarUnit, waterPresureVarResolution, - waterPressureUUID, waterPresureVarCode); +Variable *calcWaterPress = new Variable(calculateWaterPressure, waterPressureVarName, + waterPressureVarUnit, waterPressureVarResolution, + waterPressureUUID, waterPressureVarCode); // Create the function to calculate the "raw" water depth // For this, we're using the conversion between mbar and mm pure water at 4°C @@ -284,7 +284,7 @@ Variable *variableList[] = { calcRawDepth, calcCorrDepth, modemRSSI, - modemSinalPct + modemSignalPct }; // Count up the number of pointers in the array int variableCount = sizeof(variableList) / sizeof(variableList[0]); diff --git a/src/VariableBase.h b/src/VariableBase.h index e0152c45f..16187d034 100644 --- a/src/VariableBase.h +++ b/src/VariableBase.h @@ -28,7 +28,7 @@ class Variable const char *defaultVarCode = VAR_BASE_UNKNOWN, const char *UUID = "", const char *customVarCode = ""); - // The constructor for a measured variable - that is, one whose value is + // The constructor for a calculated variable - that is, one whose value is // calculated by the calcFxn which returns a float. // NOTE: ALL arguments are required! Variable(float (*calcFxn)(), From c1af0800fb6386f48c5b55d5af4940d515299cdd Mon Sep 17 00:00:00 2001 From: Sara Damiano Date: Fri, 7 Sep 2018 16:50:29 -0400 Subject: [PATCH 54/54] Fix to unknown maxim in EnviroDIY examples --- examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino | 4 ++-- .../logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino index ac36879bf..f3e4a56fa 100644 --- a/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino +++ b/examples/logging_to_EnviroDIY/logging_to_EnviroDIY.ino @@ -284,7 +284,7 @@ MaximDS18 ds18_2(OneWireAddress2, OneWirePower, OneWireBus); MaximDS18 ds18_3(OneWireAddress3, OneWirePower, OneWireBus); MaximDS18 ds18_4(OneWireAddress4, OneWirePower, OneWireBus); MaximDS18 ds18_5(OneWireAddress5, OneWirePower, OneWireBus); -// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknown/unassigned address) +// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknown address) // MaximDS18 ds18_u(OneWirePower, OneWireBus); @@ -465,7 +465,7 @@ Variable *variableList[] = { new MaximDS18_Temp(&ds18_3, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_4, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_5, "12345678-abcd-1234-efgh-1234567890ab"), - new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-1234567890ab"), + // new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Temp(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Pressure(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MPL115A2_Temp(&mpl115a2, "12345678-abcd-1234-efgh-1234567890ab"), diff --git a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino index 02095472c..400d4a676 100644 --- a/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino +++ b/examples/logging_to_EnviroDIY_Zero/logging_to_EnviroDIY_Zero.ino @@ -277,8 +277,8 @@ MaximDS18 ds18_2(OneWireAddress2, OneWirePower, OneWireBus); MaximDS18 ds18_3(OneWireAddress3, OneWirePower, OneWireBus); MaximDS18 ds18_4(OneWireAddress4, OneWirePower, OneWireBus); MaximDS18 ds18_5(OneWireAddress5, OneWirePower, OneWireBus); -// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknow address) -// MaximDS18 ds18_5(OneWirePower, OneWireBus); +// Create and return the Maxim DS18 sensor object (use this form for a single sensor on bus with an unknown address) +// MaximDS18 ds18_u(OneWirePower, OneWireBus); // ========================================================================== @@ -469,6 +469,7 @@ Variable *variableList[] = { new MaximDS18_Temp(&ds18_3, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_4, "12345678-abcd-1234-efgh-1234567890ab"), new MaximDS18_Temp(&ds18_5, "12345678-abcd-1234-efgh-1234567890ab"), + // new MaximDS18_Temp(&ds18_u, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Temp(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MeaSpecMS5803_Pressure(&ms5803, "12345678-abcd-1234-efgh-1234567890ab"), new MPL115A2_Temp(&mpl115a2, "12345678-abcd-1234-efgh-1234567890ab"),