From c746c486497ab4b2227671fec7925bcd965c3db5 Mon Sep 17 00:00:00 2001 From: Igor Mammedov Date: Tue, 21 Apr 2026 21:49:49 +0200 Subject: [PATCH] CrealityPrint: add ws_send_and_read() helper Add a reusable websocket helper that sends a JSON command and loops reads until finding a response containing the expected key. This handles the printer's unsolicited status messages that arrive on connect before the actual response. Returns empty string on timeout instead of throwing. Signed-off-by: Igor Mammedov --- src/slic3r/Utils/CrealityPrint.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/slic3r/Utils/CrealityPrint.cpp b/src/slic3r/Utils/CrealityPrint.cpp index 43a5084177..0ae698001c 100644 --- a/src/slic3r/Utils/CrealityPrint.cpp +++ b/src/slic3r/Utils/CrealityPrint.cpp @@ -222,6 +222,27 @@ static void ws_connect(net::io_context& ioc, websocket::stream(&recv_timeout), sizeof(recv_timeout)); } + +static std::string ws_send_and_read(websocket::stream& ws, const json& cmd, const std::string& expected_key, int max_reads = 20) +{ + ws.write(net::buffer(to_string(cmd))); + + for (int i = 0; i < max_reads; i++) { + beast::flat_buffer buf; + beast::error_code ec; + ws.read(buf, ec); + if (ec == net::error::would_block) + break; + if (ec) + throw beast::system_error{ec}; + std::string msg = beast::buffers_to_string(buf.data()); + if (msg.find(expected_key) != std::string::npos) + return msg; + } + BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: No '" << expected_key << "' response after " << max_reads << " messages"; + return {}; +} + void CrealityPrint::query_model() const { if (!m_model.empty())