Skip to content

Commit 4a07528

Browse files
committed
Zigbee2mqtt: improved synchronization
1 parent 5f2b3c2 commit 4a07528

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

include/led-drivers/net/DriverNetZigbee2mqtt.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,12 @@
66
#include <memory>
77
#include <list>
88
#include <atomic>
9+
#include <chrono>
10+
#include <mutex>
911
#endif
1012

13+
#include <condition_variable>
14+
1115
#include <led-drivers/LedDevice.h>
1216
#include <linalg.h>
1317

@@ -59,5 +63,8 @@ public slots:
5963
int _timeLogger;
6064
QString _discoveryMessage;
6165

66+
std::mutex _mtx;
67+
std::condition_variable _cv;
68+
6269
static bool isRegistered;
6370
};

sources/led-drivers/net/DriverNetZigbee2mqtt.cpp

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ namespace
66
{
77
constexpr auto ZIGBEE_DISCOVERY_MESSAGE = "zigbee2mqtt/bridge/devices";
88
constexpr int DEFAULT_TIME_MEASURE_MESSAGE = 25;
9+
constexpr int DEFAULT_COMMUNICATION_TIMEOUT_MS = 200;
910
}
1011

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

150151
auto start = InternalClock::nowPrecise();
151152

152-
for (int timeout = 0; timeout < 25 && _colorsFinished > 0; timeout++)
153+
std::unique_lock<std::mutex> lck(_mtx);
154+
_cv.wait_for(lck, std::chrono::milliseconds(DEFAULT_COMMUNICATION_TIMEOUT_MS));
155+
156+
for (int timeout = 0; timeout < 20 && _colorsFinished > 0 && (InternalClock::nowPrecise() < start + DEFAULT_COMMUNICATION_TIMEOUT_MS); timeout++)
153157
{
154-
QThread::msleep(8);
158+
QThread::msleep(10);
155159
}
156160

157-
if (_colorsFinished > 0)
161+
if (_colorsFinished.exchange(0) > 0)
158162
{
159163
Warning(_log, "The communication timed out after %ims (%i)", (int)(InternalClock::nowPrecise() - start), (++_timeLogger));
160164
}
@@ -176,6 +180,10 @@ void DriverNetZigbee2mqtt::handlerSignalMqttReceived(QString topic, QString payl
176180
else if (_colorsFinished > 0)
177181
{
178182
_colorsFinished--;
183+
if (_colorsFinished == 0)
184+
{
185+
_cv.notify_all();
186+
}
179187
}
180188
}
181189

0 commit comments

Comments
 (0)