From 46d88c6520fdde8149b79a166775b9a58b32983b Mon Sep 17 00:00:00 2001 From: Thomas Basler Date: Fri, 17 Jun 2022 13:29:21 +0200 Subject: [PATCH] Improoved websocket handling --- include/WebApi_ws_live.h | 4 ++++ src/WebApi_ws_live.cpp | 32 ++++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/include/WebApi_ws_live.h b/include/WebApi_ws_live.h index 9e44811..0f57bd9 100644 --- a/include/WebApi_ws_live.h +++ b/include/WebApi_ws_live.h @@ -12,4 +12,8 @@ public: private: AsyncWebSocket* _ws; void addField(JsonDocument& root, uint8_t idx, std::shared_ptr inv, uint8_t channel, uint8_t fieldId); + + uint32_t _lastWsPublish = 0; + uint32_t _lastInvUpdateCheck = 0; + uint32_t _newestInverterTimestamp = 0; }; \ No newline at end of file diff --git a/src/WebApi_ws_live.cpp b/src/WebApi_ws_live.cpp index 6297466..6340755 100644 --- a/src/WebApi_ws_live.cpp +++ b/src/WebApi_ws_live.cpp @@ -1,7 +1,6 @@ #include "WebApi_ws_live.h" #include "AsyncJson.h" #include "Configuration.h" -#include void WebApiWsLiveClass::init(AsyncWebSocket* ws) { @@ -10,12 +9,27 @@ void WebApiWsLiveClass::init(AsyncWebSocket* ws) void WebApiWsLiveClass::loop() { - EVERY_N_SECONDS(10) - { - // do nothing if no WS client is connected - if (_ws->count() == 0) { - return; + // do nothing if no WS client is connected + if (_ws->count() == 0) { + return; + } + + if (millis() - _lastInvUpdateCheck < 1000) { + return; + } + _lastInvUpdateCheck = millis(); + + uint32_t maxTimeStamp = 0; + for (uint8_t i = 0; i < Hoymiles.getNumInverters(); i++) { + auto inv = Hoymiles.getInverterByPos(i); + + if (inv->getLastStatsUpdate() > maxTimeStamp) { + maxTimeStamp = inv->getLastStatsUpdate(); } + } + + // Update on every inverter change or at least after 10 seconds + if (millis() - _lastWsPublish > (10 * 1000) || (maxTimeStamp != _newestInverterTimestamp)) { DynamicJsonDocument root(40960); // Loop all inverters @@ -48,6 +62,10 @@ void WebApiWsLiveClass::loop() addField(root, i, inv, c, FLD_EFF); addField(root, i, inv, c, FLD_IRR); } + + if (inv->getLastStatsUpdate() > _newestInverterTimestamp) { + _newestInverterTimestamp = inv->getLastStatsUpdate(); + } } size_t len = measureJson(root); @@ -56,6 +74,8 @@ void WebApiWsLiveClass::loop() serializeJson(root, (char*)buffer->get(), len + 1); _ws->textAll(buffer); } + + _lastWsPublish = millis(); } }