From 205837c3ae45bef30e3a3f9d1e3f21e44cec3a3c Mon Sep 17 00:00:00 2001 From: dragonmux Date: Tue, 16 Jan 2024 04:21:07 +0000 Subject: [PATCH] windows/serialInterface: Implemented wait-based back-off on the ReadFile() call to help mitigate CPU impacts and implement proper timeouts --- src/windows/serialInterface.cxx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/windows/serialInterface.cxx b/src/windows/serialInterface.cxx index 375d040..9008ba9 100644 --- a/src/windows/serialInterface.cxx +++ b/src/windows/serialInterface.cxx @@ -281,6 +281,12 @@ void serialInterface_t::writePacket(const std::string_view &packet) const // NOLINTNEXTLINE(readability-convert-member-functions-to-static) void serialInterface_t::refillBuffer() const { + // Try to wait for up to 100ms for data to become available + if (WaitForSingleObject(device, 100) != WAIT_OBJECT_0) + { + console.error("Waiting for data from device failed ("sv, GetLastError(), ")"sv); + throw bmpCommsError_t{}; + } DWORD bytesReceived = 0; // Try to fill the read buffer, and if that fails, bail if (!ReadFile(device, readBuffer.data(), static_cast(readBuffer.size()), &bytesReceived, nullptr)) @@ -302,7 +308,7 @@ std::string serialInterface_t::readPacket() const while (length < packet.size()) { // Check if we need more data or should use what's in the buffer already - while (readBufferOffset == readBufferFullness) + if (readBufferOffset == readBufferFullness) refillBuffer(); const auto *const bufferBegin{readBuffer.data() + readBufferOffset};