diff --git a/src/logid/backend/dj/Receiver.cpp b/src/logid/backend/dj/Receiver.cpp index e32a1dd..64118f5 100644 --- a/src/logid/backend/dj/Receiver.cpp +++ b/src/logid/backend/dj/Receiver.cpp @@ -325,9 +325,7 @@ void Receiver::listen() { if(!_raw_device->isListening()) ///TODO: Kill RawDevice? - thread::spawn({[raw=this->_raw_device]() { - raw->listen(); - }}); + _raw_device->listenAsync(); if(_raw_device->eventHandlers().find("RECV_HIDPP") == _raw_device->eventHandlers().end()) { diff --git a/src/logid/backend/hidpp/Device.cpp b/src/logid/backend/hidpp/Device.cpp index ae3f061..5e62a66 100644 --- a/src/logid/backend/hidpp/Device.cpp +++ b/src/logid/backend/hidpp/Device.cpp @@ -200,9 +200,7 @@ uint16_t Device::pid() const void Device::listen() { if(!_raw_device->isListening()) - thread::spawn({[raw=this->_raw_device]() { - raw->listen(); - }}); + _raw_device->listenAsync(); // Pass all HID++ events with device index to this device. auto handler = std::make_shared(); diff --git a/src/logid/backend/raw/RawDevice.cpp b/src/logid/backend/raw/RawDevice.cpp index 2905c38..8019aa5 100644 --- a/src/logid/backend/raw/RawDevice.cpp +++ b/src/logid/backend/raw/RawDevice.cpp @@ -23,6 +23,7 @@ #include "../../util/log.h" #include "../hidpp/Report.h" #include "../../Configuration.h" +#include "../../util/thread.h" #include #include @@ -327,8 +328,8 @@ void RawDevice::interruptRead() void RawDevice::listen() { std::lock_guard lock(_listening); - _continue_listen = true; + _listen_condition.notify_all(); while(_continue_listen) { while(!_io_queue.empty()) { auto task = _io_queue.front(); @@ -351,6 +352,18 @@ void RawDevice::listen() _continue_listen = false; } +void RawDevice::listenAsync() +{ + std::mutex listen_check; + std::unique_lock check_lock(listen_check); + thread::spawn({[this]() { listen(); }}); + + // Block until RawDevice is listening + _listen_condition.wait(check_lock, [this](){ + return (bool)_continue_listen; + }); +} + void RawDevice::stopListener() { _continue_listen = false; diff --git a/src/logid/backend/raw/RawDevice.h b/src/logid/backend/raw/RawDevice.h index 3cb1823..4c7dec9 100644 --- a/src/logid/backend/raw/RawDevice.h +++ b/src/logid/backend/raw/RawDevice.h @@ -54,6 +54,7 @@ namespace raw void interruptRead(); void listen(); + void listenAsync(); void stopListener(); bool isListening(); @@ -74,6 +75,7 @@ namespace raw std::vector rdesc; std::atomic _continue_listen; + std::condition_variable _listen_condition; std::map> _event_handlers;