forked from oseiler2/CO2Monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
331 lines (285 loc) · 11.1 KB
/
Copy pathmain.cpp
File metadata and controls
331 lines (285 loc) · 11.1 KB
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
#include <logging.h>
#include <globals.h>
#include <Arduino.h>
#include <config.h>
#include <WiFi.h>
#include <Wire.h>
#include <i2c.h>
#include <esp_event.h>
#include <esp_err.h>
#include <esp_task_wdt.h>
#include <rom/rtc.h>
#include <configManager.h>
#include <mqtt.h>
#include <sensors.h>
#include <scd30.h>
#include <scd40.h>
#include <sps_30.h>
#include <housekeeping.h>
#include <lcd.h>
#include <trafficLight.h>
#include <neopixel.h>
#include <neopixelMatrix.h>
#include <featherMatrix.h>
#include <hub75.h>
#include <bme680.h>
#include <wifiManager.h>
#include <ota.h>
// Local logging tag
static const char TAG[] = __FILE__;
Model* model;
LCD* lcd;
TrafficLight* trafficLight;
Neopixel* neopixel;
NeopixelMatrix* neopixelMatrix;
FeatherMatrix* featherMatrix;
HUB75* hub75;
SCD30* scd30;
SCD40* scd40;
SPS_30* sps30;
BME680* bme680;
TaskHandle_t sensorsTask;
TaskHandle_t wifiManagerTask;
TaskHandle_t neopixelMatrixTask;
bool hasLEDs = false;
bool hasNeoPixel = false;
bool hasFeatherMatrix = false;
bool hasNeopixelMatrix = false;
bool hasHub75 = false;
const uint32_t debounceDelay = 50;
volatile uint32_t lastBtnDebounceTime = 0;
volatile uint8_t buttonState = 0;
uint8_t oldConfirmedButtonState = 0;
uint32_t lastConfirmedBtnPressedTime = 0;
void ICACHE_RAM_ATTR buttonHandler() {
buttonState = (digitalRead(BTN_1) ? 0 : 1);
lastBtnDebounceTime = millis();
}
void prepareOta() {
if (hasHub75 && hub75) hub75->stopDMA();
if (hasNeopixelMatrix && neopixelMatrix) {
hasNeopixelMatrix = false;
neopixelMatrix->stop();
}
}
void updateMessage(char const* msg) {
if (lcd) {
lcd->updateMessage(msg);
}
}
void setPriorityMessage(char const* msg) {
if (lcd) {
lcd->setPriorityMessage(msg);
}
}
void clearPriorityMessage() {
if (lcd) {
lcd->clearPriorityMessage();
}
}
void modelUpdatedEvt(uint16_t mask, TrafficLightStatus oldStatus, TrafficLightStatus newStatus) {
if (lcd) lcd->update(mask, oldStatus, newStatus);
if (hasLEDs && trafficLight) trafficLight->update(mask, oldStatus, newStatus);
if (hasNeoPixel && neopixel) neopixel->update(mask, oldStatus, newStatus);
if (hasFeatherMatrix && featherMatrix) featherMatrix->update(mask, oldStatus, newStatus);
if (hasNeopixelMatrix && neopixelMatrix) neopixelMatrix->update(mask, oldStatus, newStatus);
if (hasHub75 && hub75) hub75->update(mask, oldStatus, newStatus);
if ((mask & M_PRESSURE) && I2C::scd40Present() && scd40) scd40->setAmbientPressure(model->getPressure());
if ((mask & M_PRESSURE) && I2C::scd30Present() && scd30) scd30->setAmbientPressure(model->getPressure());
if ((mask & ~M_CONFIG_CHANGED) != M_NONE) {
char buf[8];
DynamicJsonDocument* doc = new DynamicJsonDocument(512);
if (mask & M_CO2) (*doc)["co2"] = model->getCo2();
if (mask & M_TEMPERATURE) {
sprintf(buf, "%.1f", model->getTemperature());
(*doc)["temperature"] = buf;
}
if (mask & M_HUMIDITY) {
sprintf(buf, "%.1f", model->getHumidity());
(*doc)["humidity"] = buf;
}
if (mask & M_PRESSURE) (*doc)["pressure"] = model->getPressure();
if (mask & M_IAQ) (*doc)["iaq"] = model->getIAQ();
if (mask & M_PM0_5) (*doc)["pm0.5"] = model->getPM0_5();
if (mask & M_PM1_0) (*doc)["pm1"] = model->getPM1();
if (mask & M_PM2_5) (*doc)["pm2.5"] = model->getPM2_5();
if (mask & M_PM4) (*doc)["pm4"] = model->getPM4();
if (mask & M_PM10) (*doc)["pm10"] = model->getPM10();
mqtt::publishSensors(doc);
}
}
void configChanged() {
model->configurationChanged();
}
void calibrateCo2SensorCallback(uint16_t co2Reference) {
ESP_LOGI(TAG, "Starting calibration");
if (lcd) lcd->setPriorityMessage("Starting calibration");
if (I2C::scd30Present() && scd30) scd30->calibrateScd30ToReference(co2Reference);
if (I2C::scd40Present() && scd40) scd40->calibrateScd40ToReference(co2Reference);
vTaskDelay(pdMS_TO_TICKS(200));
if (lcd) lcd->clearPriorityMessage();
}
void setTemperatureOffsetCallback(float temperatureOffset) {
if (I2C::scd30Present() && scd30) scd30->setTemperatureOffset(temperatureOffset);
if (I2C::scd40Present() && scd40) scd40->setTemperatureOffset(temperatureOffset);
}
float getTemperatureOffsetCallback() {
if (I2C::scd30Present() && scd30) return scd30->getTemperatureOffset();
if (I2C::scd40Present() && scd40) return scd40->getTemperatureOffset();
return NaN;
}
uint32_t getSPS30AutoCleanInterval() {
if (I2C::sps30Present && sps30) return sps30->getAutoCleanInterval();
return 0;
}
boolean setSPS30AutoCleanInterval(uint32_t intervalInSeconds) {
if (I2C::sps30Present && sps30) return sps30->setAutoCleanInterval(intervalInSeconds);
return false;
}
boolean cleanSPS30() {
if (I2C::sps30Present && sps30) return sps30->clean();
return false;
}
uint8_t getSPS30Status() {
if (I2C::sps30Present && sps30) return sps30->getStatus();
return false;
}
void logCoreInfo() {
esp_chip_info_t chip_info;
esp_chip_info(&chip_info);
ESP_LOGI(TAG,
"This is ESP32 chip with %d CPU cores, WiFi%s%s, silicon revision "
"%d, %dMB %s Flash",
chip_info.cores,
(chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
(chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "",
chip_info.revision, spi_flash_get_chip_size() / (1024 * 1024),
(chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded"
: "external");
ESP_LOGI(TAG, "Internal Total heap %d, internal Free Heap %d",
ESP.getHeapSize(), ESP.getFreeHeap());
#ifdef BOARD_HAS_PSRAM
ESP_LOGI(TAG, "SPIRam Total heap %d, SPIRam Free Heap %d",
ESP.getPsramSize(), ESP.getFreePsram());
#endif
ESP_LOGI(TAG, "ChipRevision %d, Cpu Freq %d, SDK Version %s",
ESP.getChipRevision(), ESP.getCpuFreqMHz(), ESP.getSdkVersion());
ESP_LOGI(TAG, "Flash Size %d, Flash Speed %d", ESP.getFlashChipSize(),
ESP.getFlashChipSpeed());
}
void setup() {
esp_task_wdt_init(20, true);
if (LED_PIN >= 0) {
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
}
pinMode(BTN_1, INPUT_PULLUP);
Serial.begin(115200);
esp_log_set_vprintf(logging::logger);
esp_log_level_set("*", ESP_LOG_VERBOSE);
ESP_LOGI(TAG, "CO2 Monitor v%s. Built from %s @ %s", APP_VERSION, SRC_REVISION, BUILD_TIMESTAMP);
model = new Model(modelUpdatedEvt);
logCoreInfo();
RESET_REASON resetReason = rtc_get_reset_reason(0);
ESP_ERROR_CHECK(esp_event_loop_create_default());
ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, WifiManager::eventHandler, NULL, NULL));
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, WifiManager::eventHandler, NULL, NULL));
setupConfigManager();
if (!loadConfiguration(config)) {
getDefaultConfiguration(config);
saveConfiguration(config);
}
logConfiguration(config);
WifiManager::setupWifiManager("CO2-Monitor", getConfigParameters(), false, true,
updateMessage, setPriorityMessage, clearPriorityMessage, configChanged);
hasLEDs = (config.greenLed != 0 && config.yellowLed != 0 && config.redLed != 0);
hasNeoPixel = (config.neopixelData != 0 && config.neopixelNumber != 0);
hasFeatherMatrix = (config.featherMatrixClock != 0 && config.featherMatrixData != 0);
hasNeopixelMatrix = (config.neopixelMatrixData != 0 && config.matrixColumns != 0 && config.matrixRows != 0);
hasHub75 = (config.hub75B1 != 0 && config.hub75B2 != 0 && config.hub75ChA != 0 && config.hub75ChB != 0 && config.hub75ChC != 0 && config.hub75ChD != 0
&& config.hub75Clk != 0 && config.hub75G1 != 0 && config.hub75G2 != 0 && config.hub75Lat != 0 && config.hub75Oe != 0 && config.hub75R1 != 0 && config.hub75R2 != 0);
Wire.begin((int)SDA_PIN, (int)SCL_PIN, (uint32_t)I2C_CLK);
I2C::initI2C();
if (I2C::scd30Present()) scd30 = new SCD30(&Wire, model, updateMessage);
if (I2C::scd40Present()) scd40 = new SCD40(&Wire, model, updateMessage);
if (I2C::sps30Present()) sps30 = new SPS_30(&Wire, model, updateMessage);
if (I2C::bme680Present()) bme680 = new BME680(&Wire, model, updateMessage);
if (I2C::lcdPresent()) lcd = new LCD(&Wire, model);
if (hasLEDs) trafficLight = new TrafficLight(model, config.redLed, config.yellowLed, config.greenLed);
if (hasNeoPixel) neopixel = new Neopixel(model, config.neopixelData, config.neopixelNumber);
if (hasFeatherMatrix) featherMatrix = new FeatherMatrix(model, config.featherMatrixData, config.featherMatrixClock);
if (hasNeopixelMatrix) neopixelMatrix = new NeopixelMatrix(model, config.neopixelMatrixData, config.matrixColumns, config.matrixRows, config.matrixLayout);
if (hasHub75) hub75 = new HUB75(model);
mqtt::setupMqtt(
calibrateCo2SensorCallback,
setTemperatureOffsetCallback,
getTemperatureOffsetCallback,
getSPS30AutoCleanInterval,
setSPS30AutoCleanInterval,
cleanSPS30,
getSPS30Status,
configChanged);
char msg[128];
sprintf(msg, "Reset reason: %u", resetReason);
mqtt::publishStatusMsg(msg);
xTaskCreatePinnedToCore(mqtt::mqttLoop, // task function
"mqttLoop", // name of task
8192, // stack size of task
(void*)1, // parameter of the task
2, // priority of the task
&mqtt::mqttTask, // task handle
0); // CPU core
xTaskCreatePinnedToCore(OTA::otaLoop, // task function
"otaLoop", // name of task
8192, // stack size of task
(void*)1, // parameter of the task
2, // priority of the task
&OTA::otaTask, // task handle
1); // CPU core
Sensors::setupSensorsLoop(scd30, scd40, sps30, bme680);
sensorsTask = Sensors::start(
"sensorsLoop", // name of task
4096, // stack size of task
2, // priority of the task
1); // CPU core
if (hasNeopixelMatrix) {
neopixelMatrixTask = neopixelMatrix->start(
"neopixelMatrixLoop", // name of task
4096, // stack size of task
3, // priority of the task
1); // CPU core
}
wifiManagerTask = WifiManager::start(
"wifiManagerLoop", // name of task
8192, // stack size of task
2, // priority of the task
1); // CPU core
housekeeping::cyclicTimer.attach(30, housekeeping::doHousekeeping);
OTA::setupOta(prepareOta, setPriorityMessage, clearPriorityMessage);
attachInterrupt(BTN_1, buttonHandler, CHANGE);
ESP_LOGI(TAG, "Setup done.");
#ifdef SHOW_DEBUG_MSGS
if (lcd) {
lcd->updateMessage("Setup done.");
}
#endif
}
void loop() {
if (buttonState != oldConfirmedButtonState && (millis() - lastBtnDebounceTime) > debounceDelay) {
oldConfirmedButtonState = buttonState;
if (oldConfirmedButtonState == 1) {
lastConfirmedBtnPressedTime = millis();
} else if (oldConfirmedButtonState == 0) {
uint32_t btnPressTime = millis() - lastConfirmedBtnPressedTime;
ESP_LOGD(TAG, "lastConfirmedBtnPressedTime - millis() %u", btnPressTime);
if (btnPressTime < 2000) {
if (LED_PIN >= 0) digitalWrite(LED_PIN, LOW);
prepareOta();
WifiManager::startCaptivePortal();
} else if (btnPressTime > 5000) {
calibrateCo2SensorCallback(420);
}
}
}
vTaskDelay(pdMS_TO_TICKS(50));
}