From 2292087a32db65b052d63ff059bd1dca64b30265 Mon Sep 17 00:00:00 2001 From: Hpsaturn Date: Sat, 3 Feb 2024 23:58:35 +0100 Subject: [PATCH] updated all source file to the new .clang-format repo style --- src/Sensors.cpp | 262 +++++++---------- src/Sensors.hpp | 626 ++++++++++++++++++++-------------------- src/drivers/MovingSum.h | 128 ++++---- src/drivers/geiger.cpp | 29 +- src/drivers/geiger.h | 11 +- src/drivers/pm1006.cpp | 154 +++++----- src/drivers/pm1006.h | 75 +++-- 7 files changed, 605 insertions(+), 680 deletions(-) diff --git a/src/Sensors.cpp b/src/Sensors.cpp index fe0e82fb..6fdb45b3 100644 --- a/src/Sensors.cpp +++ b/src/Sensors.cpp @@ -31,8 +31,9 @@ uint8_t sensors_registered[SCOUNT]; * All sensors are read here, please call it on main loop. */ void Sensors::loop() { - static uint32_t pmLoopTimeStamp = 0; // timestamp for sensor loop check data - if ((millis() - pmLoopTimeStamp > sample_time * (uint32_t)1000)) { // sample time for each capture + static uint32_t pmLoopTimeStamp = 0; // timestamp for sensor loop check data + if ((millis() - pmLoopTimeStamp > + sample_time * (uint32_t)1000)) { // sample time for each capture pmLoopTimeStamp = millis(); readAllSensors(); @@ -161,9 +162,9 @@ void Sensors::setSampleTime(int seconds) { /** * @brief set CO2 recalibration PPM value (400 to 2000) * @param ppmValue the ppm value to set, normally 400. - * + * * This method is used to set the CO2 recalibration value, please use it only on outdoor conditions. - * Please see the documentation of each sensor for more information. + * Please see the documentation of each sensor for more information. */ void Sensors::setCO2RecalibrationFactor(int ppmValue) { if (isSensorRegistered(SENSORS::SSCD30)) { @@ -198,7 +199,7 @@ void Sensors::setCO2RecalibrationFactor(int ppmValue) { /** * @brief set CO2 altitude offset (m) * @param altitude (m). - * + * * This method is used to compensate the CO2 value with the altitude. Recommended on high altitude. */ void Sensors::setCO2AltitudeOffset(float altitude) { @@ -220,12 +221,10 @@ void Sensors::setCO2AltitudeOffset(float altitude) { /** * @brief set the sea level pressure (hPa) * @param hpa (hPa). - * + * * This method is used to set the sea level pressure for some sensors that need it. */ -void Sensors::setSeaLevelPressure(float hpa) { - sealevel = hpa; -} +void Sensors::setSeaLevelPressure(float hpa) { sealevel = hpa; } /// restart and re-init all sensors (not recommended) void Sensors::restart() { @@ -238,70 +237,48 @@ void Sensors::restart() { * @brief Get sensor data. * @param cb (mandatory) callback function to be called when data is ready. */ -void Sensors::setOnDataCallBack(voidCbFn cb) { - _onDataCb = cb; -} +void Sensors::setOnDataCallBack(voidCbFn cb) { _onDataCb = cb; } /** * @brief Optional callback for get the sensors errors * @param cb callback function to be called when any warnning or error happens. */ -void Sensors::setOnErrorCallBack(errorCbFn cb) { - _onErrorCb = cb; -} +void Sensors::setOnErrorCallBack(errorCbFn cb) { _onErrorCb = cb; } /** * @brief Optional for increase the debug level * @param enable true to enable debug mode, false to disable debug mode. */ -void Sensors::setDebugMode(bool enable) { - devmode = enable; -} +void Sensors::setDebugMode(bool enable) { devmode = enable; } /// get the sensor status -bool Sensors::isDataReady() { - return readAllComplete; -} +bool Sensors::isDataReady() { return readAllComplete; } /// get PM1.0 ug/m3 value -uint16_t Sensors::getPM1() { - return pm1; -} +uint16_t Sensors::getPM1() { return pm1; } /// get PM2.5 ug/m3 value -uint16_t Sensors::getPM25() { - return pm25; -} +uint16_t Sensors::getPM25() { return pm25; } /// get PM4 ug/m3 value -uint16_t Sensors::getPM4() { - return pm4; -} +uint16_t Sensors::getPM4() { return pm4; } /// get PM10 ug/m3 value -uint16_t Sensors::getPM10() { - return pm10; -} +uint16_t Sensors::getPM10() { return pm10; } /// get CO2 ppm value -uint16_t Sensors::getCO2() { - return CO2Val; -} +uint16_t Sensors::getCO2() { return CO2Val; } /// get humidity % value of CO2 sensor device -float Sensors::getCO2humi() { - return CO2humi; -} +float Sensors::getCO2humi() { return CO2humi; } /// get humidity % value of environment sensor -float Sensors::getHumidity() { - return humi; -} +float Sensors::getHumidity() { return humi; } /** * @brief set the temperature type unit * @param tunit celciuse, kelvin or fahrenheit. -*/ + */ void Sensors::setTemperatureUnit(TEMPUNIT tunit) { temp_unit = tunit; String tunit_symbol; @@ -350,9 +327,9 @@ float Sensors::getTemperature() { /** * @brief Temperature unit register (auto) * @param isCO2temp temperature unit register for CO2 sensors. - * + * * This method should register the right unit regarding setTemperatureUnit() method. -*/ + */ void Sensors::tempRegister(bool isCO2temp) { switch (temp_unit) { case (TEMPUNIT::CELSIUS): @@ -378,8 +355,8 @@ void Sensors::tempRegister(bool isCO2temp) { /** * @brief Set temperature offset for all temperature sensors - * @param offset temperature offset in °C (default 0). - * + * @param offset temperature offset in °C (default 0). + * * Positive value for offset to be subtracetd to the temperature. */ void Sensors::setTempOffset(float offset) { @@ -390,73 +367,49 @@ void Sensors::setTempOffset(float offset) { } /// get Gas resistance value of BMP680 sensor -float Sensors::getGas() { - return gas; -} +float Sensors::getGas() { return gas; } /// get Altitude value in meters -float Sensors::getAltitude() { - return alt; -} +float Sensors::getAltitude() { return alt; } /// get Pressure value in hPa -float Sensors::getPressure() { - return pres; -} +float Sensors::getPressure() { return pres; } /// get NH3 value in ppm -float Sensors::getNH3() { - return nh3; -} +float Sensors::getNH3() { return nh3; } /// get CO value in ppm -float Sensors::getCO() { - return co; -} +float Sensors::getCO() { return co; } /// get NO2 value in ppm -float Sensors::getNO2() { - return no2; -} +float Sensors::getNO2() { return no2; } /** * @brief UART only: check if the UART sensor is registered * @return bool true if the UART sensor is registered, false otherwise. */ -bool Sensors::isUARTSensorConfigured() { - return dev_uart_type >= 0; -} +bool Sensors::isUARTSensorConfigured() { return dev_uart_type >= 0; } /** * @brief UART only: get the UART sensor type. See SENSORS enum. Also getDeviceName() * @return SENSORS enum value. */ -int Sensors::getUARTDeviceTypeSelected() { - return dev_uart_type; -} +int Sensors::getUARTDeviceTypeSelected() { return dev_uart_type; } /** * @brief Forced to enable I2C sensors only. * Recommended to use only if you are using a I2C sensor and improve the performance. */ -void Sensors::detectI2COnly(bool enable) { - i2conly = enable; -} +void Sensors::detectI2COnly(bool enable) { i2conly = enable; } /// returns the CanAirIO Sensorslib version -String Sensors::getLibraryVersion() { - return String(CSL_VERSION); -} +String Sensors::getLibraryVersion() { return String(CSL_VERSION); } /// return the current revision code number -int16_t Sensors::getLibraryRevision() { - return CSL_REVISION; -} +int16_t Sensors::getLibraryRevision() { return CSL_REVISION; } /// get device sensors detected count -uint8_t Sensors::getSensorsRegisteredCount() { - return sensors_registered_count; -} +uint8_t Sensors::getSensorsRegisteredCount() { return sensors_registered_count; } /** * @brief Read and check the sensors status on initialization @@ -484,7 +437,7 @@ String Sensors::getSensorName(SENSORS sensor) { * @brief get the sensor group type * @param sensor (mandatory) SENSORS enum value. * @return Sensor group int with the sensor type. - * + * * if the sensor is not in a group, return 0. * if the sensor is in a group, return 1 (PM), 2 (CO2), 3 (ENV). */ @@ -495,18 +448,16 @@ SensorGroup Sensors::getSensorGroup(SENSORS sensor) { /** * @brief get the sensor registry for retrieve the sensor names * @return pointer to the sensor registry. - * - * See the Advanced Multivariable example + * + * See the Advanced Multivariable example */ -uint8_t *Sensors::getSensorsRegistered() { - return sensors_registered; -} +uint8_t *Sensors::getSensorsRegistered() { return sensors_registered; } /** * @brief get the sensor unit status on the registry * @return True if the sensor unit is available, false otherwise. - * - * See the Advanced Multivariable example + * + * See the Advanced Multivariable example */ bool Sensors::isUnitRegistered(UNIT unit) { if (unit == UNIT::NUNIT) return false; @@ -517,19 +468,16 @@ bool Sensors::isUnitRegistered(UNIT unit) { } /** - * @brief get the sensor units registry for retrieve the unit name, unit type and symbol. See getNextUnit() + * @brief get the sensor units registry for retrieve the unit name, unit type and symbol. See + * getNextUnit() * @return pointer to the sensor units registry - * - * See the Advanced Multivariable example + * + * See the Advanced Multivariable example */ -uint8_t *Sensors::getUnitsRegistered() { - return units_registered; -} +uint8_t *Sensors::getUnitsRegistered() { return units_registered; } /// get device sensors units detected count -uint8_t Sensors::getUnitsRegisteredCount() { - return units_registered_count; -} +uint8_t Sensors::getUnitsRegisteredCount() { return units_registered_count; } /** * @brief get the sensor unit name @@ -546,9 +494,7 @@ String Sensors::getUnitName(UNIT unit) { * @param unit (mandatory) UNIT enum value. * @return String with the unit symbol. */ -String Sensors::getUnitSymbol(UNIT unit) { - return String(unit_symbol[unit]); -} +String Sensors::getUnitSymbol(UNIT unit) { return String(unit_symbol[unit]); } /** * @brief get the next sensor unit available @@ -567,7 +513,7 @@ UNIT Sensors::getNextUnit() { /** * @brief reset the sensor units registry. - * + * * This function is useful to reset the units registry after a sensor unit is removed. * but it is **Not necessary** to call this function. */ @@ -579,7 +525,7 @@ void Sensors::resetUnitsRegister() { } /** * @brief reset the sensor registry. - * + * * This function is useful to reset the sensors registry after a sensor is removed. * It should be called before the initialization of the sensors but * it is **Not necessary** to call this function. @@ -593,20 +539,18 @@ void Sensors::resetSensorsRegister() { /** * @brief reset the next sensor unit counter. - * + * * This function is useful to reset the counter to review the sensor units again. * but it is not necessary to call this function. */ -void Sensors::resetNextUnit() { - current_unit = 0; -} +void Sensors::resetNextUnit() { current_unit = 0; } /** * @brief get the sensor unit value (float) * @param unit (mandatory) UNIT enum value. * @return float value of the each unit (RAW). - * - * Also you can use the specific primitive like getTemperature(), + * + * Also you can use the specific primitive like getTemperature(), * getHumidity(), getGas(), getAltitude(), getPressure() */ float Sensors::getUnitValue(UNIT unit) { @@ -706,8 +650,8 @@ void Sensors::printValues() { } /****************************************************************************** -* S E N S O R P R I V A T E M E T H O D S -******************************************************************************/ + * S E N S O R P R I V A T E M E T H O D S + ******************************************************************************/ /** * @brief PMS sensor generic read. Supported: Honeywell & Plantower sensors @@ -832,7 +776,7 @@ String Sensors::hwSerialRead(unsigned int lenght_buffer) { bool Sensors::sps30Read() { if (!isSensorRegistered(SENSORS::SSPS30)) return false; uint8_t ret, error_cnt = 0; - delay(35); //Delay for sincronization + delay(35); // Delay for sincronization do { ret = sps30.GetValues(&val); @@ -949,8 +893,8 @@ bool Sensors::pmSensorRead() { } /****************************************************************************** -* I 2 C S E N S O R R E A D M E T H O D S -******************************************************************************/ + * I 2 C S E N S O R R E A D M E T H O D S + ******************************************************************************/ void Sensors::am2320Read() { if (!am2320.isConnected()) return; @@ -1084,8 +1028,7 @@ void Sensors::sen5xRead() { uint16_t error = sen5x.readMeasuredValues( massConcentrationPm1p0, massConcentrationPm2p5, massConcentrationPm4p0, - massConcentrationPm10p0, ambientHumidity, ambientTemperature, vocIndex, - noxIndex); + massConcentrationPm10p0, ambientHumidity, ambientTemperature, vocIndex, noxIndex); if (error) return; @@ -1199,10 +1142,10 @@ void Sensors::sps30Errorloop(char *mess, uint8_t r) { /** * Particule meter sensor (PMS) init. - * + * * Hardware serial init for multiple PM sensors, like * Honeywell, Plantower, Panasonic, Sensirion, etc. - * + * * @param pms_type PMS type, please see DEVICE_TYPE enum. * @param pms_rx PMS RX pin. * @param pms_tx PMS TX pin. @@ -1252,8 +1195,8 @@ bool Sensors::sensorSerialInit(u_int pms_type, int pms_rx, int pms_tx) { return false; } /** - * @brief Generic PM sensor auto detection. - * + * @brief Generic PM sensor auto detection. + * * In order UART config, this method looking up for * special header on Serial stream **/ @@ -1458,7 +1401,8 @@ bool Sensors::sps30I2CInit() { // start measurement if (sps30.start()) { DEBUG("-->[SLIB] SPS30 Measurement OK"); - if (sps30.I2C_expect() == 4) DEBUG("[W][SLIB] SPS30 setup message\t: I2C buffersize only PM values \r\n"); + if (sps30.I2C_expect() == 4) + DEBUG("[W][SLIB] SPS30 setup message\t: I2C buffersize only PM values \r\n"); sensorRegister(SENSORS::SSPS30); return true; } else @@ -1491,7 +1435,7 @@ void Sensors::sps30DeviceInfo() { uint8_t ret; SPS30_version v; - //try to read serial number + // try to read serial number ret = sps30.GetSerialNumber(buf, 32); if (ret == SPS30_ERR_OK) { if (strlen(buf) > 0) @@ -1564,10 +1508,9 @@ void Sensors::bme280Init() { #ifndef Wire1 if (!bme280.begin() && !bme280.begin(BME280_ADDRESS_ALTERNATE)) return; #else - if (!bme280.begin() && - !bme280.begin(BME280_ADDRESS_ALTERNATE) && - !bme280.begin(BME280_ADDRESS, &Wire1) && - !bme280.begin(BME280_ADDRESS_ALTERNATE, &Wire1)) return; + if (!bme280.begin() && !bme280.begin(BME280_ADDRESS_ALTERNATE) && + !bme280.begin(BME280_ADDRESS, &Wire1) && !bme280.begin(BME280_ADDRESS_ALTERNATE, &Wire1)) + return; #endif sensorRegister(SENSORS::SBME280); } @@ -1680,7 +1623,8 @@ void Sensors::CO2scd4xInit() { if (tSensorAltitude != uint16_t(altoffset)) setSCD4xAltitudeOffset(altoffset); offsetDifference = abs((toffset * 100) - (tTemperatureOffset * 100)); - if (offsetDifference > 0.5) { // Accounts for SCD4x conversion rounding errors in temperature offset + if (offsetDifference > + 0.5) { // Accounts for SCD4x conversion rounding errors in temperature offset Serial.println("-->[SLIB] SCD4x new offset\t: Temp offset to" + String(toffset)); setSCD4xTempOffset(toffset); } @@ -1723,7 +1667,8 @@ void Sensors::sen5xInit() { error = sen5x.deviceReset(); if (error) return; float tempOffset = 0.0; - DEBUG("-->[SLIB] SEN5X Temp offset\t:", String(sen5x.getTemperatureOffsetSimple(tempOffset)).c_str()); + DEBUG("-->[SLIB] SEN5X Temp offset\t:", + String(sen5x.getTemperatureOffsetSimple(tempOffset)).c_str()); if (uint16_t((tempOffset * 100)) != (uint16_t(toffset * 100))) { sen5x.setTemperatureOffsetSimple(toffset); delay(10); @@ -1756,11 +1701,12 @@ void Sensors::GCJA5Init() { /// DFRobot GAS (CO) sensors init void Sensors::DFRobotCOInit() { sensorAnnounce(SENSORS::SDFRCO); - dfrCO = DFRobot_GAS_I2C(&Wire, 0x78); // Be sure that your group of i2c address is 7, and A0=0 A1=0 + dfrCO = + DFRobot_GAS_I2C(&Wire, 0x78); // Be sure that your group of i2c address is 7, and A0=0 A1=0 if (!dfrCO.begin()) return; - //Mode of obtaining data: the main controller needs to request the sensor for data + // Mode of obtaining data: the main controller needs to request the sensor for data dfrCO.changeAcquireMode(dfrCO.PASSIVITY); - //Turn on temperature compensation: gas.ON : turn on + // Turn on temperature compensation: gas.ON : turn on dfrCO.setTempCompensation(dfrCO.ON); sensorRegister(SENSORS::SDFRCO); } @@ -1768,11 +1714,12 @@ void Sensors::DFRobotCOInit() { /// DFRobot GAS (NH3) sensors init void Sensors::DFRobotNH3Init() { sensorAnnounce(SENSORS::SDFRNH3); - dfrNH3 = DFRobot_GAS_I2C(&Wire, 0x7A); // 0x77 y 0x75 used by bme680. Be sure that your group of i2c address is 7, and A0=1 A1=0 + dfrNH3 = DFRobot_GAS_I2C(&Wire, 0x7A); // 0x77 y 0x75 used by bme680. Be sure that your group of + // i2c address is 7, and A0=1 A1=0 if (!dfrNH3.begin()) return; - //Mode of obtaining data: the main controller needs to request the sensor for data + // Mode of obtaining data: the main controller needs to request the sensor for data dfrNH3.changeAcquireMode(dfrNH3.PASSIVITY); - //Turn on temperature compensation: gas.ON : turn on + // Turn on temperature compensation: gas.ON : turn on dfrNH3.setTempCompensation(dfrNH3.ON); sensorRegister(SENSORS::SDFRNH3); } @@ -1780,11 +1727,12 @@ void Sensors::DFRobotNH3Init() { /// DFRobot GAS (NO2) sensors init void Sensors::DFRobotNO2Init() { sensorAnnounce(SENSORS::SDFRNO2); - dfrNO2 = DFRobot_GAS_I2C(&Wire, 0x7B); // Be sure that your group of i2c address is 7, and A0=1 A1=1 + dfrNO2 = + DFRobot_GAS_I2C(&Wire, 0x7B); // Be sure that your group of i2c address is 7, and A0=1 A1=1 if (!dfrNO2.begin()) return; - //Mode of obtaining data: the main controller needs to request the sensor for data + // Mode of obtaining data: the main controller needs to request the sensor for data dfrNO2.changeAcquireMode(dfrNO2.PASSIVITY); - //Turn on temperature compensation: gas.ON : turn on + // Turn on temperature compensation: gas.ON : turn on dfrNO2.setTempCompensation(dfrNO2.ON); sensorRegister(SENSORS::SDFRNO2); } @@ -1792,7 +1740,8 @@ void Sensors::DFRobotNO2Init() { // Altitude compensation for CO2 sensors without Pressure atm or Altitude compensation void Sensors::CO2correctionAlt() { DEBUG("-->[SLIB] CO2 altitud original\t:", String(CO2Val).c_str()); - float CO2cor = (0.016 * ((1013.25 - hpa) / 10) * (CO2Val - 400)) + CO2Val; // Increment of 1.6% for every hpa of difference at sea level + float CO2cor = (0.016 * ((1013.25 - hpa) / 10) * (CO2Val - 400)) + + CO2Val; // Increment of 1.6% for every hpa of difference at sea level CO2Val = round(CO2cor); DEBUG("-->[SLIB] CO2 compensated\t:", String(CO2Val).c_str()); } @@ -1800,7 +1749,10 @@ void Sensors::CO2correctionAlt() { /// hPa hectopascal calculation based on the altitude. See CO2AltitudeOffset setter float Sensors::hpaCalculation(float altitude) { DEBUG("-->[SLIB] CO2 altitude offset\t:", String(altitude).c_str()); - float hpa = 1012 - 0.118 * altitude + 0.00000473 * altitude * altitude; // Cuadratic regresion formula obtained PA (hpa) from high above the sea + float hpa = + 1012 - 0.118 * altitude + + 0.00000473 * altitude * + altitude; // Cuadratic regresion formula obtained PA (hpa) from high above the sea DEBUG("-->[SLIB] CO2 pressure (hPa)\t:", String(hpa).c_str()); return hpa; } @@ -1813,10 +1765,10 @@ void Sensors::sensorAnnounce(SENSORS sensor) { /** * @brief register the sensor type. * @param receive SENSORS enum param. - * + * * Each sensor should be registered and also its units. With that we will able to have * dynamic calls of the sensors and its units on the GUI or implementation. -*/ + */ void Sensors::sensorRegister(SENSORS sensor) { if (isSensorRegistered(sensor) && sensor != SENSORS::Auto) { return; @@ -1831,7 +1783,7 @@ void Sensors::sensorRegister(SENSORS sensor) { * * Each sensor unit should be registered. For temperature sensors * please use tempRegister() method. -*/ + */ void Sensors::unitRegister(UNIT unit) { if (isUnitRegistered(unit)) return; if (unit == UNIT::NUNIT) return; @@ -1868,7 +1820,7 @@ void Sensors::geigerRead() { /** * @brief Enable Geiger sensor on specific pin * @param gpio number or pin. -*/ + */ void Sensors::enableGeigerSensor(int gpio) { sensorAnnounce(SENSORS::SCAJOE); if (gpio < 0) { @@ -1882,7 +1834,7 @@ void Sensors::enableGeigerSensor(int gpio) { /** * @brief get Geiger count. Tics in the last 60secs * @return CPM -*/ + */ uint32_t Sensors::getGeigerCPM(void) { if (rad == nullptr) return 0; @@ -1893,7 +1845,7 @@ uint32_t Sensors::getGeigerCPM(void) { /** * @brief get Geiger count in uSv/h units * @return CPM * J305 conversion factor -*/ + */ float Sensors::getGeigerMicroSievertHour(void) { if (rad == nullptr) return 0; @@ -1924,7 +1876,8 @@ void Sensors::startI2C() { #ifdef M5ATOM enableWire1(); #endif -#if not defined(M5STICKCPLUS) && not defined(M5COREINK) && not defined(M5ATOM) && not defined(ESP32C3) +#if not defined(M5STICKCPLUS) && not defined(M5COREINK) && not defined(M5ATOM) && \ + not defined(ESP32C3) Wire.begin(); #endif #ifdef ESP32C3 @@ -1959,13 +1912,16 @@ void Sensors::disableWire1() { } bool Sensors::serialInit(u_int pms_type, unsigned long speed_baud, int pms_rx, int pms_tx) { - if (devmode) Serial.printf("-->[SLIB] UART init with speed\t: %lu TX:%i RX:%i\r\n", speed_baud, pms_tx, pms_rx); + if (devmode) + Serial.printf("-->[SLIB] UART init with speed\t: %lu TX:%i RX:%i\r\n", speed_baud, pms_tx, + pms_rx); switch (SENSOR_COMMS) { case SERIALPORT: Serial.begin(speed_baud); _serial = &Serial; break; -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(SAMD21G18A) || defined(ARDUINO_SAM_DUE) +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(SAMD21G18A) || \ + defined(ARDUINO_SAM_DUE) case SERIALPORT1: Serial1.begin(speed_baud); _serial = &Serial1; @@ -1990,8 +1946,8 @@ bool Sensors::serialInit(u_int pms_type, unsigned long speed_baud, int pms_rx, i #endif #if defined(ARDUINO_ARCH_ESP32) - //on a Sparkfun ESP32 Thing the default pins for serial1 are used for acccessing flash memory - //you have to define different pins upfront in order to use serial1 port. + // on a Sparkfun ESP32 Thing the default pins for serial1 are used for acccessing flash memory + // you have to define different pins upfront in order to use serial1 port. case SERIALPORT1: DEBUG("-->[SLIB] UART COMM port \t: Serial1"); if (pms_rx == 0 || pms_tx == 0) { @@ -2043,7 +1999,7 @@ bool Sensors::serialInit(u_int pms_type, unsigned long speed_baud, int pms_rx, i #else DEBUG("-->[SLIB] UART SoftwareSerial \t: disable"); return (false); -#endif //INCLUDE_SOFTWARE_SERIAL +#endif // INCLUDE_SOFTWARE_SERIAL } break; } diff --git a/src/Sensors.hpp b/src/Sensors.hpp index 80f398b4..7442f1d4 100644 --- a/src/Sensors.hpp +++ b/src/Sensors.hpp @@ -6,37 +6,39 @@ #include #include #include -#include #include +#include #include +#include #include +#include +#include #include #include +#include +#include #include -#include #include -#include -#include -#include -#include #ifdef DHT11_ENABLED -#include +#include #endif #define CSL_VERSION "0.7.3" #define CSL_REVISION 382 /*************************************************************** -* S E T U P E S P 3 2 B O A R D S A N D F I E L D S -***************************************************************/ + * S E T U P E S P 3 2 B O A R D S A N D F I E L D S + ***************************************************************/ #ifdef WEMOSOLED -#define PMS_RX 13 // config for Wemos board & TTGO18650 -#define PMS_TX 15 // some old TTGO18650 have PMS_RX 18 & PMS_TX 17 +#define PMS_RX 13 // config for Wemos board & TTGO18650 +#define PMS_TX 15 // some old TTGO18650 have PMS_RX 18 & PMS_TX 17 #elif HELTEC #define PMS_RX 17 // config for Heltec board, ESP32Sboard & ESPDUINO-32. Use Uart2 -#define PMS_TX 18 // some old ESP32Sboard have PMS_RX 27 & PMS_TX 25. Jump Uart2 tx from 16 to 18. !6 used by Oled. +#define PMS_TX \ + 18 // some old ESP32Sboard have PMS_RX 27 & PMS_TX 25. Jump Uart2 tx from 16 to 18. !6 used by + // Oled. #elif TTGO_TQ #define PMS_RX 13 #define PMS_TX 18 @@ -53,7 +55,7 @@ #define PMS_RX RX #define PMS_TX TX #elif M5STICKCPLUS -#define PMS_RX 36 // provisional for M5StickCPlus board for now +#define PMS_RX 36 // provisional for M5StickCPlus board for now #define PMS_TX 0 #elif M5COREINK #define PMS_RX 13 @@ -86,79 +88,75 @@ #define SENSOR_COMMS SERIALPORT2 // Sensors units definitions (symbol/name) -#define SENSOR_UNITS \ - X(NUNIT, "NUNIT", "NUNIT") \ - X(PM1, "ug/m3", "PM1") \ - X(PM25, "ug/m3", "PM2.5") \ - X(PM4, "ug/m3", "PM4") \ - X(PM10, "ug/m3", "PM10") \ - X(TEMP, "C", "T") \ - X(TEMPK, "K", "T") \ - X(TEMPF, "F", "T") \ - X(HUM, "%", "H") \ - X(CO2, "ppm", "CO2") \ - X(CO2TEMP, "C", "CO2T") \ - X(CO2TEMPK, "K", "CO2TK") \ - X(CO2TEMPF, "F", "CO2TF") \ - X(CO2HUM, "%", "CO2H") \ - X(PRESS, "hPa", "P") \ - X(ALT, "m", "Alt") \ - X(GAS, "Ohm", "Gas") \ - X(CPM, "CPM", "RAD") \ - X(RAD, "uSv/h", "RAD") \ - X(NH3, "ppm", "NH3") \ - X(CO, "ppm", "CO") \ - X(NO2, "ppm", "NO2") \ - X(UCOUNT, "COUNT", "UCOUNT") - +#define SENSOR_UNITS \ + X(NUNIT, "NUNIT", "NUNIT") \ + X(PM1, "ug/m3", "PM1") \ + X(PM25, "ug/m3", "PM2.5") \ + X(PM4, "ug/m3", "PM4") \ + X(PM10, "ug/m3", "PM10") \ + X(TEMP, "C", "T") \ + X(TEMPK, "K", "T") \ + X(TEMPF, "F", "T") \ + X(HUM, "%", "H") \ + X(CO2, "ppm", "CO2") \ + X(CO2TEMP, "C", "CO2T") \ + X(CO2TEMPK, "K", "CO2TK") \ + X(CO2TEMPF, "F", "CO2TF") \ + X(CO2HUM, "%", "CO2H") \ + X(PRESS, "hPa", "P") \ + X(ALT, "m", "Alt") \ + X(GAS, "Ohm", "Gas") \ + X(CPM, "CPM", "RAD") \ + X(RAD, "uSv/h", "RAD") \ + X(NH3, "ppm", "NH3") \ + X(CO, "ppm", "CO") \ + X(NO2, "ppm", "NO2") \ + X(UCOUNT, "COUNT", "UCOUNT") #define X(unit, symbol, name) unit, typedef enum UNIT : size_t { SENSOR_UNITS } UNIT; #undef X // sensors types: 1:PM, 2:CO2, 3:ENV -#define SENSORS_TYPES \ - X(Auto, "GENERIC", 1) \ - X(SGCJA5, "GCJA5", 1) \ - X(SSPS30, "SPS30", 1) \ - X(SDS011, "SDS011", 1) \ - X(SMHZ19, "MHZ19", 2) \ - X(SCM1106, "CM1106", 2) \ - X(SAIRS8, "SAIRS8", 2) \ - X(IKEAVK, "IKEAVK",1) \ - X(SSCD30, "SCD30", 2) \ - X(SSCD4X, "SCD4X", 2) \ - X(SSEN5X, "SEN5X", 1) \ - X(SSHT31, "SHT31", 3) \ - X(SBME280, "BME280", 3) \ - X(SBMP280, "BMP280", 3) \ - X(SBME680, "BME680", 3) \ - X(SAHTXX, "AHTXX", 3) \ - X(SAM232X, "AM232X", 3) \ - X(SDHTX, "DHTX", 3) \ - X(SDFRCO, "DFRCO", 3) \ - X(SDFRNH3, "DFRNH3", 3) \ - X(SDFRNO2, "DFRNO2", 3) \ - X(SCAJOE, "CAJOE", 3) \ - X(SCOUNT, "SCOUNT", 3) +#define SENSORS_TYPES \ + X(Auto, "GENERIC", 1) \ + X(SGCJA5, "GCJA5", 1) \ + X(SSPS30, "SPS30", 1) \ + X(SDS011, "SDS011", 1) \ + X(SMHZ19, "MHZ19", 2) \ + X(SCM1106, "CM1106", 2) \ + X(SAIRS8, "SAIRS8", 2) \ + X(IKEAVK, "IKEAVK", 1) \ + X(SSCD30, "SCD30", 2) \ + X(SSCD4X, "SCD4X", 2) \ + X(SSEN5X, "SEN5X", 1) \ + X(SSHT31, "SHT31", 3) \ + X(SBME280, "BME280", 3) \ + X(SBMP280, "BMP280", 3) \ + X(SBME680, "BME680", 3) \ + X(SAHTXX, "AHTXX", 3) \ + X(SAM232X, "AM232X", 3) \ + X(SDHTX, "DHTX", 3) \ + X(SDFRCO, "DFRCO", 3) \ + X(SDFRNH3, "DFRNH3", 3) \ + X(SDFRNO2, "DFRNO2", 3) \ + X(SCAJOE, "CAJOE", 3) \ + X(SCOUNT, "SCOUNT", 3) #define X(utype, uname, umaintype) utype, typedef enum SENSORS : size_t { SENSORS_TYPES } SENSORS; // backward compatibility #undef X // MAIN SENSOR GROUPS TYPE -enum class SensorGroup { SENSOR_NONE, - SENSOR_PM, - SENSOR_CO2, - SENSOR_ENV, - SENSOR_RAD // CAJOE_GEIGER - }; -// TEMPERATURE UNITS -enum class TEMPUNIT { - CELSIUS, - FAHRENHEIT, - KELVIN +enum class SensorGroup { + SENSOR_NONE, + SENSOR_PM, + SENSOR_CO2, + SENSOR_ENV, + SENSOR_RAD // CAJOE_GEIGER }; +// TEMPERATURE UNITS +enum class TEMPUNIT { CELSIUS, FAHRENHEIT, KELVIN }; typedef void (*errorCbFn)(const char *msg); typedef void (*voidCbFn)(); @@ -166,355 +164,352 @@ typedef void (*voidCbFn)(); /** * @brief CanAirIO Sensors Manager main class. * @authors \@hpsaturn and CanAir.IO contributers -*/ + */ class Sensors { - public: - /// SPS30 values. Only for Sensirion SPS30 sensor. - struct sps_values val; - - /// Debug mode for increase verbose. - bool devmode; + public: + /// SPS30 values. Only for Sensirion SPS30 sensor. + struct sps_values val; - /// Initial sample time for all sensors - int sample_time = 10; + /// Debug mode for increase verbose. + bool devmode; - /// Temperature offset (for final temp output) - float toffset = 0.0; + /// Initial sample time for all sensors + int sample_time = 10; - /// Altitud compensation variable - float altoffset = 0.0; + /// Temperature offset (for final temp output) + float toffset = 0.0; - /// Sea level pressure (hPa) - float sealevel = 1013.25; + /// Altitud compensation variable + float altoffset = 0.0; - /// Altitud hpa calculation - float hpa = 0.0; + /// Sea level pressure (hPa) + float sealevel = 1013.25; - /// Sensirion library - SPS30 sps30; + /// Altitud hpa calculation + float hpa = 0.0; - /// only detect i2c sensors flag - bool i2conly; + /// Sensirion library + SPS30 sps30; - /***************************************** - * I2C sensors: - ****************************************/ + /// only detect i2c sensors flag + bool i2conly; - /// AM2320 object (Humidity and temperature) - AM232X am2320; - /// BME280 object (Humidity, Pressure, Altitude and Temperature) - Adafruit_BME280 bme280; - /// BMP280 object (Humidity, Pressure, Altitude and Temperature) - Adafruit_BMP280 bmp280; - /// BME680 object (Humidity, Gas, IAQ, Pressure, Altitude and Temperature) - Adafruit_BME680 bme680; - /// AHTXX sensors object - AHTxx aht10; - /// SHT31 object (Humidity and temperature) - Adafruit_SHT31 sht31; + /***************************************** + * I2C sensors: + ****************************************/ - #ifdef DHT11_ENABLED - /// @deprecated DHT sensor variable - float dhthumi, dhttemp; - #endif - /// Mhz19 object sensor - MHZ19 mhz19; - /// SCD30 object sensor - Adafruit_SCD30 scd30; - /// CM1106 UART main object sensor - CM1106_UART *cm1106; - /// CM1106 UART main variable - CM1106_sensor cm1106sensor; - /// CM1106 UART calibration object - CM1106_ABC abc; - /// Panasonic SN-GCJA5 object sensor - SFE_PARTICLE_SENSOR pmGCJA5; - /// SenseAir S8 CO2 object sensor - S8_UART *s8; - /// SenseAir S8 CO2 object sensor - S8_sensor s8sensor; - /// SCD4x object sensor - SensirionI2CScd4x scd4x; - // SEN5x sensor PM - SensirionI2CSen5x sen5x; - /// IKEA Vindriktn object sensor - PM1006 *pm1006; - /// DFRobot gravity CO object sensor addr 0x78 - DFRobot_GAS_I2C dfrCO; - /// DFRobot gravity NH3 object sensor addr 0x7A - DFRobot_GAS_I2C dfrNH3; - /// DFRobot gravity NO2 object sensor add 0x7B - DFRobot_GAS_I2C dfrNO2; - /// Geiger CAJOE object sensor - GEIGER *rad; + /// AM2320 object (Humidity and temperature) + AM232X am2320; + /// BME280 object (Humidity, Pressure, Altitude and Temperature) + Adafruit_BME280 bme280; + /// BMP280 object (Humidity, Pressure, Altitude and Temperature) + Adafruit_BMP280 bmp280; + /// BME680 object (Humidity, Gas, IAQ, Pressure, Altitude and Temperature) + Adafruit_BME680 bme680; + /// AHTXX sensors object + AHTxx aht10; + /// SHT31 object (Humidity and temperature) + Adafruit_SHT31 sht31; +#ifdef DHT11_ENABLED + /// @deprecated DHT sensor variable + float dhthumi, dhttemp; +#endif + /// Mhz19 object sensor + MHZ19 mhz19; + /// SCD30 object sensor + Adafruit_SCD30 scd30; + /// CM1106 UART main object sensor + CM1106_UART *cm1106; + /// CM1106 UART main variable + CM1106_sensor cm1106sensor; + /// CM1106 UART calibration object + CM1106_ABC abc; + /// Panasonic SN-GCJA5 object sensor + SFE_PARTICLE_SENSOR pmGCJA5; + /// SenseAir S8 CO2 object sensor + S8_UART *s8; + /// SenseAir S8 CO2 object sensor + S8_sensor s8sensor; + /// SCD4x object sensor + SensirionI2CScd4x scd4x; + // SEN5x sensor PM + SensirionI2CSen5x sen5x; + /// IKEA Vindriktn object sensor + PM1006 *pm1006; + /// DFRobot gravity CO object sensor addr 0x78 + DFRobot_GAS_I2C dfrCO; + /// DFRobot gravity NH3 object sensor addr 0x7A + DFRobot_GAS_I2C dfrNH3; + /// DFRobot gravity NO2 object sensor add 0x7B + DFRobot_GAS_I2C dfrNO2; + /// Geiger CAJOE object sensor + GEIGER *rad; + void init(u_int pms_type = 0, int pms_rx = PMS_RX, int pms_tx = PMS_TX); - void init(u_int pms_type = 0, int pms_rx = PMS_RX, int pms_tx = PMS_TX); + void loop(); - void loop(); + bool readAllSensors(); - bool readAllSensors(); + bool isDataReady(); - bool isDataReady(); + void setSampleTime(int seconds); - void setSampleTime(int seconds); + void setOnDataCallBack(voidCbFn cb); - void setOnDataCallBack(voidCbFn cb); + void setOnErrorCallBack(errorCbFn cb); - void setOnErrorCallBack(errorCbFn cb); + void setTemperatureUnit(TEMPUNIT tunit); - void setTemperatureUnit(TEMPUNIT tunit); + void setDebugMode(bool enable); - void setDebugMode(bool enable); + bool isUARTSensorConfigured(); - bool isUARTSensorConfigured(); + int getUARTDeviceTypeSelected(); - int getUARTDeviceTypeSelected(); + uint16_t getPM1(); - uint16_t getPM1(); + uint16_t getPM25(); - uint16_t getPM25(); + uint16_t getPM4(); - uint16_t getPM4(); + uint16_t getPM10(); - uint16_t getPM10(); + uint16_t getCO2(); - uint16_t getCO2(); + float getCO2humi(); - float getCO2humi(); + float getCO2temp(); - float getCO2temp(); + float getTemperature(); - float getTemperature(); + float getHumidity(); - float getHumidity(); + float getPressure(); - float getPressure(); + float getAltitude(); - float getAltitude(); + float getGas(); - float getGas(); - - float getNH3(); - - float getCO(); - - float getNO2(); + float getNH3(); - void enableGeigerSensor(int gpio); + float getCO(); - uint32_t getGeigerCPM(void); + float getNO2(); - float getGeigerMicroSievertHour(void); + void enableGeigerSensor(int gpio); - void setTempOffset(float offset); + uint32_t getGeigerCPM(void); - void setCO2AltitudeOffset(float altitude); + float getGeigerMicroSievertHour(void); - void setSeaLevelPressure(float hpa); - - void setCO2RecalibrationFactor(int ppmValue); + void setTempOffset(float offset); - void detectI2COnly(bool enable); + void setCO2AltitudeOffset(float altitude); - String getLibraryVersion(); + void setSeaLevelPressure(float hpa); - int16_t getLibraryRevision(); + void setCO2RecalibrationFactor(int ppmValue); - bool isSensorRegistered(SENSORS sensor); + void detectI2COnly(bool enable); - uint8_t *getSensorsRegistered(); + String getLibraryVersion(); - uint8_t getSensorsRegisteredCount(); + int16_t getLibraryRevision(); - String getSensorName(SENSORS sensor); + bool isSensorRegistered(SENSORS sensor); - SensorGroup getSensorGroup(SENSORS sensor); + uint8_t *getSensorsRegistered(); - uint8_t getUnitsRegisteredCount(); + uint8_t getSensorsRegisteredCount(); - bool isUnitRegistered(UNIT unit); + String getSensorName(SENSORS sensor); - String getUnitName(UNIT unit); + SensorGroup getSensorGroup(SENSORS sensor); - String getUnitSymbol(UNIT unit); + uint8_t getUnitsRegisteredCount(); - UNIT getNextUnit(); + bool isUnitRegistered(UNIT unit); - void resetUnitsRegister(); + String getUnitName(UNIT unit); - void resetSensorsRegister(); + String getUnitSymbol(UNIT unit); - void resetNextUnit(); + UNIT getNextUnit(); - void resetAllVariables(); + void resetUnitsRegister(); - float getUnitValue(UNIT unit); + void resetSensorsRegister(); - void printUnitsRegistered(bool debug = false); + void resetNextUnit(); - void printSensorsRegistered(bool debug = false); + void resetAllVariables(); - private: + float getUnitValue(UNIT unit); - #ifdef DHT11_ENABLED - /// DHT library - uint32_t delayMS; - #endif - /// For UART sensors (autodetected available serial) - Stream *_serial; - /// Callback on some sensors error. - errorCbFn _onErrorCb = nullptr; - /// Callback when sensor data is ready. - voidCbFn _onDataCb = nullptr; + void printUnitsRegistered(bool debug = false); - int dev_uart_type = -1; + void printSensorsRegistered(bool debug = false); + + private: +#ifdef DHT11_ENABLED + /// DHT library + uint32_t delayMS; +#endif + /// For UART sensors (autodetected available serial) + Stream *_serial; + /// Callback on some sensors error. + errorCbFn _onErrorCb = nullptr; + /// Callback when sensor data is ready. + voidCbFn _onDataCb = nullptr; - bool dataReady; + int dev_uart_type = -1; - bool readAllComplete = false; + bool dataReady; - uint8_t sensors_registered_count; + bool readAllComplete = false; - uint8_t units_registered_count; + uint8_t sensors_registered_count; - uint8_t current_unit = 0; + uint8_t units_registered_count; - uint16_t pm1; // PM1 - uint16_t pm25; // PM2.5 - uint16_t pm4; // PM4 - uint16_t pm10; // PM10 + uint8_t current_unit = 0; - float humi = 0.0; // % Relative humidity - float temp = 0.0; // Temperature (°C) - float pres = 0.0; // Pressure - float alt = 0.0; - float gas = 0.0; // + uint16_t pm1; // PM1 + uint16_t pm25; // PM2.5 + uint16_t pm4; // PM4 + uint16_t pm10; // PM10 - // temperature unit (C,K,F) - TEMPUNIT temp_unit = TEMPUNIT::CELSIUS; - - uint16_t CO2Val; // CO2 in ppm - float CO2humi = 0.0; // humidity of CO2 sensor - float CO2temp = 0.0; // temperature of CO2 sensor + float humi = 0.0; // % Relative humidity + float temp = 0.0; // Temperature (°C) + float pres = 0.0; // Pressure + float alt = 0.0; + float gas = 0.0; // - float nh3; // Amonium in ppm - float co; // Carbon monoxide in ppm - float no2; // Nitrogen dioxide in ppm - - void am2320Init(); - void am2320Read(); + // temperature unit (C,K,F) + TEMPUNIT temp_unit = TEMPUNIT::CELSIUS; - void bme280Init(); - void bme280Read(); + uint16_t CO2Val; // CO2 in ppm + float CO2humi = 0.0; // humidity of CO2 sensor + float CO2temp = 0.0; // temperature of CO2 sensor - void bmp280Init(); - void bmp280Read(); + float nh3; // Amonium in ppm + float co; // Carbon monoxide in ppm + float no2; // Nitrogen dioxide in ppm - void bme680Init(); - void bme680Read(); + void am2320Init(); + void am2320Read(); - void aht10Init(); - void aht10Read(); + void bme280Init(); + void bme280Read(); - void sht31Init(); - void sht31Read(); + void bmp280Init(); + void bmp280Read(); - void CO2scd30Init(); - void CO2scd30Read(); - void setSCD30TempOffset(float offset); - void setSCD30AltitudeOffset(float offset); - void CO2correctionAlt(); - float hpaCalculation(float altitude); + void bme680Init(); + void bme680Read(); - void CO2scd4xInit(); - void CO2scd4xRead(); - void setSCD4xTempOffset(float offset); - void setSCD4xAltitudeOffset(float offset); + void aht10Init(); + void aht10Read(); - void sen5xInit(); - void sen5xRead(); - void setsen5xTempOffset(float offset); + void sht31Init(); + void sht31Read(); - void GCJA5Init(); - void GCJA5Read(); - - #ifdef DHT11_ENABLED - void dhtInit(); - void dhtRead(); - bool dhtIsReady(float *temperature, float *humidity); - #endif + void CO2scd30Init(); + void CO2scd30Read(); + void setSCD30TempOffset(float offset); + void setSCD30AltitudeOffset(float offset); + void CO2correctionAlt(); + float hpaCalculation(float altitude); + + void CO2scd4xInit(); + void CO2scd4xRead(); + void setSCD4xTempOffset(float offset); + void setSCD4xAltitudeOffset(float offset); + + void sen5xInit(); + void sen5xRead(); + void setsen5xTempOffset(float offset); + + void GCJA5Init(); + void GCJA5Read(); + +#ifdef DHT11_ENABLED + void dhtInit(); + void dhtRead(); + bool dhtIsReady(float *temperature, float *humidity); +#endif - void DFRobotNH3Init(); - void DFRobotNH3Read(); - void DFRobotCOInit(); - void DFRobotCORead(); - void DFRobotNO2Init(); - void DFRobotNO2Read(); + void DFRobotNH3Init(); + void DFRobotNH3Read(); + void DFRobotCOInit(); + void DFRobotCORead(); + void DFRobotNO2Init(); + void DFRobotNO2Read(); - // UART sensors methods: + // UART sensors methods: - bool sensorSerialInit(u_int pms_type, int rx, int tx); - bool pmSensorAutoDetect(u_int pms_type); - bool pmSensorRead(); - bool pmGenericRead(); - bool pmGCJA5Read(); - bool pmSDS011Read(); - bool pm1006Read(); - bool CO2Mhz19Read(); - bool CO2CM1106Read(); - bool CO2Mhz19Init(); - bool CO2CM1106Init(); - bool senseAirS8Init(); - bool senseAirS8Read(); - bool PM1006Init(); + bool sensorSerialInit(u_int pms_type, int rx, int tx); + bool pmSensorAutoDetect(u_int pms_type); + bool pmSensorRead(); + bool pmGenericRead(); + bool pmGCJA5Read(); + bool pmSDS011Read(); + bool pm1006Read(); + bool CO2Mhz19Read(); + bool CO2CM1106Read(); + bool CO2Mhz19Init(); + bool CO2CM1106Init(); + bool senseAirS8Init(); + bool senseAirS8Read(); + bool PM1006Init(); - bool sps30I2CInit(); - bool sps30UARTInit(); - bool sps30Read(); - bool sps30tests(); - void sps30ErrToMess(char *mess, uint8_t r); - void sps30Errorloop(char *mess, uint8_t r); - void sps30DeviceInfo(); + bool sps30I2CInit(); + bool sps30UARTInit(); + bool sps30Read(); + bool sps30tests(); + void sps30ErrToMess(char *mess, uint8_t r); + void sps30Errorloop(char *mess, uint8_t r); + void sps30DeviceInfo(); - void geigerRead(); + void geigerRead(); - void onSensorError(const char *msg); + void onSensorError(const char *msg); - void startI2C(); + void startI2C(); - void enableWire1(); + void enableWire1(); - void disableWire1(); + void disableWire1(); - bool serialInit(u_int pms_type, unsigned long speed_baud, int pms_rx, int pms_tx); + bool serialInit(u_int pms_type, unsigned long speed_baud, int pms_rx, int pms_tx); - String hwSerialRead(unsigned int lenght_buffer); + String hwSerialRead(unsigned int lenght_buffer); - void restart(); // restart serial (it isn't works sometimes) + void restart(); // restart serial (it isn't works sometimes) - void DEBUG(const char *text, const char *textb = ""); + void DEBUG(const char *text, const char *textb = ""); - void printValues(); + void printValues(); - void printHumTemp(); + void printHumTemp(); - void tempRegister(bool isCO2temp); + void tempRegister(bool isCO2temp); - void sensorRegister(SENSORS sensor); + void sensorRegister(SENSORS sensor); - void sensorAnnounce(SENSORS sensor); + void sensorAnnounce(SENSORS sensor); - void unitRegister(UNIT unit); + void unitRegister(UNIT unit); - uint8_t *getUnitsRegistered(); + uint8_t *getUnitsRegistered(); // @todo use DEBUG_ESP_PORT ? #ifdef WM_DEBUG_PORT - Stream &_debugPort = WM_DEBUG_PORT; + Stream &_debugPort = WM_DEBUG_PORT; #else - Stream &_debugPort = Serial; // debug output stream ref + Stream &_debugPort = Serial; // debug output stream ref #endif }; @@ -523,4 +518,3 @@ extern Sensors sensors; #endif #endif - diff --git a/src/drivers/MovingSum.h b/src/drivers/MovingSum.h index 62cfd1c9..6554f4e2 100644 --- a/src/drivers/MovingSum.h +++ b/src/drivers/MovingSum.h @@ -7,45 +7,41 @@ #ifndef MOVING_SUM_H #define MOVING_SUM_H -#define DEFAULT_FILTER_LENGTH 8 // default length of the filter +#define DEFAULT_FILTER_LENGTH 8 // default length of the filter // ---------------------------------------------------------------------------------------------------------------------------------------- // template types are: , // // : should be an integer type large enough to fit the current sample variable -// : must be large enough to contain the sum of filter_length samples, each of type -// +// : must be large enough to contain the sum of filter_length samples, each of type +// +// // example: MovingSum adc // MovingSum adc // MovingSum adc // ---------------------------------------------------------------------------------------------------------------------------------------- -template -class MovingSum -{ - -public: - - MovingSum(unsigned short _filter_length=DEFAULT_FILTER_LENGTH); - ~MovingSum(); - - void add(MA_dt x); - void clear(void); - MA_dt* getData(void); - MA_st getCurrentSum(void) const; - unsigned short getFilterLength(void) const; - unsigned short getCurrentFilterLength(void) const; - -private: - - MA_st sum; // sum of current samples - MA_dt *data; // vector with raw data - unsigned short index; // index of current sample - unsigned short filter_length; // length of the filter - bool filter_complete; // true when there are filter_length samples - - void init(); - +template +class MovingSum { + public: + MovingSum(unsigned short _filter_length = DEFAULT_FILTER_LENGTH); + ~MovingSum(); + + void add(MA_dt x); + void clear(void); + MA_dt* getData(void); + MA_st getCurrentSum(void) const; + unsigned short getFilterLength(void) const; + unsigned short getCurrentFilterLength(void) const; + + private: + MA_st sum; // sum of current samples + MA_dt* data; // vector with raw data + unsigned short index; // index of current sample + unsigned short filter_length; // length of the filter + bool filter_complete; // true when there are filter_length samples + + void init(); }; // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -53,11 +49,10 @@ class MovingSum // ---------------------------------------------------------------------------------------------------------------------------------------- template -MovingSum::MovingSum(unsigned short _filter_length) -{ - filter_length = _filter_length; +MovingSum::MovingSum(unsigned short _filter_length) { + filter_length = _filter_length; - init(); + init(); } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -65,9 +60,8 @@ MovingSum::MovingSum(unsigned short _filter_length) // ---------------------------------------------------------------------------------------------------------------------------------------- template -MovingSum::~MovingSum() -{ - delete[] data; +MovingSum::~MovingSum() { + delete[] data; } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -75,15 +69,14 @@ MovingSum::~MovingSum() // ---------------------------------------------------------------------------------------------------------------------------------------- template -void MovingSum::init(void) -{ - sum = 0; - index = -1; - filter_complete = false; +void MovingSum::init(void) { + sum = 0; + index = -1; + filter_complete = false; - data = new MA_dt[filter_length]; + data = new MA_dt[filter_length]; - clear(); + clear(); } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -91,11 +84,10 @@ void MovingSum::init(void) // ---------------------------------------------------------------------------------------------------------------------------------------- template -void MovingSum::clear(void) -{ - for(unsigned short i=0; i::clear(void) { + for (unsigned short i = 0; i < filter_length; i++) { + data[i] = 0; + } } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -103,17 +95,15 @@ void MovingSum::clear(void) // ---------------------------------------------------------------------------------------------------------------------------------------- template -void MovingSum::add(MA_dt x) -{ - index = (index + 1) % filter_length; - sum -= data[index]; - data[index] = x; - sum += x; - - if (!filter_complete && index==filter_length-1){ - filter_complete = true; - } - +void MovingSum::add(MA_dt x) { + index = (index + 1) % filter_length; + sum -= data[index]; + data[index] = x; + sum += x; + + if (!filter_complete && index == filter_length - 1) { + filter_complete = true; + } } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -121,9 +111,8 @@ void MovingSum::add(MA_dt x) // ---------------------------------------------------------------------------------------------------------------------------------------- template -MA_st MovingSum::getCurrentSum(void) const -{ - return sum; +MA_st MovingSum::getCurrentSum(void) const { + return sum; } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -131,9 +120,8 @@ MA_st MovingSum::getCurrentSum(void) const // ---------------------------------------------------------------------------------------------------------------------------------------- template -MA_dt* MovingSum::getData(void) -{ - return data; +MA_dt* MovingSum::getData(void) { + return data; } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -141,9 +129,8 @@ MA_dt* MovingSum::getData(void) // ---------------------------------------------------------------------------------------------------------------------------------------- template -unsigned short MovingSum::getFilterLength(void) const -{ - return filter_length; +unsigned short MovingSum::getFilterLength(void) const { + return filter_length; } // ---------------------------------------------------------------------------------------------------------------------------------------- @@ -151,9 +138,8 @@ unsigned short MovingSum::getFilterLength(void) const // ---------------------------------------------------------------------------------------------------------------------------------------- template -unsigned short MovingSum::getCurrentFilterLength(void) const -{ - return filter_complete ? filter_length : (index+1); +unsigned short MovingSum::getCurrentFilterLength(void) const { + return filter_complete ? filter_length : (index + 1); } #endif diff --git a/src/drivers/geiger.cpp b/src/drivers/geiger.cpp index 455af578..a1635198 100644 --- a/src/drivers/geiger.cpp +++ b/src/drivers/geiger.cpp @@ -3,13 +3,14 @@ #ifdef ESP32 hw_timer_t* geiger_timer = NULL; portMUX_TYPE* geiger_timerMux = NULL; -uint16_t tics_cnt = 0U; // tics in 1000ms -uint32_t tics_tot = 0U; // total tics since boot +uint16_t tics_cnt = 0U; // tics in 1000ms +uint32_t tics_tot = 0U; // total tics since boot MovingSum* cajoe_fms; // ######################################################################### // Interrupt routine called on each click from the geiger tube -// WARNING! the ISR is actually called on both the rising and the falling edge even if configure for FALLING or RISING +// WARNING! the ISR is actually called on both the rising and the falling edge even if configure for +// FALLING or RISING void IRAM_ATTR GeigerTicISR() { portENTER_CRITICAL_ISR(geiger_timerMux); @@ -31,7 +32,7 @@ void IRAM_ATTR onGeigerTimer() { // ######################################################################### // Initialize Geiger counter GEIGER::GEIGER(int gpio, bool debug) { -#ifdef ESP32 +#ifdef ESP32 devmode = debug; tics_cnt = 0U; // tics in 1000ms tics_tot = 0U; // total tics since boot @@ -39,10 +40,11 @@ GEIGER::GEIGER(int gpio, bool debug) { geiger_timer = NULL; geiger_timerMux = new portMUX_TYPE(portMUX_INITIALIZER_UNLOCKED); - // moving sum for CAJOE Geiger Counter, configured for 60 samples (1 sample every 1s * 60 samples = 60s) + // moving sum for CAJOE Geiger Counter, configured for 60 samples (1 sample every 1s * 60 samples + // = 60s) cajoe_fms = new MovingSum(GEIGER_BUFSIZE); - Serial.printf("-->[SLIB] Geiger startup on pin\t: %i\r\n",gpio); + Serial.printf("-->[SLIB] Geiger startup on pin\t: %i\r\n", gpio); // attach interrupt routine to the GPI connected to the Geiger counter module pinMode(gpio, INPUT); @@ -75,7 +77,8 @@ bool GEIGER::read() { ready = (tics_len == cajoe_fms->getFilterLength()); // convert CPM (tics in last minute) to uSv/h and put in display buffer for TFT - // moving sum buffer size is 60 (1 sample every 1000 ms * 60 samples): the complete sum cover exactly last 60s + // moving sum buffer size is 60 (1 sample every 1000 ms * 60 samples): the complete sum cover + // exactly last 60s if (ready) { uSvh = getUSvh(); } else { @@ -99,16 +102,12 @@ bool GEIGER::read() { /** * Converts CPM to uSv/h units (J305 tube) -*/ -float GEIGER::getUSvh() { - return float(this->tics_cpm) * J305_CONV_FACTOR; -} + */ +float GEIGER::getUSvh() { return float(this->tics_cpm) * J305_CONV_FACTOR; } /** * Returns CPM -*/ -uint32_t GEIGER::getTics() { - return this->tics_cpm; -} + */ +uint32_t GEIGER::getTics() { return this->tics_cpm; } void GEIGER::clear() { tics_cpm = 0; diff --git a/src/drivers/geiger.h b/src/drivers/geiger.h index 72b5bef0..63593794 100644 --- a/src/drivers/geiger.h +++ b/src/drivers/geiger.h @@ -1,17 +1,20 @@ #include + #include "MovingSum.h" /************************************************************** * GEIGER * ************************************************************/ -#define GEIGER_TIMER 1 // timer0 is already used (at least on TTGO-TDisplay) somewhere ??? -#define GEIGER_BUFSIZE 60 // moving sum buffer size (1 sample every 1s * 60 samples = 60s) -#define J305_CONV_FACTOR 0.008120370 // conversion factor used for conversion from CPM to uSv/h units (J305 tube) +#define GEIGER_TIMER 1 // timer0 is already used (at least on TTGO-TDisplay) somewhere ??? +#define GEIGER_BUFSIZE 60 // moving sum buffer size (1 sample every 1s * 60 samples = 60s) +#define J305_CONV_FACTOR \ + 0.008120370 // conversion factor used for conversion from CPM to uSv/h units (J305 tube) class GEIGER { private: bool devmode = false; + public: uint32_t tics_cpm = 0U; // tics in last 60s float uSvh = 0.0f; @@ -19,7 +22,7 @@ class GEIGER { * @brief Constructor * @param gpio attached pin * @param debug debug mode enable/disable - */ + */ explicit GEIGER(int gpio = -1, bool debug = false); bool read(); void clear(); diff --git a/src/drivers/pm1006.cpp b/src/drivers/pm1006.cpp index 10e0a07a..8bd2e142 100755 --- a/src/drivers/pm1006.cpp +++ b/src/drivers/pm1006.cpp @@ -2,108 +2,102 @@ #define DEFAULT_TIMEOUT 1000 -PM1006::PM1006(Stream &serial, bool debug) -{ - _serial = &serial; - _debug = debug; +PM1006::PM1006(Stream &serial, bool debug) { + _serial = &serial; + _debug = debug; - _state = PM1006_HEADER; - _rxlen = 0; - _index = 0; - memset(_rxbuf, 0, sizeof(_rxbuf)); - memset(_txbuf, 0, sizeof(_txbuf)); - _checksum = 0; + _state = PM1006_HEADER; + _rxlen = 0; + _index = 0; + memset(_rxbuf, 0, sizeof(_rxbuf)); + memset(_txbuf, 0, sizeof(_txbuf)); + _checksum = 0; } -bool PM1006::read_pm25(uint16_t *pm) -{ - uint8_t cmd[] = {0x0B, 0x01}; - if (send_command(2, cmd) && (_rxlen > 4) && (_rxbuf[0] == cmd[0])) { - *pm = (_rxbuf[3] << 8) + _rxbuf[4]; - return true; - } - return false; +bool PM1006::read_pm25(uint16_t *pm) { + uint8_t cmd[] = {0x0B, 0x01}; + if (send_command(2, cmd) && (_rxlen > 4) && (_rxbuf[0] == cmd[0])) { + *pm = (_rxbuf[3] << 8) + _rxbuf[4]; + return true; + } + return false; } // sends a command and waits for response, returns length of response -bool PM1006::send_command(size_t cmd_len, const uint8_t *cmd_data) -{ - // build and send command - int txlen = build_tx(cmd_len, cmd_data); - _serial->write(_txbuf, txlen); +bool PM1006::send_command(size_t cmd_len, const uint8_t *cmd_data) { + // build and send command + int txlen = build_tx(cmd_len, cmd_data); + _serial->write(_txbuf, txlen); - // wait for response - unsigned long start = millis(); - while ((millis() - start) < DEFAULT_TIMEOUT) { - while (_serial->available()) { - char c = _serial->read(); - if (process_rx(c)) { - return true; - } - } - yield(); + // wait for response + unsigned long start = millis(); + while ((millis() - start) < DEFAULT_TIMEOUT) { + while (_serial->available()) { + char c = _serial->read(); + if (process_rx(c)) { + return true; + } } + yield(); + } - // timeout - return false; + // timeout + return false; } // builds a tx buffer, returns length of tx data -int PM1006::build_tx(size_t cmd_len, const uint8_t *cmd_data) -{ - int len = 0; - _txbuf[len++] = 0x11; - _txbuf[len++] = cmd_len; - for (size_t i = 0; i < cmd_len; i++) { - _txbuf[len++] = cmd_data[i]; - } - uint8_t sum = 0; - for (int i = 0; i < len; i++) { - sum += _txbuf[i]; - } - _txbuf[len++] = (256 - sum) & 0xFF; - return len; +int PM1006::build_tx(size_t cmd_len, const uint8_t *cmd_data) { + int len = 0; + _txbuf[len++] = 0x11; + _txbuf[len++] = cmd_len; + for (size_t i = 0; i < cmd_len; i++) { + _txbuf[len++] = cmd_data[i]; + } + uint8_t sum = 0; + for (int i = 0; i < len; i++) { + sum += _txbuf[i]; + } + _txbuf[len++] = (256 - sum) & 0xFF; + return len; } // processes one rx character, returns true if a valid frame was found -bool PM1006::process_rx(uint8_t c) -{ - switch (_state) { +bool PM1006::process_rx(uint8_t c) { + switch (_state) { case PM1006_HEADER: - _checksum = c; - if (c == 0x16) { - _state = PM1006_LENGTH; - } - break; + _checksum = c; + if (c == 0x16) { + _state = PM1006_LENGTH; + } + break; case PM1006_LENGTH: - _checksum += c; - if (c <= sizeof(_rxbuf)) { - _rxlen = c; - _index = 0; - _state = (_rxlen > 0) ? PM1006_DATA : PM1006_CHECK; - } else { - _state = PM1006_HEADER; - } - break; + _checksum += c; + if (c <= sizeof(_rxbuf)) { + _rxlen = c; + _index = 0; + _state = (_rxlen > 0) ? PM1006_DATA : PM1006_CHECK; + } else { + _state = PM1006_HEADER; + } + break; case PM1006_DATA: - _checksum += c; - _rxbuf[_index++] = c; - if (_index == _rxlen) { - _state = PM1006_CHECK; - } - break; + _checksum += c; + _rxbuf[_index++] = c; + if (_index == _rxlen) { + _state = PM1006_CHECK; + } + break; case PM1006_CHECK: - _checksum += c; - _state = PM1006_HEADER; - return (_checksum == 0); + _checksum += c; + _state = PM1006_HEADER; + return (_checksum == 0); default: - _state = PM1006_HEADER; - break; - } - return false; + _state = PM1006_HEADER; + break; + } + return false; } - diff --git a/src/drivers/pm1006.h b/src/drivers/pm1006.h index e177e4a4..0aa8f8e7 100755 --- a/src/drivers/pm1006.h +++ b/src/drivers/pm1006.h @@ -3,47 +3,40 @@ #include #include -typedef enum { - PM1006_HEADER, - PM1006_LENGTH, - PM1006_DATA, - PM1006_CHECK -} pm1006_state_t; +typedef enum { PM1006_HEADER, PM1006_LENGTH, PM1006_DATA, PM1006_CHECK } pm1006_state_t; class PM1006 { - -private: - Stream* _serial; - bool _debug; - - pm1006_state_t _state; - size_t _rxlen; - size_t _index; - uint8_t _txbuf[16]; - uint8_t _rxbuf[20]; - uint8_t _checksum; - - bool send_command(size_t cmd_len, const uint8_t *cmd_data); - int build_tx(size_t cmd_len, const uint8_t *cmd_data); - bool process_rx(uint8_t c); - -public: - static const int BIT_RATE = 9600; - - /** - * Constructor. - * - * @param serial the serial port, NOTE: the serial port has to be configured for a bit rate of PM1006::BIT_RATE ! - */ - explicit PM1006(Stream &serial, bool debug = false); - - /** - * Reads the PM2.5 value (plus some other yet unknown parameters) - * - * @param pm the PM2.5 value - * @return true if the value was read successfully - */ - bool read_pm25(uint16_t *pm); - + private: + Stream *_serial; + bool _debug; + + pm1006_state_t _state; + size_t _rxlen; + size_t _index; + uint8_t _txbuf[16]; + uint8_t _rxbuf[20]; + uint8_t _checksum; + + bool send_command(size_t cmd_len, const uint8_t *cmd_data); + int build_tx(size_t cmd_len, const uint8_t *cmd_data); + bool process_rx(uint8_t c); + + public: + static const int BIT_RATE = 9600; + + /** + * Constructor. + * + * @param serial the serial port, NOTE: the serial port has to be configured for a bit rate of + * PM1006::BIT_RATE ! + */ + explicit PM1006(Stream &serial, bool debug = false); + + /** + * Reads the PM2.5 value (plus some other yet unknown parameters) + * + * @param pm the PM2.5 value + * @return true if the value was read successfully + */ + bool read_pm25(uint16_t *pm); }; -