From f92dc78be0272f804bebf88998d0d568736bf27f Mon Sep 17 00:00:00 2001 From: HanifKoh <76276251+HanifKoh@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:27:04 +0800 Subject: [PATCH] Check Moonraker Free Space Before Reporting Storage (#16903) * Report storage on every Moonraker status push MachineObject sets the storage state on every push, first from "sdcard" and then from home_flag bits 8-9. The Moonraker agent sent neither, so each push reset the state to NO_SDCARD and the send dialog blocked with "Storage needs to be inserted before printing". Moonraker printers always have storage (virtual_sdcard), so report it in both places. Co-Authored-By: Claude Opus 5.5 * Check Moonraker Free Space Before Reporting Storage Report storage only when the gcodes root has free space, read from disk_usage in /server/files/directory?path=gcodes, instead of always reporting it. The status stream checks before the subscription and again from the read loop every 30 s. A check that fails counts as no storage. Move the Http::get boilerplate of the device info, status, object list and storage queries into one get_json helper. * Ask to Insert Storage or Free Up Space Before Printing A printer agent now also reports no storage when its disk is full, so the messages for that state say to free up space as well. The two "before send(ing) to printer" variants share one string. --------- Co-authored-by: dr-apple <15102858+dr-apple@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../GUI/CalibrationWizardPresetPage.cpp | 2 +- src/slic3r/GUI/Jobs/SendJob.cpp | 2 +- src/slic3r/GUI/PrePrintChecker.cpp | 2 +- src/slic3r/GUI/SendToPrinter.cpp | 2 +- src/slic3r/GUI/SyncAmsInfoDialog.cpp | 2 +- src/slic3r/Utils/CalibUtils.cpp | 4 +- src/slic3r/Utils/MoonrakerPrinterAgent.cpp | 236 +++++++++--------- src/slic3r/Utils/MoonrakerPrinterAgent.hpp | 12 + .../test_moonraker_printer_agent.cpp | 76 ++++++ 9 files changed, 209 insertions(+), 129 deletions(-) diff --git a/src/slic3r/GUI/CalibrationWizardPresetPage.cpp b/src/slic3r/GUI/CalibrationWizardPresetPage.cpp index 673026159e..9f8cb0b127 100644 --- a/src/slic3r/GUI/CalibrationWizardPresetPage.cpp +++ b/src/slic3r/GUI/CalibrationWizardPresetPage.cpp @@ -1943,7 +1943,7 @@ void CalibrationPresetPage::show_status(CaliPresetPageStatus status) Enable_Send_Button(false); } else if (status == CaliPresetPageStatus::CaliPresetStatusNoSdcard) { - wxString msg_text = _L("Storage needs to be inserted before printing."); + wxString msg_text = _L("Insert storage or free up space before printing."); update_print_status_msg(msg_text, true); Enable_Send_Button(false); } diff --git a/src/slic3r/GUI/Jobs/SendJob.cpp b/src/slic3r/GUI/Jobs/SendJob.cpp index 419b03afd3..cd7b05e353 100644 --- a/src/slic3r/GUI/Jobs/SendJob.cpp +++ b/src/slic3r/GUI/Jobs/SendJob.cpp @@ -352,7 +352,7 @@ void SendJob::process(Ctl &ctl) } else { switch(this->sdcard_state) { case DevStorage::SdcardState::NO_SDCARD: - ctl.update_status(curr_percent, _u8L("Storage needs to be inserted before sending to printer.")); + ctl.update_status(curr_percent, _u8L("Insert storage or free up space before sending to the printer.")); return; case DevStorage::SdcardState::HAS_SDCARD_ABNORMAL: if(this->has_sdcard) { diff --git a/src/slic3r/GUI/PrePrintChecker.cpp b/src/slic3r/GUI/PrePrintChecker.cpp index 40ec5207aa..1cefc98cc6 100644 --- a/src/slic3r/GUI/PrePrintChecker.cpp +++ b/src/slic3r/GUI/PrePrintChecker.cpp @@ -114,7 +114,7 @@ wxString PrePrintChecker::get_pre_state_msg(PrintDialogStatus status) case PrintStatusNozzleDataInvalid: return _L("Invalid nozzle information, please refresh or manually set nozzle information."); case PrintStatusLanModeNoSdcard: return _L("Storage needs to be inserted before printing via LAN."); case PrintStatusLanModeSDcardNotAvailable: return _L("Storage is in abnormal state or is in read-only mode."); - case PrintStatusNoSdcard: return _L("Storage needs to be inserted before printing."); + case PrintStatusNoSdcard: return _L("Insert storage or free up space before printing."); case PrintStatusNeedForceUpgrading: return _L("Cannot send the print job to a printer whose firmware must be updated."); case PrintStatusNeedConsistencyUpgrading: return _L("Cannot send the print job to a printer whose firmware must be updated."); case PrintStatusBlankPlate: return _L("Cannot send a print job for an empty plate."); diff --git a/src/slic3r/GUI/SendToPrinter.cpp b/src/slic3r/GUI/SendToPrinter.cpp index 036a60827d..8289b4e484 100644 --- a/src/slic3r/GUI/SendToPrinter.cpp +++ b/src/slic3r/GUI/SendToPrinter.cpp @@ -1509,7 +1509,7 @@ void SendToPrinterDialog::show_status(PrintDialogStatus status, std::vectorGetConfig()->SupportPrintWithoutSD() && (obj_->GetStorage()->get_sdcard_state() == DevStorage::SdcardState::NO_SDCARD)) { - error_message = _L("Storage needs to be inserted before printing."); + error_message = _L("Insert storage or free up space before printing."); return; } if (obj_->is_lan_mode_printer()) { @@ -1959,7 +1959,7 @@ void CalibUtils::send_to_print(const std::vector &calib_infos, wxStri } else if (!obj_->GetConfig()->SupportPrintWithoutSD() && (obj_->GetStorage()->get_sdcard_state() == DevStorage::SdcardState::NO_SDCARD)) { - error_message = _L("Storage needs to be inserted before printing."); + error_message = _L("Insert storage or free up space before printing."); return; } if (obj_->is_lan_mode_printer()) { diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp index 67289b85b6..c96b081f62 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp @@ -223,6 +223,7 @@ int MoonrakerPrinterAgent::connect_printer(const PrinterConnectionParams& params std::lock_guard lock(payload_mutex); status_cache = nlohmann::json::object(); } + has_storage.store(false); ws_last_emit_ms.store(0); ws_last_dispatch_ms.store(0); last_print_state.clear(); @@ -597,9 +598,8 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index, } obj->last_push_time = std::chrono::system_clock::now(); - // Set storage state - Moonraker printers use virtual_sdcard, storage is always available. - // This is required for SelectMachineDialog to allow printing (otherwise it blocks with "No SD card"). - obj->GetStorage()->set_sdcard_state(DevStorage::HAS_SDCARD_NORMAL); + // SelectMachineDialog blocks printing with "No SD card" unless the storage state is normal. + obj->GetStorage()->set_sdcard_state(has_storage.load() ? DevStorage::HAS_SDCARD_NORMAL : DevStorage::NO_SDCARD); // Populate module_vers so is_info_ready() passes the version check. // Moonraker printers don't have BBL-style version info, but we need a non-empty map. @@ -1148,56 +1148,60 @@ bool MoonrakerPrinterAgent::init_device_info(const std::string& dev_id, const st return true; } +bool MoonrakerPrinterAgent::get_json(const std::string& url, + const std::string& api_key, + const std::function& cancelled, + nlohmann::json& json, + std::string& error) const +{ + std::string response_body; + bool success = false; + std::string http_error; + + auto http = Http::get(url); + if (!api_key.empty()) { + http.header("X-Api-Key", api_key); + } + http.timeout_connect(5) + .timeout_max(10) + .on_progress(cancel_when(cancelled)) + .on_complete([&](std::string body, unsigned status) { + if (status == 200) { + response_body = body; + success = true; + } else { + http_error = "HTTP error: " + std::to_string(status); + } + }) + .on_error([&](std::string body, std::string err, unsigned status) { + http_error = err; + if (status > 0) { + http_error += " (HTTP " + std::to_string(status) + ")"; + } + }) + .perform_sync(); + + if (!success) { + error = http_error.empty() ? "Connection failed" : http_error; + return false; + } + + json = nlohmann::json::parse(response_body, nullptr, false, true); + if (json.is_discarded()) { + error = "Invalid JSON response"; + return false; + } + return true; +} + bool MoonrakerPrinterAgent::fetch_device_info(const std::string& base_url, const std::string& api_key, MoonrakerDeviceInfo& info, std::string& error, const std::function& cancelled) const { - auto fetch_json = [&](const std::string& url, nlohmann::json& out) { - std::string response_body; - bool success = false; - std::string http_error; - - auto http = Http::get(url); - if (!api_key.empty()) { - http.header("X-Api-Key", api_key); - } - http.timeout_connect(5) - .timeout_max(10) - .on_progress(cancel_when(cancelled)) - .on_complete([&](std::string body, unsigned status) { - if (status == 200) { - response_body = body; - success = true; - } else { - http_error = "HTTP error: " + std::to_string(status); - } - }) - .on_error([&](std::string body, std::string err, unsigned status) { - http_error = err; - if (status > 0) { - http_error += " (HTTP " + std::to_string(status) + ")"; - } - }) - .perform_sync(); - - if (!success) { - error = http_error.empty() ? "Connection failed" : http_error; - return false; - } - - out = nlohmann::json::parse(response_body, nullptr, false, true); - if (out.is_discarded()) { - error = "Invalid JSON response"; - return false; - } - return true; - }; - nlohmann::json json; - std::string url = join_url(base_url, "/server/info"); - if (!fetch_json(url, json)) { + if (!get_json(join_url(base_url, "/server/info"), api_key, cancelled, json, error)) { return false; } @@ -1215,43 +1219,9 @@ bool MoonrakerPrinterAgent::query_printer_status(const std::string& ba std::string& error, const std::function& cancelled) const { - std::string url = join_url(base_url, "/printer/objects/query?print_stats&virtual_sdcard&extruder&heater_bed&fan"); - - std::string response_body; - bool success = false; - std::string http_error; - - auto http = Http::get(url); - if (!api_key.empty()) { - http.header("X-Api-Key", api_key); - } - http.timeout_connect(5) - .timeout_max(10) - .on_progress(cancel_when(cancelled)) - .on_complete([&](std::string body, unsigned status_code) { - if (status_code == 200) { - response_body = body; - success = true; - } else { - http_error = "HTTP error: " + std::to_string(status_code); - } - }) - .on_error([&](std::string body, std::string err, unsigned status_code) { - http_error = err; - if (status_code > 0) { - http_error += " (HTTP " + std::to_string(status_code) + ")"; - } - }) - .perform_sync(); - - if (!success) { - error = http_error.empty() ? "Connection failed" : http_error; - return false; - } - - auto json = nlohmann::json::parse(response_body, nullptr, false, true); - if (json.is_discarded()) { - error = "Invalid JSON response"; + nlohmann::json json; + if (!get_json(join_url(base_url, "/printer/objects/query?print_stats&virtual_sdcard&extruder&heater_bed&fan"), api_key, cancelled, json, + error)) { return false; } @@ -1349,42 +1319,9 @@ bool MoonrakerPrinterAgent::fetch_object_list(const std::string& base_url, std::set& objects, std::string& error) const { - std::string response_body; - bool success = false; - std::string http_error; - - auto http = Http::get(join_url(base_url, "/printer/objects/list")); - if (!api_key.empty()) { - http.header("X-Api-Key", api_key); - } - http.timeout_connect(5) - .timeout_max(10) - // Gives up once the status stream, the only caller, stops - .on_progress(cancel_when([this] { return ws_stop.load(); })) - .on_complete([&](std::string body, unsigned status) { - if (status == 200) { - response_body = body; - success = true; - } else { - http_error = "HTTP error: " + std::to_string(status); - } - }) - .on_error([&](std::string body, std::string err, unsigned status) { - http_error = err; - if (status > 0) { - http_error += " (HTTP " + std::to_string(status) + ")"; - } - }) - .perform_sync(); - - if (!success) { - error = http_error.empty() ? "Connection failed" : http_error; - return false; - } - - auto json = nlohmann::json::parse(response_body, nullptr, false, true); - if (json.is_discarded()) { - error = "Invalid JSON response"; + nlohmann::json json; + // Gives up once the status stream, the only caller, stops + if (!get_json(join_url(base_url, "/printer/objects/list"), api_key, [this] { return ws_stop.load(); }, json, error)) { return false; } @@ -1404,6 +1341,28 @@ bool MoonrakerPrinterAgent::fetch_object_list(const std::string& base_url, return !objects.empty(); } +bool MoonrakerPrinterAgent::fetch_has_free_storage(const std::string& base_url, + const std::string& api_key, + bool& has_free, + std::string& error) const +{ + nlohmann::json json; + // Gives up once the status stream, the only caller, stops + if (!get_json(join_url(base_url, "/server/files/directory?path=gcodes"), api_key, [this] { return ws_stop.load(); }, json, error)) { + return false; + } + + const nlohmann::json& result = json.contains("result") ? json["result"] : json; + if (!result.contains("disk_usage") || !result["disk_usage"].is_object() || !result["disk_usage"].contains("free") || + !result["disk_usage"]["free"].is_number()) { + error = "No disk usage in the directory listing"; + return false; + } + + has_free = result["disk_usage"]["free"].get() > 0; + return true; +} + int MoonrakerPrinterAgent::send_version_info(const std::string& dev_id) { nlohmann::json payload; @@ -1749,6 +1708,12 @@ void MoonrakerPrinterAgent::run_status_stream(std::string dev_id, std::string ba subscribe_objects.insert("fan"); // Try to subscribe to fan as fallback } + // Queried before the subscription, so the first status push already carries the storage state + if (!ws_stop.load()) { + refresh_storage(base_url, api_key); + } + auto last_storage_check = std::chrono::steady_clock::now(); + nlohmann::json subscribe; subscribe["jsonrpc"] = "2.0"; subscribe["method"] = "printer.objects.subscribe"; @@ -1788,6 +1753,14 @@ void MoonrakerPrinterAgent::run_status_stream(std::string dev_id, std::string ba connection_lost = true; break; } + // Moonraker sends no free space updates, so they are re-read here; its proc stats arrive every second + if (last_message - last_storage_check >= timings.storage_check && !ws_stop.load()) { + last_storage_check = last_message; + // Only a status the printer has reported is re-sent + if (refresh_storage(base_url, api_key) && ws_last_emit_ms.load() != 0) { + dispatch_status(dev_id); + } + } } } catch (const std::exception& e) { if (!ws_stop.load()) { @@ -1935,14 +1908,29 @@ void MoonrakerPrinterAgent::send_heartbeat_if_due(const std::string& dev_id, std if (last_ms == 0 || now_ms - last_ms < static_cast(interval.count())) { return; } + dispatch_status(dev_id); +} +void MoonrakerPrinterAgent::dispatch_status(const std::string& dev_id) +{ nlohmann::json message; { std::lock_guard lock(payload_mutex); message = build_print_payload_locked(); } dispatch_message(dev_id, message.dump()); - ws_last_emit_ms.store(now_ms); + ws_last_emit_ms.store(steady_now_ms()); +} + +bool MoonrakerPrinterAgent::refresh_storage(const std::string& base_url, const std::string& api_key) +{ + bool has_free = false; + std::string error; + // Storage that could not be checked counts as unavailable + if (!fetch_has_free_storage(base_url, api_key, has_free, error)) { + BOOST_LOG_TRIVIAL(warning) << "MoonrakerPrinterAgent: storage query failed: " << error; + } + return has_storage.exchange(has_free) != has_free; } void MoonrakerPrinterAgent::update_status_cache(const nlohmann::json& updates) @@ -2007,10 +1995,14 @@ nlohmann::json MoonrakerPrinterAgent::build_print_payload_locked() const payload["print"]["print_error"] = 0; // Map homed axes to bit field: X=bit0, Y=bit1, Z=bit2 - // WARNING: This only sets bits 0-2, clearing support flags (bit 3+) + // WARNING: Apart from the storage state below, this clears the support flags (bit 3+) // Bit 3 = 220V voltage, bit 4 = auto recovery, etc. // This is acceptable for Moonraker (no AMS, different feature set) - int home_flag = 0; + // Every push sets the storage state twice, from "sdcard" and then from home_flag bits 8-9, + // so both must report it or the send dialog blocks. + const bool storage = has_storage.load(); + payload["print"]["sdcard"] = storage; + int home_flag = (storage ? DevStorage::HAS_SDCARD_NORMAL : DevStorage::NO_SDCARD) << 8; if (status_cache.contains("toolhead") && status_cache["toolhead"].contains("homed_axes")) { std::string homed = status_cache["toolhead"]["homed_axes"].get(); if (homed.find('X') != std::string::npos) diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp index 7159699189..1f9ea2203d 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp @@ -94,6 +94,7 @@ protected: std::chrono::milliseconds idle{std::chrono::seconds(30)}; // Silence before giving up, with a ping every half of it std::chrono::milliseconds heartbeat{std::chrono::seconds(10)}; // Silence before the cached status is sent again std::chrono::milliseconds reconnect_delay{std::chrono::seconds(1)}; // First wait, doubling per consecutive failure up to 32x + std::chrono::milliseconds storage_check{std::chrono::seconds(30)}; // How often the free space of the gcodes root is re-read } ws_timings; // Tray data for AMS payload building @@ -144,7 +145,14 @@ private: int send_version_info(const std::string& dev_id); int send_access_code(const std::string& dev_id); + // GETs a Moonraker endpoint and parses its JSON answer, giving up once `cancelled` returns true + bool get_json(const std::string& url, + const std::string& api_key, + const std::function& cancelled, + nlohmann::json& json, + std::string& error) const; bool fetch_object_list(const std::string& base_url, const std::string& api_key, std::set& objects, std::string& error) const; + bool fetch_has_free_storage(const std::string& base_url, const std::string& api_key, bool& has_free, std::string& error) const; bool query_printer_status(const std::string& base_url, const std::string& api_key, nlohmann::json& status, @@ -163,6 +171,9 @@ private: void run_status_stream(std::string dev_id, std::string base_url, std::string api_key, StatusStreamTimings timings); void handle_ws_message(const std::string& dev_id, const std::string& payload); void send_heartbeat_if_due(const std::string& dev_id, std::chrono::milliseconds interval); + void dispatch_status(const std::string& dev_id); + // Re-reads whether the gcodes root has free space, and returns whether the answer changed + bool refresh_storage(const std::string& base_url, const std::string& api_key); void update_status_cache(const nlohmann::json& updates); nlohmann::json build_print_payload_locked() const; @@ -217,6 +228,7 @@ private: std::atomic next_jsonrpc_id{1}; std::set available_objects; // Track for feature detection + std::atomic has_storage{false}; // The gcodes root has free space std::atomic ws_stop{false}; std::atomic ws_reconnect_requested{false}; // Flag to trigger reconnection diff --git a/tests/slic3rutils/test_moonraker_printer_agent.cpp b/tests/slic3rutils/test_moonraker_printer_agent.cpp index 3a831fef8a..bf60617aa0 100644 --- a/tests/slic3rutils/test_moonraker_printer_agent.cpp +++ b/tests/slic3rutils/test_moonraker_printer_agent.cpp @@ -37,6 +37,7 @@ #include #include +#include "slic3r/GUI/DeviceCore/DevStorage.h" #include "slic3r/Utils/IPrinterAgent.hpp" #include "slic3r/Utils/MoonrakerPrinterAgent.hpp" @@ -211,6 +212,13 @@ public: return m_changed.wait_for(lock, 10s, [&] { return m_close_frames >= count; }); } + // The answer to the gcodes directory listing, which reports the free space in disk_usage. Null leaves disk_usage out. + void set_gcodes_listing(nlohmann::json disk_usage) + { + std::lock_guard lock(m_mutex); + m_disk_usage = std::move(disk_usage); + } + // Hangs up every connection that is waiting. void release() { @@ -329,6 +337,16 @@ private: return; } http::response response{http::status::not_found, request.version()}; + if (request.target() == "/server/files/directory?path=gcodes") { + nlohmann::json result = {{"dirs", nlohmann::json::array()}, {"files", nlohmann::json::array()}}; + { + std::lock_guard lock(m_mutex); + if (!m_disk_usage.is_null()) + result["disk_usage"] = m_disk_usage; + } + response.result(http::status::ok); + response.body() = nlohmann::json{{"result", result}}.dump(); + } response.prepare_payload(); beast::error_code ec; http::write(stream, response, ec); @@ -412,6 +430,7 @@ private: int m_http_hung_up = 0; int m_close_frames = 0; bool m_released = false; + nlohmann::json m_disk_usage = {{"total", 8e9}, {"used", 2e9}, {"free", 6e9}}; }; // Records when the agent dispatches a status report. @@ -618,6 +637,63 @@ TEST_CASE("A callback on the stream thread can stop the status stream", "[Moonra CHECK(f.stops_within(3s)); } +TEST_CASE("Status reports tell the send dialog whether the gcodes storage has free space", "[MoonrakerPrinterAgent][StatusStream]") +{ + auto [disk_usage, has_storage] = GENERATE(table({ + {{{"total", 8e9}, {"used", 2e9}, {"free", 6e9}}, true}, + {{{"total", 8e9}, {"used", 8e9}, {"free", 0}}, false}, + {nullptr, false}, + })); + CAPTURE(disk_usage.dump()); + + std::promise first_report; + std::once_flag reported; + StreamFixture f(Behavior::AnswersPings); + f.printer.set_gcodes_listing(disk_usage); + f.agent.set_on_local_message_fn([&](std::string, std::string payload) { + std::call_once(reported, [&] { first_report.set_value(payload); }); + }); + f.start(); + + auto report = first_report.get_future(); + REQUIRE(report.wait_for(5s) == std::future_status::ready); + const nlohmann::json print = nlohmann::json::parse(report.get()).at("print"); + // MachineObject reads the storage state from "sdcard" and then again from home_flag bits 8-9. + CHECK(print.at("sdcard") == has_storage); + CHECK(((print.at("home_flag").get() >> 8) & 0x3) == (has_storage ? DevStorage::HAS_SDCARD_NORMAL : DevStorage::NO_SDCARD)); + CHECK(f.stops_within(3s)); +} + +TEST_CASE("The status stream keeps re-reading the printer's free space", "[MoonrakerPrinterAgent][StatusStream]") +{ + std::mutex mutex; + std::condition_variable changed; + std::vector storage_reports; + // Chatters sends a message every 50 ms, which the stream re-reads the free space after + StreamFixture f(Behavior::Chatters); + f.agent.ws_timings.storage_check = 100ms; + f.printer.set_gcodes_listing({{"total", 8e9}, {"used", 8e9}, {"free", 0}}); + f.agent.set_on_local_message_fn([&](std::string, std::string payload) { + std::lock_guard lock(mutex); + storage_reports.push_back(nlohmann::json::parse(payload).at("print").at("sdcard").get()); + changed.notify_all(); + }); + const auto wait_for_storage = [&](bool has_storage) { + std::unique_lock lock(mutex); + return changed.wait_for(lock, 5s, [&] { return !storage_reports.empty() && storage_reports.back() == has_storage; }); + }; + f.start(); + REQUIRE(wait_for_storage(false)); + + f.printer.set_gcodes_listing({{"total", 8e9}, {"used", 2e9}, {"free", 6e9}}); + REQUIRE(wait_for_storage(true)); + + // A listing without disk usage cannot be checked, which counts as no storage + f.printer.set_gcodes_listing(nullptr); + CHECK(wait_for_storage(false)); + CHECK(f.stops_within(3s)); +} + TEST_CASE("A quiet printer that is still up keeps reporting its status", "[MoonrakerPrinterAgent][StatusStream]") { Reports reports;