-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensors.cpp
390 lines (346 loc) · 12.1 KB
/
sensors.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#include "sensors.h"
#include "definitions.h"
#include "influx.h"
#ifdef BME280_I2C
#include <Adafruit_BME280.h>
Adafruit_BME280 bme280;
#endif
#ifdef BME680_I2C
#include <bsec.h>
Bsec iaqSensor;
void checkIaqSensorStatus(void);
void saveBsecState(void);
void loadBsecState(void);
const uint8_t bsec_config_iaq[] = {
#include "config/generic_33v_3s_4d/bsec_iaq.txt"
};
#define STATE_SAVE_PERIOD UINT32_C(360 * 60 * 1000) // 360 mins - 4 times a day
#define BSEC_SENSOR_COUNT 10
uint8_t bsecState[BSEC_MAX_STATE_BLOB_SIZE] = {0};
uint16_t stateUpdateCounter = 0;
#endif
#ifdef SCT_013_PIN
#include "EmonLib.h"
EnergyMonitor emon;
#endif
#if defined(MHZ19_RX) && defined(MHZ19_TX)
#define HAS_MHZ19
#include "MHZ19.h"
MHZ19 *mhz19 = new MHZ19(MHZ19_RX, MHZ19_TX);
#endif
#if defined(PZEM_RX) && defined(PZEM_TX)
#define HAS_PZEM
#include <PZEM004Tv30.h>
PZEM004Tv30 pzem(Serial2, 16, 17);
int failCount = 0;
int failLimit = 5;
#endif
#ifdef ADS1115_I2C
#define HAS_ADS1115
#include <Adafruit_ADS1X15.h>
Adafruit_ADS1115 ads1115;
#endif
Point sensors("sensors");
void setupSensors() {
#ifdef BME280_I2C
Serial.println(F("[ BME280 ] has sensor"));
boolean bme280Ok = bme280.begin(0x76, &Wire);
Serial.print(F("[ BME280 ] sensor "));
Serial.print(bme280Ok ? F("") : F("NOT "));
Serial.println(F("OK"));
bme280.setSampling(Adafruit_BME280::MODE_FORCED,
Adafruit_BME280::SAMPLING_X4, // temperature
Adafruit_BME280::SAMPLING_X4, // pressure
Adafruit_BME280::SAMPLING_X4, // humidity
Adafruit_BME280::FILTER_X4,
Adafruit_BME280::STANDBY_MS_0_5);
#endif
#ifdef BME680_I2C
Serial.println(F("[ BME680 ] has sensor"));
iaqSensor.begin(BME680_I2C_ADDR_SECONDARY, Wire);
Serial.printf("[ BME680 ] BSEC library v%d.%d.%d.%d\n",
iaqSensor.version.major, iaqSensor.version.minor,
iaqSensor.version.major_bugfix, iaqSensor.version.minor_bugfix);
checkIaqSensorStatus();
iaqSensor.setConfig(bsec_config_iaq);
checkIaqSensorStatus();
loadBsecState();
checkIaqSensorStatus();
bsec_virtual_sensor_t sensorList[] = {
BSEC_OUTPUT_RAW_TEMPERATURE,
BSEC_OUTPUT_RAW_PRESSURE,
BSEC_OUTPUT_RAW_HUMIDITY,
BSEC_OUTPUT_RAW_GAS,
BSEC_OUTPUT_IAQ,
BSEC_OUTPUT_STATIC_IAQ,
BSEC_OUTPUT_CO2_EQUIVALENT,
BSEC_OUTPUT_BREATH_VOC_EQUIVALENT,
BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_TEMPERATURE,
BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY};
iaqSensor.updateSubscription(sensorList,
sizeof(sensorList) / sizeof(sensorList[0]),
BSEC_SAMPLE_RATE_LP);
checkIaqSensorStatus();
#endif
#ifdef SCT_013_PIN
Serial.println(F("[ SCT013 ] has sensor"));
emon.current(SCT_013_PIN, SCT_013_CALIBRATION);
delay(5000); // Sensor needs to chill after boot or values spike
#endif
#ifdef HAS_MHZ19
mhz19->begin();
mhz19->setAutoCalibration(false); // if outdoors set to true
delay(3000); // apparently fixes a infinite warming issue
Serial.print(F(" [ MH-Z19 ] has sensor, status: "));
Serial.println(mhz19->getStatus());
#endif
#ifdef HAS_PZEM
Serial.print(F(" [ PZEM ] has sensor, address: "));
Serial.println(pzem.readAddress(), HEX);
#endif
#ifdef HAS_ADS1115
ads1115.begin(ADS1115_ADDR);
ads1115.setGain(GAIN_ONE); // 1x gain +/- 4.096V 1 bit = 2mV
#endif
} /* setupSensors */
#ifdef BME680_I2C
void checkIaqSensorStatus(void) {
if (iaqSensor.status != BSEC_OK) {
if (iaqSensor.status < BSEC_OK) {
Serial.print(F("[ BME680 ] BSEC error code: "));
Serial.println(iaqSensor.status);
} else {
Serial.print(F("[ BME680 ] BSEC warning code: "));
Serial.println(iaqSensor.status);
}
}
if (iaqSensor.bme680Status != BME680_OK) {
if (iaqSensor.bme680Status < BME680_OK) {
Serial.print(F("[ BME680 ] BME680 error code: "));
Serial.println(iaqSensor.status);
} else {
Serial.print(F("[ BME680 ] BME680 warning code: "));
Serial.println(iaqSensor.status);
}
}
Serial.println(F("[ BME680 ] sensor OK"));
}
void loadBsecState() {
// TODO maybe we need to run this sensor in 5 minute read intervals
if (config.getBytesLength("bsecState") == 0) {
// No state saved, zero fill
Serial.println("[ BME680 ] Zero filled state");
config.putBytes("bsecState", &bsecState, BSEC_MAX_STATE_BLOB_SIZE);
} else {
stateUpdateCounter = 1;
config.getBytes("bsecState", &bsecState, BSEC_MAX_STATE_BLOB_SIZE);
Serial.printf("[ BME680 ] Loaded state (%i) ",
config.getBytesLength("bsecState"));
for (int i = 0; i < BSEC_MAX_STATE_BLOB_SIZE; i++) {
Serial.printf("%d", bsecState[i]);
}
iaqSensor.setState(bsecState);
Serial.println();
}
}
void saveBsecState() {
Serial.printf("[ BME680 ] counter %d, iaqAccuracy %d\n", stateUpdateCounter,
iaqSensor.iaqAccuracy);
Serial.printf("[ BME680 ] runInStatus %f, staticIaqAccuracy %d\n",
iaqSensor.runInStatus, iaqSensor.staticIaqAccuracy);
Serial.printf("[ BME680 ] iaq %f, staticIaq %f\n", iaqSensor.iaq,
iaqSensor.staticIaq);
if (stateUpdateCounter ==
0) { // if state was zero filled initially (as in, not set)
// Only persist state when calibration completes (maybe never)
if (iaqSensor.iaqAccuracy >= 3) {
stateUpdateCounter++;
iaqSensor.getState(bsecState);
config.putBytes("bsecState", bsecState, BSEC_MAX_STATE_BLOB_SIZE);
}
} else {
// Update every STATE_SAVE_PERIOD milliseconds
if ((stateUpdateCounter * STATE_SAVE_PERIOD) < millis()) {
stateUpdateCounter++;
iaqSensor.getState(bsecState);
config.putBytes("bsecState", bsecState, BSEC_MAX_STATE_BLOB_SIZE);
}
}
}
#endif
double calculateVpd(double temperature, double humidity) {
double e = 2.71828;
/* in pascals */
double SVP = 610.78 * pow(e, (temperature / (temperature + 238.3) * 17.2694));
double vpd = (SVP / 1000) * (1 - humidity / 100); // kPa
return vpd;
}
#ifdef HAS_ADS1115
float calculateTemperatureFromAdc(int adcInput) {
int32_t adcVsum = 0;
int counts = 10;
for (int i = 0; i < counts; i++) {
adcVsum += ads1115.readADC_SingleEnded(adcInput);
}
int16_t adcVal = adcVsum / counts;
float voltage = ads1115.computeVolts(adcVal);
// Calculate the resistance of the thermistor using the voltage divider
// formula
float resistance = (3.3 / voltage - 1) * SERIES_RESISTOR;
// Calculate the temperature in Celsius using the Steinhart-Hart equation
// using B value
float steinhart;
steinhart = resistance / SERIES_RESISTOR; // (R/Ro)
steinhart = log(steinhart); // ln(R/Ro)
steinhart /= THERMISTOR_B; // 1/B * ln(R/Ro)
steinhart += 1.0 / (25 + 273.15); // + (1/To)
steinhart = 1.0 / steinhart; // Invert
float temperature = steinhart - 273.15; // Convert to Celsius
return temperature;
}
#endif
void setSensorsTags() {
sensors.clearTags();
sensors.addTag(F("MAC"), WiFi.macAddress());
sensors.addTag(F("name"), config.getString("name"));
sensors.addTag(F("location"), config.getString("location"));
}
void captureSensorsFields() {
sensors.clearFields();
#ifdef BME280_I2C
bme280.takeForcedMeasurement();
double temperature = bme280.readTemperature();
double pressure = bme280.readPressure() / 100.0F;
double humidity = bme280.readHumidity();
double vpd = calculateVpd(temperature, humidity);
sensors.addField(F("temperature"), temperature);
sensors.addField(F("pressure"), pressure);
sensors.addField(F("humidity"), humidity);
sensors.addField(F("vpd"), vpd);
#endif
#ifdef BME680_I2C
if (iaqSensor.run()) {
Serial.printf(
"Pressure %.2f\nIAQ %.2f\nIAQ "
"acc %d\nTemp %.2f\nrH %.2f\nStaticIAQ %.2f\nco2e %.2f\nbVOCe %.2f\n",
iaqSensor.pressure, iaqSensor.iaq, iaqSensor.iaqAccuracy,
iaqSensor.temperature, iaqSensor.humidity, iaqSensor.staticIaq,
iaqSensor.co2Equivalent, iaqSensor.breathVocEquivalent);
double vpd = calculateVpd(iaqSensor.temperature, iaqSensor.humidity);
Serial.printf("%f, %f, %d\n", iaqSensor.runInStatus, iaqSensor.stabStatus,
iaqSensor.status);
sensors.addField(F("temperature"), iaqSensor.temperature);
sensors.addField(F("pressure"), iaqSensor.pressure / 100.0F);
sensors.addField(F("humidity"), iaqSensor.humidity);
sensors.addField(F("eCO2"), iaqSensor.co2Equivalent);
sensors.addField(F("bVOCe"), iaqSensor.breathVocEquivalent);
sensors.addField(F("vpd"), vpd);
// Good reading about what this field actually represents
// https://community.bosch-sensortec.com/t5/MEMS-sensors-forum/BME680-strange-IAQ-and-CO2-values/m-p/9667/highlight/true#M1505
sensors.addField(F("iaq"), iaqSensor.staticIaq);
saveBsecState();
} else {
checkIaqSensorStatus();
}
#endif
#ifdef SCT_013_PIN
double irms = emon.calcIrms(1480);
sensors.addField(F("irms"), irms);
sensors.addField(F("power"), irms * VOLTAGE);
#endif
#ifdef HAS_MHZ19
measurement_t measurement = mhz19->getMeasurement();
// Only log sane values incase of accidental failures
if (measurement.co2_ppm > 400 && measurement.co2_ppm < 5000) {
sensors.addField(F("co2"), measurement.co2_ppm);
} else {
Serial.printf("[ MHZ19 ] Invalid CO2 reading: %d\n", measurement.co2_ppm);
}
if (measurement.temperature != -1) {
sensors.addField(F("temperature"), (float)measurement.temperature);
} else {
Serial.printf("[ MHZ19 ] Invalid temperature reading: %d\n",
measurement.temperature);
}
#endif
#ifdef HAS_PZEM
// Read the data from the sensor
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
float frequency = pzem.frequency();
float pf = pzem.pf();
// Check if the data is valid
if (isnan(voltage)) {
Serial.println("Error reading voltage");
failCount++;
} else if (isnan(current)) {
Serial.println("Error reading current");
failCount++;
} else if (isnan(power)) {
Serial.println("Error reading power");
failCount++;
} else if (isnan(energy)) {
Serial.println("Error reading energy");
failCount++;
} else if (isnan(frequency)) {
Serial.println("Error reading frequency");
failCount++;
} else if (isnan(pf)) {
Serial.println("Error reading power factor");
failCount++;
} else {
sensors.addField(F("voltage"), voltage);
sensors.addField(F("current"), current);
sensors.addField(F("power"), power);
sensors.addField(F("frequency"), frequency);
sensors.addField(F("pf"), pf);
failCount = 0;
}
if (failCount >= failLimit) {
Serial.println(F("[ PZEM ] failed too often, restarting..."));
Serial.flush();
ESP.restart();
}
#endif
#ifdef HAS_ADS1115
// Strictly in this order!
// ADC0 = CH FLOW
// ADC1 = CH RET
// ADC2 = DHW IN
// ADC3 = DHW OUT
float chFlowTemp = calculateTemperatureFromAdc(0);
float chRetTemp = calculateTemperatureFromAdc(1);
float dhwInTemp = calculateTemperatureFromAdc(2);
float dhwOutTemp = calculateTemperatureFromAdc(3);
Serial.printf("CH Flow: %f\nCH Ret: %f\nDHW In: %f\nDHW Out: %f\n",
chFlowTemp, chRetTemp, dhwInTemp, dhwOutTemp);
sensors.addField(F("ch_flow"), chFlowTemp);
sensors.addField(F("ch_ret"), chRetTemp);
sensors.addField(F("dhw_in"), dhwInTemp);
sensors.addField(F("dhw_out"), dhwOutTemp);
#endif
} /* captureSensorsFields */
/**
* Task: Wait the appropriate period, and log the `sensors` fields.
*
* If logging fails, it will wait progressively smaller portions of time.
*/
void sensorsLoggerTask(void *parameters) {
uint64_t delayTime = SENSORS_LOG_PERIOD;
for (;;) {
Serial.println(F("[ SENSORS ] Logger task"));
captureSensorsFields();
bool logOk = logPoint(sensors);
if (!logOk) {
// On failure, Decrease delay by 25%, 1 sec minimum
delayTime = min(delayTime * 0.75, 1000.0);
} else {
// On success, reset delay to normal
delayTime = SENSORS_LOG_PERIOD;
}
Serial.println(F("[ SENSORS ] Waiting..."));
vTaskDelay(delayTime / portTICK_PERIOD_MS);
}
}