Skip to content

Commit

Permalink
Zigbee2mqtt: improved synchronization
Browse files Browse the repository at this point in the history
  • Loading branch information
awawa-dev committed Dec 28, 2024
1 parent 5f2b3c2 commit 4a07528
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 7 additions & 0 deletions include/led-drivers/net/DriverNetZigbee2mqtt.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@
#include <memory>
#include <list>
#include <atomic>
#include <chrono>
#include <mutex>
#endif

#include <condition_variable>

#include <led-drivers/LedDevice.h>
#include <linalg.h>

Expand Down Expand Up @@ -59,5 +63,8 @@ public slots:
int _timeLogger;
QString _discoveryMessage;

std::mutex _mtx;
std::condition_variable _cv;

static bool isRegistered;
};
14 changes: 11 additions & 3 deletions sources/led-drivers/net/DriverNetZigbee2mqtt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace
{
constexpr auto ZIGBEE_DISCOVERY_MESSAGE = "zigbee2mqtt/bridge/devices";
constexpr int DEFAULT_TIME_MEASURE_MESSAGE = 25;
constexpr int DEFAULT_COMMUNICATION_TIMEOUT_MS = 200;
}

DriverNetZigbee2mqtt::DriverNetZigbee2mqtt(const QJsonObject& deviceConfig)
Expand Down Expand Up @@ -149,12 +150,15 @@ int DriverNetZigbee2mqtt::write(const std::vector<ColorRgb>& ledValues)

auto start = InternalClock::nowPrecise();

for (int timeout = 0; timeout < 25 && _colorsFinished > 0; timeout++)
std::unique_lock<std::mutex> lck(_mtx);
_cv.wait_for(lck, std::chrono::milliseconds(DEFAULT_COMMUNICATION_TIMEOUT_MS));

for (int timeout = 0; timeout < 20 && _colorsFinished > 0 && (InternalClock::nowPrecise() < start + DEFAULT_COMMUNICATION_TIMEOUT_MS); timeout++)
{
QThread::msleep(8);
QThread::msleep(10);
}

if (_colorsFinished > 0)
if (_colorsFinished.exchange(0) > 0)
{
Warning(_log, "The communication timed out after %ims (%i)", (int)(InternalClock::nowPrecise() - start), (++_timeLogger));
}
Expand All @@ -176,6 +180,10 @@ void DriverNetZigbee2mqtt::handlerSignalMqttReceived(QString topic, QString payl
else if (_colorsFinished > 0)
{
_colorsFinished--;
if (_colorsFinished == 0)
{
_cv.notify_all();
}
}
}

Expand Down

0 comments on commit 4a07528

Please sign in to comment.