BresserWeatherSensorLW
Bresser 868 MHz Weather Sensor Radio Receiver based on ESP32/RP2040 and SX1262/SX1276/LR1121 - sends data to a LoRaWAN Network
Loading...
Searching...
No Matches
SystemContext.h
Go to the documentation of this file.
1
2// SystemContext.h
3//
4// System context for BresserWeatherSensorLW
5//
6// - Hardware (MCU or board) specific initialization
7// - Real time clock (RTC) initialization
8// - Sleep interval handling (energy saving/battery discharge protection)
9// - Sleep mode/wake-up handling
10//
11// created: 08/2025
12//
13//
14// MIT License
15//
16// Copyright (c) 2025 Matthias Prinke
17//
18// Permission is hereby granted, free of charge, to any person obtaining a copy
19// of this software and associated documentation files (the "Software"), to deal
20// in the Software without restriction, including without limitation the rights
21// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
22// copies of the Software, and to permit persons to whom the Software is
23// furnished to do so, subject to the following conditions:
24//
25// The above copyright notice and this permission notice shall be included in all
26// copies or substantial portions of the Software.
27//
28// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
30// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
31// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
32// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
33// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
34// SOFTWARE.
35//
36//
37// History:
38//
39// 20250806 Created from BresserWeatherSensorLW.ino
40// 20250811 Replaced ESP32Time by POSIX functions
41// 20250820 Added getBattlevel()
42// 20250827 Added hysteresis for sleep interval switching
43// 20251017 Added getBattlevelPowerfeather()
44// 20251018 Added sleepIfSupplyLow for PowerFeather
45// Renamed mcuVoltage to busVoltage, changed busVoltage assignment
46// 20251030 Added sleepIfSupplyLow() for M5Core2 and getBattlevelM5core2()
47// 20251031 Added M5Stack configuration for power saving
48// Added M5Stack RTC integration
49// 20260304 Added gpsPower() and getGPSData() for GPS time sync
50//
52
61#pragma once
62
63#include <Arduino.h>
64#include <time.h>
65#include <Preferences.h>
66#include "../BresserWeatherSensorLWCfg.h"
67#include "LoadNodeCfg.h"
68#include "adc/adc.h"
69#include "logging.h"
70#if defined(ARDUINO_ESP32S3_POWERFEATHER)
71#include <PowerFeather.h>
72using namespace PowerFeather;
73#endif
74#if defined(ARDUINO_M5STACK_CORE2)
75#include <M5Unified.h>
76#endif
77#if defined(ARDUINO_ARCH_RP2040)
78#include "rp2040/pico_rtc_utils.h"
79#include <hardware/rtc.h>
80#endif
81
82#if defined(EXT_RTC)
83// Adafruit RTClib - https://github.com/adafruit/RTClib
84#include <RTClib.h>
85#endif
86
94class SystemContext
95{
96public:
97 uint16_t sleep_interval;
100
101 SystemContext() {
102 };
103
114 void begin(void);
115
122 bool isFirstBoot(void);
123
129 void resetFailedJoinCount(void);
130
137 void sleepAfterFailedJoin(void);
138
147 void setTime(time_t epoch, E_TIME_SOURCE source);
148
152 void printDateTime(void)
153 {
154 struct tm timeinfo;
155 char tbuf[25];
156
157 time_t tnow = time(nullptr);
158 localtime_r(&tnow, &timeinfo);
159 strftime(tbuf, 25, "%Y-%m-%d %H:%M:%S", &timeinfo);
160 log_i("%s", tbuf);
161 };
162
166 void savePreferences(void);
167
179 void getVoltages(void)
180 {
181 batteryVoltage = getBatteryVoltage();
182 supplyVoltage = getSupplyVoltage();
183
184 if (supplyVoltage > 3500)
185 {
186 busVoltage = supplyVoltage; // Assume that supply voltage if available
187 }
188 else if (batteryVoltage > 2000)
189 {
190 busVoltage = batteryVoltage; // Assume battery voltage if no supply voltage
191 }
192 else
193 {
194 busVoltage = 0; // No battery or supply voltage available, cannot determine bus voltage
195 }
196 };
197
198#if defined(ARDUINO_ESP32S3_POWERFEATHER)
199 void sleepIfSupplyLow(void)
200 {
201 Result res;
202 bool supply_good;
203
204 res = Board.checkSupplyGood(supply_good);
205 if ((res == Result::Ok) && supply_good)
206 {
207 return;
208 }
209 uint8_t soc = 0;
210 res = Board.getBatteryCharge(soc);
211 log_i("SOC = %d %%", soc);
212 if (res == Result::Ok && soc <= PowerFeatherCfg.soc_critical)
213 {
214 log_i("Battery low!");
216 }
217 };
218#elif defined(ARDUINO_M5STACK_CORE2)
226 void sleepIfSupplyLow(void)
227 {
228 int16_t vbus = M5.Power.getVBUSVoltage();
229 log_i("VBUS = %d mV", vbus);
230 int8_t soc = M5.Power.getBatteryLevel();
231 log_i("SOC = %d %%", soc);
232 // Charging is enabled by default
233 // void setBatteryCharge(true);
234 log_d("Charging: %u", M5.Power.isCharging());
235 log_d("Battery current = %d mA", M5.Power.getBatteryCurrent());
236
237 if (M5.Power.getVBUSVoltage() >= VOLTAGE_CRITICAL)
238 {
239 return;
240 }
241
242 if (soc <= M5StackCfg.soc_critical)
243 {
244 log_i("Battery low!");
246 }
247 };
248#else
257 {
258 if (busVoltage > 0 && busVoltage <= voltage_critical)
259 {
260 log_i("Battery low!");
262 }
263 };
264#endif
265
279 uint8_t getBattlevel(void)
280 {
281#if defined(ARDUINO_ESP32S3_POWERFEATHER)
282 return getBattlevelPowerfeather();
283#elif defined(ARDUINO_M5STACK_CORE2)
284 return getBattlevelM5core2();
285#else
286 return getBattlevelDefault();
287#endif
288 }
289
302 {
303 uint16_t voltage = batteryVoltage;
304 uint16_t limit_low = battery_discharge_lim;
305 uint16_t limit_high = battery_charge_lim;
306 uint8_t battLevel;
307
308 if (voltage == 0)
309 {
310 // Unable to measure battery voltage
311 battLevel = 255;
312 }
313 else if (voltage > limit_high)
314 {
315 // External power source
316 battLevel = 0;
317 }
318 else
319 {
320 battLevel = static_cast<uint8_t>(
321 static_cast<float>(voltage - limit_low) / static_cast<float>(limit_high - limit_low) * 255);
322 battLevel = (battLevel == 0) ? 1 : battLevel;
323 battLevel = (battLevel == 255) ? 254 : battLevel;
324 }
325 return battLevel;
326 };
327
328#if defined(GPS_EN)
334 void gpsPower(bool on)
335 {
336 if (GPS_PWR_EN_PIN < 0)
337 {
338 return; // GPS power control not available
339 }
340 if (GPS_PWR_EN_ACTIVE)
341 {
342 pinMode(GPS_PWR_EN_PIN, OUTPUT);
343 digitalWrite(GPS_PWR_EN_PIN, on ? HIGH : LOW);
344 }
345 else
346 {
347 pinMode(GPS_PWR_EN_PIN, OUTPUT);
348 digitalWrite(GPS_PWR_EN_PIN, on ? LOW : HIGH);
349 }
350 };
351#endif // GPS_EN
352
353#if defined(ARDUINO_ESP32S3_POWERFEATHER)
365 uint8_t getBattlevelPowerfeather(void)
366 {
367 Result res;
368 bool supply_good;
369
370 res = Board.checkSupplyGood(supply_good);
371 if ((res == Result::Ok) && supply_good)
372 {
373 return 0; // external power source
374 }
375
376 uint8_t soc = 0;
377 res = Board.getBatteryCharge(soc);
378 log_d("Battery SOC: %u %%", soc);
379 if (res == Result::Ok)
380 {
381 // Scale SOC (0-100%) to LoRaWAN battery level (1-254)
382 uint8_t level;
383 level = static_cast<uint8_t>(static_cast<float>(soc) / 100.0f * 254.0f);
384 level = (level == 0) ? 1 : level;
385 return level;
386 }
387 return 255; // Unable to measure
388 };
389#endif // ARDUINO_ESP32S3_POWERFEATHER
390
391#if defined(ARDUINO_M5STACK_CORE2)
403 uint8_t getBattlevelM5core2(void)
404 {
405 if (M5.Power.getVBUSVoltage() >= VOLTAGE_CRITICAL)
406 {
407 return 0; // external power source
408 }
409
410 uint8_t soc = M5.Power.getBatteryLevel();
411 log_d("Battery SOC: %u %%", soc);
412
413 // Scale SOC (0-100%) to LoRaWAN battery level (1-254)
414 uint8_t level;
415 level = static_cast<uint8_t>(static_cast<float>(soc) / 100.0f * 254.0f);
416 level = (level == 0) ? 1 : level;
417 return level;
418 };
419#endif // ARDUINO_M5STACK_CORE2
420
433 uint32_t sleepInterval(void);
434
445 {
447 };
448
455 bool isRtcSynched(void);
456
462 E_TIME_SOURCE getRtcTimeSource(void);
463
475 bool rtcNeedsSync(void);
476
477#if defined(GPS_EN)
484 bool getGPSData(time_t &gpsTime);
485#endif
486
502 uint32_t sleepDuration(void)
503 {
504 uint32_t sleep_interval = sleepInterval();
505
506 // If the real time is available, align the wake-up time to
507 // next non-fractional multiple of sleep_interval past the hour
508 if (isRtcSynched())
509 {
510 struct tm timeinfo;
511 time_t t_now = time(nullptr);
512 localtime_r(&t_now, &timeinfo);
513
514 sleep_interval = sleep_interval - ((timeinfo.tm_min * 60) % sleep_interval + timeinfo.tm_sec);
515 }
516
517 sleep_interval = max(sleep_interval, static_cast<uint32_t>(SLEEP_INTERVAL_MIN));
518 return sleep_interval;
519 };
520
529 void uplinkDelay(uint32_t timeUntilUplink, uint32_t uplinkInterval)
530 {
531 uint32_t uplinkIntervalMs = uplinkInterval * 1000UL;
532 uint32_t delayMs = max(timeUntilUplink, uplinkIntervalMs); // cannot send faster than duty cycle allows
533
534 log_d("Sending uplink in %u s", delayMs / 1000);
535#if defined(ESP32)
536 esp_sleep_enable_timer_wakeup(delayMs * 1000);
537 esp_light_sleep_start();
538#else
539 delay(delayMs);
540#endif
541 };
542
550 void gotoSleep(uint32_t seconds)
551 {
552#if defined(ARDUINO_ARCH_RP2040)
553 gotoSleepRP2040(seconds);
554#elif defined(ESP32)
555 gotoSleepESP32(seconds);
556#endif
557 };
558
559#if defined(ARDUINO_M5STACK_CORE2)
560 void setupM5StackCore2(void);
561#endif
562
563private:
564#if defined(EXT_RTC)
568 void getTimeFromExtRTC(void);
569#endif
570
571#if defined(EXT_RTC)
575 void syncRTCWithExtRTC(void);
576#endif
577
578#if defined(ARDUINO_M5STACK_CORE2)
582 void getTimeFromExtRTC(void);
583#endif
584
585#if defined(ARDUINO_M5STACK_CORE2)
589 void syncRTCWithExtRTC(void);
590#endif
591
592#if defined(ESP32)
600 void gotoSleepESP32(uint32_t seconds);
601#endif
602
603#if defined(ARDUINO_ARCH_RP2040)
604
619 void gotoSleepRP2040(uint32_t seconds);
620
624 void restoreRP2040(void);
625#endif // ARDUINO_ARCH_RP2040
626
627#if defined(ESP32)
635 void print_wakeup_reason()
636 {
637 esp_sleep_wakeup_cause_t wakeup_reason = esp_sleep_get_wakeup_cause();
638 if (wakeup_reason == ESP_SLEEP_WAKEUP_TIMER)
639 {
640 log_i("Wake from sleep");
641 }
642 else
643 {
644 log_i("Wake not caused by deep sleep: %u", wakeup_reason);
645 }
646 };
647#endif // ESP32
648
649#if defined(ARDUINO_ESP32S3_POWERFEATHER)
650 void setupPowerFeather(struct sPowerFeatherCfg &cfg);
651#endif
652
653private:
654#if defined(ARDUINO_ESP32S3_POWERFEATHER)
655 struct sPowerFeatherCfg PowerFeatherCfg = {
656 .battery_capacity = BATTERY_CAPACITY_MAH,
657 .supply_maintain_voltage = PF_SUPPLY_MAINTAIN_VOLTAGE,
658 .max_charge_current = PF_MAX_CHARGE_CURRENT_MAH,
659 .soc_eco_enter = SOC_ECO_ENTER,
660 .soc_eco_exit = SOC_ECO_EXIT,
661 .soc_critical = SOC_CRITICAL,
662 .temperature_measurement = PF_TEMPERATURE_MEASUREMENT,
663 .battery_fuel_gauge = PF_BATTERY_FUEL_GAUGE};
664 struct sM5StackCfg M5StackCfg = {0};
665#elif defined(ARDUINO_M5STACK_CORE2)
666 struct sPowerFeatherCfg PowerFeatherCfg = {0};
667 struct sM5StackCfg M5StackCfg = {
668 .soc_eco_enter = SOC_ECO_ENTER,
669 .soc_eco_exit = SOC_ECO_EXIT,
670 .soc_critical = SOC_CRITICAL};
671#else
672 struct sPowerFeatherCfg PowerFeatherCfg = {0};
673 struct sM5StackCfg M5StackCfg = {0};
674#endif
675
676 uint16_t voltage_eco_exit = VOLTAGE_ECO_EXIT;
677 uint16_t voltage_eco_enter = VOLTAGE_ECO_ENTER;
678 uint16_t voltage_critical = VOLTAGE_CRITICAL;
679 uint16_t battery_discharge_lim = BATTERY_DISCHARGE_LIM;
680 uint16_t battery_charge_lim = BATTERY_CHARGE_LIM;
681 uint16_t batteryVoltage = 0; // Battery voltage in mV
682 uint16_t supplyVoltage = 0; // Supply voltage in mV
683 uint16_t busVoltage = 0; // bus voltage in mV (depending on the circuit)
684};
Load LoRaWAN node configuration 'node_config.json' from LittleFS, if available.
ADC wrapper/convenience functions.
uint16_t getSupplyVoltage(void)
Get supply voltage.
Definition adc.cpp:155
uint16_t getBatteryVoltage(void)
Get battery voltage.
Definition adc.cpp:99
void getVoltages(void)
Get the voltages from ADC / Power Management Chip.
Definition SystemContext.h:179
uint8_t getBattlevelDefault(void)
Get the battery fill level (default implementation).
Definition SystemContext.h:301
uint32_t sleepDuration(void)
Compute sleep duration in seconds.
Definition SystemContext.h:502
void savePreferences(void)
Save preferences to flash memory.
Definition SystemContext.cpp:221
void printDateTime(void)
Definition SystemContext.h:152
uint8_t lw_stat_interval
preferences: LoRaWAN node status uplink interval
Definition SystemContext.h:99
bool isFirstBoot(void)
Check if this is the first boot of the system after power-on/HW reset.
Definition SystemContext.cpp:184
bool isRtcSynched(void)
Check if the RTC is synchronized to a time source.
Definition SystemContext.cpp:386
void uplinkDelay(uint32_t timeUntilUplink, uint32_t uplinkInterval)
LoRaWAN uplink delay.
Definition SystemContext.h:529
void sleepAfterFailedJoin(void)
Sleep after a failed join attempt.
Definition SystemContext.cpp:194
void resetFailedJoinCount(void)
Reset the failed join count.
Definition SystemContext.cpp:189
bool longSleepActive(void)
Check if long sleep is active.
Definition SystemContext.h:444
uint8_t getBattlevel(void)
Get the battery fill level.
Definition SystemContext.h:279
void sleepIfSupplyLow(void)
Sleep if battery voltage is low to prevent deep-discharging.
Definition SystemContext.h:256
void setTime(time_t epoch, E_TIME_SOURCE source)
Set RTC to epoch.
Definition SystemContext.cpp:208
void gotoSleep(uint32_t seconds)
Enter sleep mode.
Definition SystemContext.h:550
bool rtcNeedsSync(void)
Check if the RTC needs to be synchronized to a time source.
Definition SystemContext.cpp:398
void begin(void)
Initialize the system context.
Definition SystemContext.cpp:133
uint32_t sleepInterval(void)
Switch between normal and long sleep interval.
Definition SystemContext.cpp:278
uint16_t sleep_interval
preferences: sleep interval
Definition SystemContext.h:97
E_TIME_SOURCE getRtcTimeSource(void)
Get the RTC time source.
Definition SystemContext.cpp:392
uint16_t sleep_interval_long
preferences: sleep interval long
Definition SystemContext.h:98
Replacement for esp32-hal-log.h on RP20240.