Clarify code for sleep

This commit is contained in:
Christoph Hagen 2023-06-05 13:06:17 +02:00
parent c4d8116cfd
commit 7f3ec0841e
2 changed files with 16 additions and 13 deletions

View File

@ -39,11 +39,13 @@ public:
void onConnect(BLEServer *server) override {
isConnected = true;
Serial.println("Connected");
}
void onDisconnect(BLEServer *server) override {
isConnected = false;
bluetoothStartAdvertising();
Serial.println("Disconnected");
}
};

View File

@ -50,14 +50,16 @@ uint32_t secondsUntilNextTemperatureMeasurement() {
void deepSleepUntilNextTemperatureMeasurement() {
uint32_t seconds = secondsUntilNextTemperatureMeasurement();
if (seconds == 0) {
if (seconds = 0) {
// The time until next measurement is too short,
// so don't sleep and just wait a little
// May run the loop multiple times until the time is elapsed
delay(100);
} else {
esp_deep_sleep(seconds * 1000000);
return;
}
Serial.print("Sleeping for ");
Serial.print(seconds);
Serial.println(" seconds");
esp_deep_sleep(seconds * 1000000);
}
/**
@ -76,11 +78,14 @@ void updateStayAwakeTime() {
timeUntilSleep = time(NULL) + wakeupDurationAfterButtonPress;
}
bool shouldStayAwakeDueToActivity() {
bool shouldGoToSleep() {
if (timeUntilSleep > time(NULL)) {
return true;
return false;
}
return bluetoothIsConnected();
if (bluetoothIsConnected()) {
return false;
}
return true;
}
void enableLED() {
@ -139,14 +144,10 @@ void loop() {
updateStayAwakeTime();
}
if (!shouldStayAwakeDueToActivity()) {
Serial.print("Sleeping for ");
Serial.print(secondsUntilNextTemperatureMeasurement());
Serial.println(" seconds");
if (shouldGoToSleep()) {
// May return, if less then one second to wait
// Otherwise control flow starts with setup() again
deepSleepUntilNextTemperatureMeasurement();
} else {
delay(100);
}
delay(50);
}