Skip to content

Commit

Permalink
day_ahead_prices: Retry download with higher frequency in some cases
Browse files Browse the repository at this point in the history
This is mostly to make sure that the day ahead prices are retrieved
without a big delay after first boot.
  • Loading branch information
borg42 committed Nov 7, 2024
1 parent 334095c commit 565daf0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
20 changes: 15 additions & 5 deletions software/src/modules/day_ahead_prices/day_ahead_prices.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@
#include "tools.h"
#include <cmath>

extern "C" esp_err_t esp_crt_bundle_attach(void *conf);

static constexpr auto CHECK_INTERVAL = 1_m;
static constexpr auto PRICE_UPDATE_INTERVAL = 15_m;

Expand Down Expand Up @@ -134,7 +132,7 @@ void DayAheadPrices::register_urls()
api.addState("day_ahead_prices/prices", &prices);

task_scheduler.scheduleWhenClockSynced([this]() {
task_scheduler.scheduleWithFixedDelay([this]() {
this->task_id = task_scheduler.scheduleWithFixedDelay([this]() {
this->update();
}, CHECK_INTERVAL);
});
Expand Down Expand Up @@ -170,6 +168,18 @@ void DayAheadPrices::update_price()
#endif
}

void DayAheadPrices::retry_update(millis_t delay)
{
// Cancel current task
task_scheduler.cancel(task_id);

// And schedule a new one that will run after the given delay,
// but with the standard interval afterwards again
this->task_id = task_scheduler.scheduleWithFixedDelay([this]() {
this->update();
}, delay, CHECK_INTERVAL);
}

void DayAheadPrices::update()
{
if (config.get("enable")->asBool() == false) {
Expand All @@ -181,6 +191,7 @@ void DayAheadPrices::update()
}

if (!network.connected) {
retry_update(1_s);
return;
}

Expand All @@ -191,6 +202,7 @@ void DayAheadPrices::update()
// Only update if clock is synced
struct timeval tv_now;
if (!rtc.clock_synced(&tv_now)) {
retry_update(1_s);
return;
}

Expand All @@ -203,8 +215,6 @@ void DayAheadPrices::update()
return;
}

last_update_begin = now_us();

if(json_buffer == nullptr) {
json_buffer = (char *)heap_caps_calloc_prefer(DAY_AHEAD_PRICE_MAX_JSON_LENGTH, sizeof(char), 2, MALLOC_CAP_SPIRAM, MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL);
} else {
Expand Down
2 changes: 2 additions & 0 deletions software/src/modules/day_ahead_prices/day_ahead_prices.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ class DayAheadPrices final : public IModule
{
private:
void update();
void retry_update(millis_t delay);
void update_price();
String get_api_url_with_path();
int get_max_price_values();
Expand All @@ -62,6 +63,7 @@ class DayAheadPrices final : public IModule
uint32_t json_buffer_position;
bool current_price_available = false;
AsyncHTTPSClient https_client;
uint64_t task_id;

DAPDownloadState download_state = DAP_DOWNLOAD_STATE_OK;

Expand Down

0 comments on commit 565daf0

Please sign in to comment.