Communication: Allow redirection of reads

pull/35/head
Paul Hollinsky 2021-04-23 17:00:37 -04:00
parent bb7719d185
commit 55ca6adee6
2 changed files with 22 additions and 6 deletions

View File

@ -72,6 +72,14 @@ bool Communication::sendCommand(Command cmd, std::vector<uint8_t> arguments) {
return sendPacket(packet); return sendPacket(packet);
} }
bool Communication::redirectRead(std::function<void(std::vector<uint8_t>&&)> redirectTo) {
if(redirectingRead)
return false;
redirectionFn = redirectTo;
redirectingRead = true;
return true;
}
bool Communication::getSettingsSync(std::vector<uint8_t>& data, std::chrono::milliseconds timeout) { bool Communication::getSettingsSync(std::vector<uint8_t>& data, std::chrono::milliseconds timeout) {
std::shared_ptr<Message> msg = waitForMessageSync([this]() { std::shared_ptr<Message> msg = waitForMessageSync([this]() {
return sendCommand(Command::ReadSettings, { 0, 0, 0, 1 /* Get Global Settings */, 0, 1 /* Subversion 1 */ }); return sendCommand(Command::ReadSettings, { 0, 0, 0, 1 /* Get Global Settings */, 0, 1 /* Subversion 1 */ });
@ -181,6 +189,9 @@ void Communication::readTask() {
while(!closing) { while(!closing) {
readBytes.clear(); readBytes.clear();
if(driver->readWait(readBytes)) { if(driver->readWait(readBytes)) {
if(redirectingRead) {
redirectionFn(std::move(readBytes));
} else {
if(packetizer->input(readBytes)) { if(packetizer->input(readBytes)) {
for(const auto& packet : packetizer->output()) { for(const auto& packet : packetizer->output()) {
std::shared_ptr<Message> msg; std::shared_ptr<Message> msg;
@ -192,4 +203,5 @@ void Communication::readTask() {
} }
} }
} }
}
} }

View File

@ -42,6 +42,8 @@ public:
virtual void joinThreads(); virtual void joinThreads();
bool rawWrite(const std::vector<uint8_t>& bytes) { return driver->write(bytes); } bool rawWrite(const std::vector<uint8_t>& bytes) { return driver->write(bytes); }
virtual bool sendPacket(std::vector<uint8_t>& bytes); virtual bool sendPacket(std::vector<uint8_t>& bytes);
bool redirectRead(std::function<void(std::vector<uint8_t>&&)> redirectTo);
void clearRedirectRead() { redirectingRead = false; }
void setWriteBlocks(bool blocks) { driver->writeBlocks = blocks; } void setWriteBlocks(bool blocks) { driver->writeBlocks = blocks; }
@ -76,6 +78,8 @@ protected:
std::mutex messageCallbacksLock; std::mutex messageCallbacksLock;
std::map<int, MessageCallback> messageCallbacks; std::map<int, MessageCallback> messageCallbacks;
std::atomic<bool> closing{false}; std::atomic<bool> closing{false};
std::atomic<bool> redirectingRead{false};
std::function<void(std::vector<uint8_t>&&)> redirectionFn;
void dispatchMessage(const std::shared_ptr<Message>& msg); void dispatchMessage(const std::shared_ptr<Message>& msg);