Skip to content

Commit

Permalink
BeforeUpdateCallback (#213)
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieucarbou authored Jun 2, 2024
1 parent 549aa98 commit 6f05017
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/ESPDash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ ESPDash::ESPDash(AsyncWebServer* server, const char* uri, bool enable_default_st
// client side commands parsing
if (json["command"] == "get:layout") {
_asyncAccessInProgress = true;
if (_beforeUpdateCallback)
_beforeUpdateCallback(false);
generateLayoutJSON(client, false);
_asyncAccessInProgress = false;
} else if (json["command"] == "ping") {
Expand Down Expand Up @@ -487,6 +489,8 @@ void ESPDash::sendUpdates(bool force) {
if (!hasClient()) {
return;
}
if (_beforeUpdateCallback)
_beforeUpdateCallback(!force);
generateLayoutJSON(nullptr, !force);
}

Expand All @@ -495,6 +499,8 @@ void ESPDash::refreshCard(Card *card) {
if (!hasClient()) {
return;
}
if (_beforeUpdateCallback)
_beforeUpdateCallback(true);
generateLayoutJSON(nullptr, true, card);
}

Expand Down
12 changes: 12 additions & 0 deletions src/ESPDash.h
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,11 @@ class Statistic;

// ESPDASH Class
class ESPDash{
public:
// changes_only: true (equivalent to sendUpdates(false)) - when sending updates to the client
// changes_only: false (equivalent to sendUpdates(true)) - when sending the entire layout to the client or when forcing a full update
typedef std::function<void(bool changes_only)> BeforeUpdateCallback;

private:
AsyncWebServer* _server = nullptr;
AsyncWebSocket* _ws = nullptr;
Expand All @@ -80,6 +85,7 @@ class ESPDash{
char username[64];
char password[64];
uint32_t _idCounter = 0;
BeforeUpdateCallback _beforeUpdateCallback = nullptr;

volatile bool _asyncAccessInProgress = false;

Expand Down Expand Up @@ -129,6 +135,12 @@ class ESPDash{
// in which case you should not modify them
bool isAsyncAccessInProgress() { return _asyncAccessInProgress; }

// Register a callback that will be called before some updates will be sent to the client.
// This callback can be used for example to refresh some card values that never change after only when a full layout is request (i.e. on page reload).
// This allows to avoid spending time refreshing cards that never change, but still allows them to be refreshed hen the user refresh the dashboard.
// If called from the async_http task, isAsyncAccessInProgress() will return true while in this callback.
void onBeforeUpdate(BeforeUpdateCallback callback) { _beforeUpdateCallback = callback; }

~ESPDash();
};

Expand Down

0 comments on commit 6f05017

Please sign in to comment.