Skip to content
Snippets Groups Projects

Update sensor config from api; CO2 Sensor; Refactor & Tidy-Up

Merged Callum Inglis requested to merge update-sensor-config-from-api into DEV
8 files
+ 228
220
Compare changes
  • Side-by-side
  • Inline
Files
8
@@ -61,7 +61,10 @@ CCS811 co2Sensor; // CO2 Sensor [i2c]
struct pms5003data pmsData; // Struct for PMS Sensor Data
// Reset poll counters
/**
* Reset Poll Counters & Average Values
* Call after a sampling period to clear collected sensor data
*/
void resetCounters() {
pollEventCount = 0;
@@ -71,13 +74,44 @@ void resetCounters() {
}
}
/**
* Add recorded values to the total for this sample period.
* Do not store false/failed/invalid values, e.g. -1 (-300 for temp sensor)
*
* @param newValue New value recorded for this sensor
* @param idx_sensor_count See config.h - Index of sensor value counts, e.g. IDX_PPM10
*/
void addValueToTotal(double newValue, int idx_sensor_count) {
if (newValue == -1 || newValue == -300) { // -300 for temp sensor
return;
}
pollEventCountPerSensor[idx_sensor_count] += 1;
totalValuePerSensor[idx_sensor_count] += newValue;
}
/**
* Get average value for a particular sensor, exluding any error values
*
* @param idx_sensor_count See config.h - Index of sensor value counts, e.g. IDX_PPM10
* @return Average value for this sensor, -1 if no values recorded
*/
double getAverageValue(int idx_sensor_count) {
// Ensure we do not divide by 0 (e.g. 0 valid values)
if (pollEventCountPerSensor[idx_sensor_count] == 0) {
return -1;
}
// Otherwise divide total by number of times we succesfully ampled this value
return totalValuePerSensor[idx_sensor_count] / pollEventCountPerSensor[idx_sensor_count];
}
/**
* Provided sensor data, construct JSON object ready for transmission, Averaged over numSamples
*
* @param messageID Number of messages sent since startup
* @param numSamples Numer of samples averages
* @return DynamicJsonDocument sensorData
* @param messageID Number of messages sent since startup
* @param numSamples Numer of samples averages
* @return sensorData in JSON form
*/
DynamicJsonDocument prepareSensorData(int messageID, int numSamples) {
DynamicJsonDocument doc(2048);
@@ -89,7 +123,7 @@ DynamicJsonDocument prepareSensorData(int messageID, int numSamples) {
JsonObject data = doc.createNestedObject("data");
JsonObject ppm = data.createNestedObject("ppm"); // Particulates
JsonObject ppm = data.createNestedObject("ppm"); // Particulates
ppm["p10"] = getAverageValue(IDX_PPM10);
ppm["p25"] = getAverageValue(IDX_PPM25);
ppm["p100"] = getAverageValue(IDX_PPM100);
@@ -98,52 +132,73 @@ DynamicJsonDocument prepareSensorData(int messageID, int numSamples) {
sht["temperature"] = getAverageValue(IDX_TEMPERATURE);
sht["humidity"] = getAverageValue(IDX_HUMIDITY);
JsonObject co2 = data.createNestedObject("co2"); // Co2
JsonObject co2 = data.createNestedObject("co2"); // CO2
co2["co2"] = getAverageValue(IDX_CO2);
return doc;
}
void packageAndSend() {
if (DEBUG) { // Print average values over this period
Serial.println(""); Serial.print("Avg ppm10: "); Serial.print(getAverageValue(IDX_PPM10)); Serial.print("\t\tAvg ppm25: "); Serial.print(getAverageValue(IDX_PPM25)); Serial.print("\t\tAvg ppm100: "); Serial.print(getAverageValue(IDX_PPM100));
Serial.print("\t\tAvg Temp: "); Serial.print(getAverageValue(IDX_TEMPERATURE)); Serial.print("\t\tAvg Humidity: "); Serial.print(getAverageValue(IDX_HUMIDITY)); Serial.print("\t\tAvg Co2: "); Serial.print(getAverageValue(IDX_CO2));
Serial.print("\t\tChip ID: "); Serial.println(getSensorUID()); Serial.println("");
}
/**
* Add recorded values to the total, do not store false/failed/invalid values, e.g. -1
*/
void addValueToTotal(double newValue, int idx_sensor_count) {
if (newValue == -1) {
return;
// Create JSON Object with our values
DynamicJsonDocument sensorData = prepareSensorData(msgCount, pollEventCount);
// Transmit
if (transmitData(sensorData)) {
resetCounters();
msgCount++;
return; // It all worked, values reset, now record new values
}
pollEventCountPerSensor[idx_sensor_count] += 1;
totalValuePerSensor[idx_sensor_count] += newValue;
}
// Transmission failed, handle re-tries
int numRetries = 1;
waitRandomDelay(TX_RESERVATION_TIME*2); // Introduce random delay to avoid another collision / error
// For as long as we are able to retry, attempt transmission again
while (!transmitData(sensorData) && numRetries < MAX_TRANSMISSION_RETRIES){
numRetries++;
Serial.println("[-] Failed to send packet, retrying. Attempt " + String(numRetries) + " of " + String(MAX_TRANSMISSION_RETRIES) + "\n");
waitRandomDelay(TX_RESERVATION_TIME*2);
}
/**
* Get average value for a particular sensor, exluding any error values
* If there are no valid values, return -1 to indicate error
*/
double getAverageValue(int idx_sensor_count) {
if (pollEventCountPerSensor[idx_sensor_count] == 0) { // Ensure we do not divide by 0 (e.g. 0 valid values)
return -1;
// We were able to transmit after retries, values reset, now record new values
if (numRetries < MAX_TRANSMISSION_RETRIES) {
resetCounters();
msgCount++;
return;
}
// Otherwise divide total by number of times we sampled this value
return totalValuePerSensor[idx_sensor_count] / pollEventCountPerSensor[idx_sensor_count];
// Failed to transmit - Don't Clear Counters, record more values then try to retransmit on next send
Serial.println("[-] Failed to send packet, max retries reached. Aborting");
return;
}
/********************************************
* Setup Sensor *
********************************************/
void setup() {
delay(1000);
delay(2500); // Allow things to warm up
Serial.begin(115200); // Console Debug
Serial.println("\n\n[+] Transmitter Node");
pmsSerial.begin(9600); // Partical Sensor
// Setup Hardware TODO Handle broken sensor!
if (!setupSHT(sht)) { /*while(1);*/ } // Temp/Humidity - Die on Error
if (!setupCO2(co2Sensor)) { /*while(1);*/ }
if (!setupLoRa()) { /*while(1);*/ } // Die on error
Serial.begin(115200);
Serial.print("\n\n[+] Hello, I'm a Transmitter Node. My UID is: "); Serial.print(getSensorUID()); Serial.println("");
// Setup / Init Hardware
pmsSerial.begin(9600); // Partical Sensor Start
if (!setupSHT(sht)) { /*while(1);*/ } // Temp/Humidity
if (!setupCO2(co2Sensor)) { /*while(1);*/ } // Co2
if (!setupLoRa()) { while(1); } // LoRa - Critical Component, die on error
}
/********************************************
* Main *
********************************************/
void loop() {
delay(POLLING_FREQUENCY);
pollEventCount++;
@@ -176,40 +231,8 @@ void loop() {
addValueToTotal(instantPPM25, IDX_PPM25);
addValueToTotal(instantPPM100, IDX_PPM100);
// If we should now transmit
// Transmit once we have reached at least N samples
if (pollEventCount >= TX_AFTER_N_READINGS) {
if (DEBUG) { // Print average values over this period
Serial.println(""); Serial.print("Avg ppm10: "); Serial.print(getAverageValue(IDX_PPM10)); Serial.print("\t\tAvg ppm25: "); Serial.print(getAverageValue(IDX_PPM25)); Serial.print("\t\tAvg ppm100: "); Serial.print(getAverageValue(IDX_PPM100));
Serial.print("\t\tAvg Temp: "); Serial.print(getAverageValue(IDX_TEMPERATURE)); Serial.print("\t\tAvg Humidity: "); Serial.print(getAverageValue(IDX_HUMIDITY)); Serial.print("\t\tAvg Co2: "); Serial.print(getAverageValue(IDX_CO2));
Serial.print("\t\tChip ID: "); Serial.println(getSensorUID()); Serial.println("");
}
// Prepare Data For Send
DynamicJsonDocument sensorData = prepareSensorData(msgCount, pollEventCount);
// Transmit
if (transmitData(sensorData)) {
return; // It all worked, values reset, now record new values
}
// Transmission failed, handle re-tries
int numRetries = 1;
waitRandomDelay(TX_RESERVATION_TIME*2); // Introduce random delay to avoid another collision
while (!transmitData(sensorData) && numRetries < MAX_TRANSMISSION_RETRIES){
numRetries++;
Serial.println("[-] Failed to send packet, retrying. Attempt " + String(numRetries) + " of " + String(MAX_TRANSMISSION_RETRIES) + "\n");
waitRandomDelay(TX_RESERVATION_TIME*2); // Introduce random delay to avoid another collision
}
// We were able to transmit after retries, values reset, now record new values
if (numRetries < MAX_TRANSMISSION_RETRIES) {
return;
}
// Failed to transmit - Don't Clear Counters, record more values then try to retransmit on next send
Serial.println("[-] Failed to send packet, max retries reached. Aborting");
return;
packageAndSend();
}
}
Loading