From b6ca378b23dbee409ea5f7fa9204e32d7a7a553b Mon Sep 17 00:00:00 2001 From: TheLegendTubaGuy <95944177+thelegendtubaguy@users.noreply.github.com> Date: Tue, 27 Oct 2026 10:47:06 -0500 Subject: [PATCH] Apply the print dialog's Box mapping on Qidi printers (#16723) With printer agents on, the Qidi agent now uses the Box slot picked for each filament in the print dialog. After the upload it writes `SAVE_VARIABLE VARIABLE=value_t VALUE="'slot'"` for each mapped filament, which the firmware's T macros read. Then it starts the print through `/printer/print/start`, because the Max 4, Q2, Q2C and Plus 5 only open prints from the copy that Moonraker's print start makes. - `MoonrakerPrinterAgent::start_local_print` now ends with a virtual `print_uploaded_file()`. The default still sends `SDCARD_PRINT_FILE`, so other Moonraker agents are unchanged. - Box units show as "Qidi Box 1", "Qidi Box 2". Agents can set an optional `display_name` on an AMS unit. - New agent flag `native_device_tab`. Qidi sets it to false, so its native Device and Calibration tabs are hidden and the web page becomes the Device tab. - The Moonraker agent retries its first connection with the status stream's backoff. A disconnect, a newer connection or closing the app stops the retries. - The print dialog fetches filament data itself for agents that only send it when asked, so the slot picker shows the Box units without a sidebar sync. - Agent printers show their address in the print dialog's printer list instead of "(LAN)". Bambu printers keep "(LAN)". - A single nozzle whose size the printer hasn't reported shows no size instead of "Unknown". --- docs/HLSD/printer-agent.md | 10 +++- src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp | 7 +++ src/slic3r/GUI/DeviceCore/DevFilaSystem.h | 1 + src/slic3r/GUI/MainFrame.cpp | 40 +++++++++++--- src/slic3r/GUI/Plater.cpp | 12 ++--- src/slic3r/GUI/SelectMachine.cpp | 40 +++++++++++--- src/slic3r/GUI/SelectMachine.hpp | 1 + src/slic3r/Utils/IPrinterAgent.hpp | 1 + src/slic3r/Utils/MoonrakerPrinterAgent.cpp | 39 ++++++++++---- src/slic3r/Utils/MoonrakerPrinterAgent.hpp | 16 +++--- src/slic3r/Utils/NetworkAgentFactory.cpp | 10 ++-- src/slic3r/Utils/NetworkAgentFactory.hpp | 5 +- src/slic3r/Utils/QidiPrinterAgent.cpp | 44 +++++++++++++++- src/slic3r/Utils/QidiPrinterAgent.hpp | 9 ++++ tests/slic3rutils/CMakeLists.txt | 1 + tests/slic3rutils/test_dev_mapping.cpp | 22 ++++++++ .../test_moonraker_printer_agent.cpp | 52 +++++++++++++++++++ tests/slic3rutils/test_printer_agent.cpp | 17 ++++++ tests/slic3rutils/test_qidi_printer_agent.cpp | 48 +++++++++++++++++ 19 files changed, 331 insertions(+), 44 deletions(-) create mode 100644 tests/slic3rutils/test_qidi_printer_agent.cpp diff --git a/docs/HLSD/printer-agent.md b/docs/HLSD/printer-agent.md index 7062fab966..81947f1735 100644 --- a/docs/HLSD/printer-agent.md +++ b/docs/HLSD/printer-agent.md @@ -100,8 +100,14 @@ the active printer agent because a normal LAN agent represents one physical prin ## Agent registration and selection `NetworkAgentFactory` maintains the printer-agent registry. Each registry entry contains an agent ID, -a display name, and a factory function. Built-in agents register during application initialization. -Python printer-agent capabilities register dynamically and contribute an agent ID and factory entry. +a display name, a factory function, and whether the native Device and Calibration tabs apply to the +agent's printers. Built-in agents register during application initialization. Python printer-agent +capabilities register dynamically and contribute an agent ID and factory entry. + +The tab flag is read from the registry rather than the live agent because the main window lays out its +tabs before the newly selected preset's agent is installed. It defaults to true. An agent that clears +it is one whose printers have their own web interface and nothing the Bambu-shaped Device and +Calibration tabs can show; for those printers the web Device page takes the Device tab's place. The selected printer preset contains the printer-agent choice. If no explicit choice is stored, the application preserves the existing default behavior: Bambu presets select the Bambu agent and other diff --git a/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp b/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp index 14d78fba1f..08398de843 100644 --- a/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp +++ b/src/slic3r/GUI/DeviceCore/DevFilaSystem.cpp @@ -169,6 +169,11 @@ static std::unordered_map s_ams_display_formats = { wxString DevAms::GetDisplayName() const { + if (!m_display_name.empty()) + { + return wxString::FromUTF8(m_display_name); + } + wxString ams_display_format; // GetAmsType() maps AMS_LITE_MIXED -> AMS_LITE so N9 shows the AMS-Lite name. auto iter = s_ams_display_formats.find(GetAmsType()); @@ -533,6 +538,8 @@ void DevFilaSystemParser::ParseV1_0(const json& jj, MachineObject* obj, DevFilaS /*set ams type flag*/ curr_ams->SetAmsType(type_id); + DevJsonValParser::ParseVal(*it, "display_name", curr_ams->m_display_name, std::string()); + // Refresh the switch-aware extruder binding on every push (both create and // update paths) so it can't go stale after an AMS is re-homed to another // extruder. Without the switch the set holds the single bound extruder and diff --git a/src/slic3r/GUI/DeviceCore/DevFilaSystem.h b/src/slic3r/GUI/DeviceCore/DevFilaSystem.h index b843eba4b3..b8b8ad8cc2 100644 --- a/src/slic3r/GUI/DeviceCore/DevFilaSystem.h +++ b/src/slic3r/GUI/DeviceCore/DevFilaSystem.h @@ -269,6 +269,7 @@ public: private: AmsType m_ams_type = AmsType::AMS; std::string m_ams_id; + std::string m_display_name; // Orca: set by printer agents for their own units, replaces the type-based name int m_ext_id;//extruder id // Orca: pull-mode / multi-vendor agent model — keeps the legacy single m_ext_id for existing // consumers and carries the switch-aware binding alongside it. Without a Filament Track Switch diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index e1e4ec06bd..549b991302 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -1654,6 +1654,14 @@ void MainFrame::show_device(bool should_use_native) { // get it — otherwise a Bambu user sees two Device tabs, one of them permanently empty. const bool want_web_device_tab = use_printer_agents && wxGetApp().preset_bundle != nullptr && !wxGetApp().preset_bundle->use_bbl_device_tab(); + // An agent whose printers have nothing for the native Device and Calibration tabs leaves the web page as the only Device tab + bool want_native_device_tabs = true; + if (want_web_device_tab) { + const std::string agent_id = wxGetApp().resolve_printer_agent_id( + wxGetApp().preset_bundle->printers.get_edited_preset().config.opt_string("printer_agent")); + const PrinterAgentInfo* agent_info = NetworkAgentFactory::get_printer_agent_info(agent_id); + want_native_device_tabs = agent_info == nullptr || agent_info->native_device_tab; + } // Remove the extra page before switching to any layout that shouldn't have it. if (!want_web_device_tab) { @@ -1664,7 +1672,16 @@ void MainFrame::show_device(bool should_use_native) { } if (use_printer_agents) { - if (!m_monitor_page->in_book()) { + if (!want_native_device_tabs) { + if ((idx = m_tabpanel->FindPage(m_monitor_page)) != wxNOT_FOUND) { + m_monitor_page->Show(false); + m_tabpanel->RemovePage(idx); + } + if ((idx = m_tabpanel->FindPage(m_calibration_page)) != wxNOT_FOUND) { + m_calibration_page->Show(false); + m_tabpanel->RemovePage(idx); + } + } else if (!m_monitor_page->in_book()) { if ((idx = m_tabpanel->FindPage(m_printer_view_page)) != wxNOT_FOUND) { m_printer_view_page->Show(false); m_tabpanel->RemovePage(idx); @@ -1684,20 +1701,29 @@ void MainFrame::show_device(bool should_use_native) { TAB_ID_MULTI_DEVICE, m_multi_machine_page, _L("Multi-device"), "tab_multi_active"); } } - if (!m_calibration_page->in_book()) { + if (want_native_device_tabs && !m_calibration_page->in_book()) { m_calibration_page->Show(false); m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_PROJECT}), TAB_ID_CALIBRATION, m_calibration_page, _L("Calibration"), "tab_calibration_active"); } if (want_web_device_tab) { - if ((idx = m_tabpanel->FindPage(m_printer_view_page)) == wxNOT_FOUND) { + // Without the native Device tab the web page takes its id, so every way to the Device tab leads here + const char* id = want_native_device_tabs ? TAB_ID_MONITOR_WEB : TAB_ID_MONITOR; + const wxString label = want_native_device_tabs ? _L("Device (Web)") : _L("Device"); + idx = m_tabpanel->FindPage(m_printer_view_page); + if (idx != wxNOT_FOUND && m_tabpanel->FindPageByName(id) != idx) { m_printer_view_page->Show(false); - // Immediately right of the native Device tab, not at the end of the tab bar. - m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_MONITOR}), TAB_ID_MONITOR_WEB, - m_printer_view_page, _L("Device (Web)"), "tab_monitor_active"); + m_tabpanel->RemovePage(idx); + idx = wxNOT_FOUND; + } + if (idx == wxNOT_FOUND) { + m_printer_view_page->Show(false); + // Immediately right of the native Device tab, or of Preview without it, not at the end of the tab bar. + m_tabpanel->InsertPage(m_tabpanel->PositionAfter({TAB_ID_MONITOR, TAB_ID_PREVIEW}), id, m_printer_view_page, label, + "tab_monitor_active"); } else { - m_tabpanel->SetPageText(idx, _L("Device (Web)")); + m_tabpanel->SetPageText(idx, label); } } diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index e8df816036..debd545a03 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -13892,7 +13892,12 @@ void Plater::priv::on_tab_selection_changing(wxBookCtrlEvent& e) const bool use_printer_agents = wxGetApp().app_config->get_bool("use_printer_agents"); const bool use_native_device_tab = wxGetApp().preset_bundle && (wxGetApp().preset_bundle->use_bbl_device_tab() || use_printer_agents); - if (use_native_device_tab && new_name == TAB_ID_MONITOR) { + // Pointer test, not a name lookup: in printer-agents mode this page is TAB_ID_MONITOR_WEB + // while the native Device tab holds TAB_ID_MONITOR, and in legacy-web mode, or for an agent + // without the native tab, it holds TAB_ID_MONITOR itself. + const bool selecting_web_device_tab = main_frame->m_printer_view_page && + main_frame->m_tabpanel->GetPage(new_sel) == main_frame->m_printer_view_page; + if (use_native_device_tab && new_name == TAB_ID_MONITOR && !selecting_web_device_tab) { // BBL network module is only required for BBL-vendor printers. // Non-BBL Python plugins (e.g. moonraker) drive the Device tab without it. if (!use_printer_agents && wxGetApp().preset_bundle->is_bbl_vendor() && !Slic3r::NetworkAgent::is_network_module_loaded()) { @@ -13904,11 +13909,6 @@ void Plater::priv::on_tab_selection_changing(wxBookCtrlEvent& e) } } } else { - // Pointer test, not a name lookup: in printer-agents mode this page is TAB_ID_MONITOR_WEB - // while the native Device tab holds TAB_ID_MONITOR, and in legacy-web mode it holds - // TAB_ID_MONITOR itself. - const bool selecting_web_device_tab = main_frame->m_printer_view_page && - main_frame->m_tabpanel->GetPage(new_sel) == main_frame->m_printer_view_page; if (selecting_web_device_tab) { // Use the selected discovered machine when the preset has no host. main_frame->load_printer_url(); diff --git a/src/slic3r/GUI/SelectMachine.cpp b/src/slic3r/GUI/SelectMachine.cpp index 26441baf37..50c144bfa1 100644 --- a/src/slic3r/GUI/SelectMachine.cpp +++ b/src/slic3r/GUI/SelectMachine.cpp @@ -130,7 +130,9 @@ #include "slic3r/GUI/Tabbook.hpp" #include "slic3r/GUI/Widgets/ComboBox.hpp" #include "slic3r/GUI/Widgets/PopupWindow.hpp" +#include "slic3r/Utils/IPrinterAgent.hpp" #include "slic3r/Utils/NetworkAgent.hpp" +#include "slic3r/Utils/NetworkAgentFactory.hpp" #include using json = nlohmann::json; @@ -181,6 +183,16 @@ std::string get_nozzle_volume_type_cloud_string(NozzleVolumeType nozzle_volume_t // Throttle so the rack print-dispatch nozzle-mapping request isn't re-sent on every status poll. static int s_nozzle_mapping_last_request_time = 0; +// Printer agents name a printer after its model, so two printers of one model are told apart by their address. +static wxString get_shown_printer_name(const MachineObject* obj) +{ + const wxString name = wxString::FromUTF8(obj->get_dev_name()); + if (!obj->printer_agent_id.empty() && obj->printer_agent_id != BBL_PRINTER_AGENT_ID && !obj->get_dev_ip().empty() && + obj->get_dev_ip() != obj->get_dev_name()) + return name + " (" + wxString::FromUTF8(obj->get_dev_ip()) + ")"; + return obj->is_lan_mode_printer() ? name + _L("(LAN)") : name; +} + std::vector SelectMachineDialog::MACHINE_BED_TYPE_STRING; std::vector SelectMachineDialog::MachineBedTypeString; void SelectMachineDialog::init_machine_bed_types() @@ -946,7 +958,7 @@ void SelectMachineDialog::init_bind() if (!obj) return; if (obj->get_dev_id() == e.GetString()) { - m_printer_box->SetPrinterName(wxString::FromUTF8(obj->get_dev_name()) + _L("(LAN)")); + m_printer_box->SetPrinterName(get_shown_printer_name(obj)); } } }); @@ -3859,6 +3871,7 @@ void SelectMachineDialog::on_refresh(wxCommandEvent &event) { BOOST_LOG_TRIVIAL(info) << "m_printer_last_select: on_refresh"; show_status(PrintDialogStatus::PrintStatusRefreshingMachineList); + m_pull_filament_pending = true; update_user_machine_list(); } @@ -4288,6 +4301,7 @@ void SelectMachineDialog::on_selection_changed(wxCommandEvent &event) // Has changed machine unrecoverably m_check_flag = false; + m_pull_filament_pending = true; } else { BOOST_LOG_TRIVIAL(error) << "on_selection_changed dev_id not found"; return; @@ -4810,6 +4824,18 @@ void SelectMachineDialog::update_show_status(MachineObject* obj_) reset_timeout(); + // Orca: pull-mode agents only refresh their filament data when asked, so ask before the mapping uses it + if (m_pull_filament_pending) { + m_pull_filament_pending = false; + if (agent->get_filament_sync_mode() == FilamentSyncMode::pull) { + wxBusyCursor busy; + if (agent->fetch_filament_info(obj_->get_dev_id())) { + m_ams_mapping_result.clear(); + m_check_flag = false; + } + } + } + /*check print all*/ if (!obj_->GetConfig()->SupportPrintAllPlates() && m_print_plate_idx == PLATE_ALL_IDX) { @@ -6441,6 +6467,7 @@ bool SelectMachineDialog::Show(bool show) void SelectMachineDialog::show_init() { m_ams_mapping_result.clear(); + m_pull_filament_pending = true; } SelectMachineDialog::~SelectMachineDialog() @@ -7042,7 +7069,9 @@ static wxString _get_tips(MachineObject* obj_) wxString ext_diameter; if (obj_->GetExtderSystem()->GetTotalExtderCount() == 1) { - ext_diameter += format_nozzle_diameter(obj_->GetExtderSystem()->GetNozzleDiameter(0)); + // A nozzle the printer hasn't reported shows no size rather than "Unknown" + if (const float diameter = obj_->GetExtderSystem()->GetNozzleDiameter(0); diameter > 0.0f) + ext_diameter += format_nozzle_diameter(diameter); } else if (obj_->GetExtderSystem()->GetTotalExtderCount() == 2) { ext_diameter += format_nozzle_diameter(obj_->GetExtderSystem()->GetNozzleDiameter(1));//Left ext_diameter += "/"; @@ -7066,13 +7095,8 @@ void PrinterInfoBox::SetPrinters(const std::vector& sorted_print std::vector drop_items; for (MachineObject* obj : sorted_printers) { - wxString shown_dev_name = wxString::FromUTF8(obj->get_dev_name()); - if (obj->is_lan_mode_printer()) { - shown_dev_name += _L("(LAN)"); - } - DropDown::Item drop_item; - drop_item.text = shown_dev_name; + drop_item.text = get_shown_printer_name(obj); drop_item.text_static_tips = _get_tips(obj); // update image diff --git a/src/slic3r/GUI/SelectMachine.hpp b/src/slic3r/GUI/SelectMachine.hpp index 30ca78130c..7d943a7832 100644 --- a/src/slic3r/GUI/SelectMachine.hpp +++ b/src/slic3r/GUI/SelectMachine.hpp @@ -323,6 +323,7 @@ private: bool m_is_canceled{ false }; bool m_is_rename_mode{ false }; bool m_check_flag {false}; + bool m_pull_filament_pending{false}; bool m_ext_change_assist{ false }; PrintPageMode m_print_page_mode{PrintPageMode::PrintPageModePrepare}; std::string m_print_error_msg; diff --git a/src/slic3r/Utils/IPrinterAgent.hpp b/src/slic3r/Utils/IPrinterAgent.hpp index 293b0af2b8..16d31092b9 100644 --- a/src/slic3r/Utils/IPrinterAgent.hpp +++ b/src/slic3r/Utils/IPrinterAgent.hpp @@ -32,6 +32,7 @@ struct AgentInfo { std::string name; ///< Human-readable agent name, e.g. "Orca", "Bambu Lab" std::string version; ///< Agent version string, e.g. "1.0.0" std::string description; ///< Brief description of the agent's capabilities, e.g. "Orca printer agent" + bool native_device_tab = true; ///< False when the native Device and Calibration tabs don't apply to the agent's printers }; struct PrinterConnectionParams diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp index c96b081f62..37503b1338 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp @@ -403,11 +403,9 @@ int MoonrakerPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusF return BAMBU_NETWORK_ERR_CANCELED; } - // Start print via gcode script (simpler than JSON-RPC) if (update_fn) update_fn(PrintingStageSending, 0, _u8L("Starting print...")); - std::string gcode = "SDCARD_PRINT_FILE FILENAME=" + upload_filename; - if (!send_gcode_sync(device_info.dev_id, gcode)) { + if (!print_uploaded_file(params, upload_filename)) { return BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED; } @@ -416,6 +414,12 @@ int MoonrakerPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusF return BAMBU_NETWORK_SUCCESS; } +bool MoonrakerPrinterAgent::print_uploaded_file(const PrintParams& /*params*/, const std::string& filename) +{ + // Start print via gcode script (simpler than JSON-RPC) + return send_gcode_sync(device_info.dev_id, "SDCARD_PRINT_FILE FILENAME=" + filename); +} + int MoonrakerPrinterAgent::start_sdcard_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) { (void) params; @@ -509,6 +513,9 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index, nlohmann::json ams_unit = nlohmann::json::object(); ams_unit["id"] = std::to_string(ams_id); ams_unit["info"] = "0002"; // treat as AMS_LITE + if (const std::string name = ams_unit_name(ams_id); !name.empty()) { + ams_unit["display_name"] = name; + } nlohmann::json tray_array = nlohmann::json::array(); int max_slot_in_this_ams = std::min(3, max_lane_index - ams_id * 4); @@ -2257,7 +2264,8 @@ bool MoonrakerPrinterAgent::send_jsonrpc_command(const std::string& base_url, http.header("Content-Type", "application/json") .set_post_body(request_str) .timeout_connect(5) - .timeout_max(10) + // Some firmware, like Qidi's, copies the file before starting the print and only answers afterwards + .timeout_max(60) .on_complete([&](std::string body, unsigned status) { if (status == 200) { response = body; @@ -2289,14 +2297,25 @@ void MoonrakerPrinterAgent::perform_connection_async(const std::string& dev_id, } try { + // Nothing else retries the connection, so retry with the status stream's backoff until superseded: the printer + // may still be starting, and on macOS the first attempt has been seen refused while the app's Local Network + // access is checked MoonrakerDeviceInfo fetched_info; - if (!fetch_device_info(base_url, api_key, fetched_info, error_msg, is_stale)) { - if (!is_stale()) { - BOOST_LOG_TRIVIAL(error) << "MoonrakerPrinterAgent: Failed to fetch server info: " << error_msg; + for (int attempt = 0; !fetch_device_info(base_url, api_key, fetched_info, error_msg, is_stale); ++attempt) { + if (is_stale()) { + return; + } + const auto delay = ws_timings.reconnect_delay * (1 << std::min(attempt, 5)); + BOOST_LOG_TRIVIAL(warning) << "MoonrakerPrinterAgent: Failed to fetch server info: " << error_msg << ", retrying in " + << delay.count() << "ms"; + // Short steps, so a disconnect or the destructor does not wait out the delay + const auto step = std::chrono::milliseconds(50); + for (auto waited = std::chrono::milliseconds(0); waited < delay && !is_stale(); waited += step) { + std::this_thread::sleep_for(step); + } + if (is_stale()) { + return; } - // Orca todo: revist here, for now don't send error, this is set current MachineObject to null - // dispatch_local_connect(ConnectStatusFailed, dev_id, "server_info_failed"); - return; } // Commit fetched info back to device_info under lock, only if still current diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp index 1f9ea2203d..fd322d531e 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp @@ -86,7 +86,8 @@ protected: bool use_ssl = false; } device_info; - // Copied when the stream starts, so changes apply to the next start_status_stream() + // Copied when the stream starts, so changes apply to the next start_status_stream(). A connection's retries read + // reconnect_delay directly. struct StatusStreamTimings { std::chrono::milliseconds handshake{std::chrono::seconds(10)}; // Opening and closing handshakes @@ -113,6 +114,8 @@ protected: // Build ams JSON and call parser void build_ams_payload(int ams_count, int max_lane_index, const std::vector& trays); + // Name shown for a filament unit, or empty for the AMS Lite name + virtual std::string ams_unit_name(int /*ams_id*/) const { return {}; } // Methods that derived classes may need to override or access virtual bool init_device_info(const std::string& dev_id, const std::string& dev_ip, const std::string& username, const std::string& password, bool use_ssl, const std::string& port); @@ -122,6 +125,8 @@ protected: MoonrakerDeviceInfo& info, std::string& error, const std::function& cancelled) const; + // Starts the print of a file already uploaded to the gcodes root + virtual bool print_uploaded_file(const PrintParams& params, const std::string& filename); void start_status_stream(const std::string& dev_id, const std::string& base_url, const std::string& api_key); void stop_status_stream(); @@ -133,6 +138,10 @@ protected: std::string normalize_base_url(bool use_ssl, const std::string& host, const std::string& port); std::string sanitize_filename(const std::string& filename); std::string join_url(const std::string& base_url, const std::string& path) const; + bool send_gcode_sync(const std::string& dev_id, const std::string& gcode) const; + // Posts the request to /printer/print/start + bool send_jsonrpc_command(const std::string& base_url, const std::string& api_key, + const nlohmann::json& request, std::string& response) const; // Trim whitespace and convert to uppercase static std::string trim_and_upper(const std::string& input); @@ -158,7 +167,6 @@ private: nlohmann::json& status, std::string& error, const std::function& cancelled) const; - bool send_gcode_sync(const std::string& dev_id, const std::string& gcode) const; void send_gcode_async(const std::string& dev_id, const std::string& gcode, std::function on_result = {}) const; @@ -187,10 +195,6 @@ private: const std::string& base_url, const std::string& api_key, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn); - // JSON-RPC helper - bool send_jsonrpc_command(const std::string& base_url, const std::string& api_key, - const nlohmann::json& request, std::string& response) const; - // Connection thread management void perform_connection_async(const std::string& dev_id, const std::string& base_url, diff --git a/src/slic3r/Utils/NetworkAgentFactory.cpp b/src/slic3r/Utils/NetworkAgentFactory.cpp index 7f59dc7573..09d01792e8 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.cpp +++ b/src/slic3r/Utils/NetworkAgentFactory.cpp @@ -76,16 +76,20 @@ template void register_agent() if (cloud_agent) agent->set_cloud_agent(cloud_agent); return agent; - }); + }, + info.native_device_tab); } } // anonymous namespace -bool NetworkAgentFactory::register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory) +bool NetworkAgentFactory::register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory, + bool native_device_tab) { std::lock_guard lock(s_registry_mutex); auto& agents = get_printer_agents(); - return agents.emplace(id, PrinterAgentInfo(id, display_name, std::move(factory))).second; + PrinterAgentInfo info(id, display_name, std::move(factory)); + info.native_device_tab = native_device_tab; + return agents.emplace(id, std::move(info)).second; } bool NetworkAgentFactory::is_printer_agent_registered(const std::string& id) diff --git a/src/slic3r/Utils/NetworkAgentFactory.hpp b/src/slic3r/Utils/NetworkAgentFactory.hpp index ea2758618a..cb8a82e81e 100644 --- a/src/slic3r/Utils/NetworkAgentFactory.hpp +++ b/src/slic3r/Utils/NetworkAgentFactory.hpp @@ -31,6 +31,7 @@ struct PrinterAgentInfo std::string display_name; // e.g., "Orca Native", "Bambu Lab" std::string plugin_identifier; // Empty for built-ins, otherwise ;; PrinterAgentFactory factory; // Function to create the agent + bool native_device_tab = true; // See AgentInfo::native_device_tab bool is_plugin() const { return !plugin_identifier.empty(); } PrinterAgentInfo(const std::string& id_, const std::string& display_name_, PrinterAgentFactory factory_) @@ -84,9 +85,11 @@ public: * @param id Unique identifier for the agent (e.g., "orca", "bbl") * @param display_name Human-readable name for UI * @param factory Factory function to create the agent + * @param native_device_tab Whether the native Device and Calibration tabs apply to the agent's printers * @return true if registration succeeded, false if already registered */ - static bool register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory); + static bool register_printer_agent(const std::string& id, const std::string& display_name, PrinterAgentFactory factory, + bool native_device_tab = true); /** * Check if an agent registry/config key is registered diff --git a/src/slic3r/Utils/QidiPrinterAgent.cpp b/src/slic3r/Utils/QidiPrinterAgent.cpp index 9b3c8a7cb7..1c4799c68a 100644 --- a/src/slic3r/Utils/QidiPrinterAgent.cpp +++ b/src/slic3r/Utils/QidiPrinterAgent.cpp @@ -2,6 +2,7 @@ #include "Http.hpp" #include "MoonrakerPrinterAgent.hpp" #include "IPrinterAgent.hpp" +#include "bambu_networking.hpp" #include "libslic3r/PresetBundle.hpp" #include "slic3r/GUI/GUI_App.hpp" @@ -44,7 +45,8 @@ QidiPrinterAgent::QidiPrinterAgent(std::string log_dir) : MoonrakerPrinterAgent( AgentInfo QidiPrinterAgent::get_agent_info_static() { - return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"}; + // The native Device and Calibration tabs have nothing to show for Qidi printers yet, so Fluidd's web Device tab is the only one + return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent", false}; } bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/) @@ -90,6 +92,46 @@ bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode return true; } +std::string QidiPrinterAgent::build_tool_slot_script(const std::string& ams_mapping) +{ + // The firmware has value_t0 to value_t15 and slots 0 to 15 + constexpr int slot_count = 16; + + // One entry per filament: its Box slot index, negative when no slot was chosen + const auto mapping = nlohmann::json::parse(ams_mapping, nullptr, false); + std::string script; + if (!mapping.is_array()) { + return script; + } + for (int filament = 0; filament < int(mapping.size()) && filament < slot_count; ++filament) { + if (!mapping[filament].is_number_integer()) { + continue; + } + const int slot = mapping[filament].get(); + if (slot < 0 || slot >= slot_count) { + continue; + } + if (!script.empty()) { + script += '\n'; + } + // SAVE_VARIABLE reads VALUE as a Python literal, so the slot name keeps its own quotes + script += "SAVE_VARIABLE VARIABLE=value_t" + std::to_string(filament) + " VALUE=\"'slot" + std::to_string(slot) + "'\""; + } + return script; +} + +bool QidiPrinterAgent::print_uploaded_file(const PrintParams& params, const std::string& filename) +{ + const std::string script = build_tool_slot_script(params.ams_mapping); + if (!script.empty() && !send_gcode_sync(device_info.dev_id, script)) { + return false; + } + + // On the X-Max 4 and Q2, Klipper only opens the copy Moonraker's print start makes, so SDCARD_PRINT_FILE can't find the upload + std::string response; + return send_jsonrpc_command(device_info.base_url, device_info.api_key, {{"filename", filename}}, response); +} + bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url, const std::string& api_key, const QidiFilamentDict& dict, diff --git a/src/slic3r/Utils/QidiPrinterAgent.hpp b/src/slic3r/Utils/QidiPrinterAgent.hpp index 5f4cfc3a7e..ec729da909 100644 --- a/src/slic3r/Utils/QidiPrinterAgent.hpp +++ b/src/slic3r/Utils/QidiPrinterAgent.hpp @@ -3,6 +3,7 @@ #include "IPrinterAgent.hpp" #include "MoonrakerPrinterAgent.hpp" +#include "bambu_networking.hpp" #include #include @@ -22,6 +23,14 @@ public: // Override filament sync (Qidi-specific implementation) bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; + // Builds the SAVE_VARIABLE lines that make each T macro load the Box slot picked for filament n + static std::string build_tool_slot_script(const std::string& ams_mapping); + +protected: + // Saves the Box slot picked for each filament in the print dialog, then starts the print through Moonraker + bool print_uploaded_file(const PrintParams& params, const std::string& filename) override; + std::string ams_unit_name(int ams_id) const override { return "Qidi Box " + std::to_string(ams_id + 1); } + private: struct QidiFilamentDict { diff --git a/tests/slic3rutils/CMakeLists.txt b/tests/slic3rutils/CMakeLists.txt index a05426e05f..118ec3205a 100644 --- a/tests/slic3rutils/CMakeLists.txt +++ b/tests/slic3rutils/CMakeLists.txt @@ -36,6 +36,7 @@ add_executable(${_TEST_NAME}_tests test_plugin_capabilities_in_use.cpp test_plugin_status.cpp test_printer_agent.cpp + test_qidi_printer_agent.cpp test_plugin_install.cpp test_plugin_lifecycle.cpp test_plugin_resource_texture.cpp diff --git a/tests/slic3rutils/test_dev_mapping.cpp b/tests/slic3rutils/test_dev_mapping.cpp index 9d9d1a7e2a..6f32e32b51 100644 --- a/tests/slic3rutils/test_dev_mapping.cpp +++ b/tests/slic3rutils/test_dev_mapping.cpp @@ -65,6 +65,28 @@ TEST_CASE("AMS tray placeholder state follows the latest status", "[DevFilaSyste CHECK_FALSE(tray->is_slot_placeholder); } +TEST_CASE("An AMS unit is shown under the name its status gives it", "[DevFilaSystem]") +{ + MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1"); + + const json named = json::parse(R"({ + "ams": { "ams": [ { "id": "0", "info": "00000001", "display_name": "Qidi Box 1", "tray": [] } ] } + })"); + DevFilaSystemParser::ParseV1_0(named, &obj, obj.GetFilaSystem().get(), false); + + DevAms* ams = obj.GetFilaSystem()->GetAmsById("0"); + REQUIRE(ams != nullptr); + CHECK(ams->GetDisplayName().ToStdString() == "Qidi Box 1"); + + // Without a name the unit falls back to its type: an AMS (info type 1) with id 0 is AMS-1 + const json unnamed = json::parse(R"({ + "ams": { "ams": [ { "id": "0", "info": "00000001", "tray": [] } ] } + })"); + DevFilaSystemParser::ParseV1_0(unnamed, &obj, obj.GetFilaSystem().get(), false); + + CHECK(ams->GetDisplayName().ToStdString() == "AMS-1"); +} + TEST_CASE("Switch-bound AMS trays map to the left extruder", "[DevMapping]") { MachineObject obj(nullptr, nullptr, "test", "test_dev", "127.0.0.1"); diff --git a/tests/slic3rutils/test_moonraker_printer_agent.cpp b/tests/slic3rutils/test_moonraker_printer_agent.cpp index bf60617aa0..4bdd741db3 100644 --- a/tests/slic3rutils/test_moonraker_printer_agent.cpp +++ b/tests/slic3rutils/test_moonraker_printer_agent.cpp @@ -139,6 +139,29 @@ protected: } }; +// Fails its first `refusals` device info queries, as when macOS refuses the app's first local network connections. +class RefusedAgent : public StreamAgent +{ +public: + using StreamAgent::StreamAgent; + int refusals = 0; + mutable std::atomic fetches{0}; + +protected: + bool fetch_device_info(const std::string& base_url, + const std::string& api_key, + MoonrakerDeviceInfo& info, + std::string& error, + const std::function& cancelled) const override + { + if (++fetches <= refusals) { + error = "Couldn't connect to server"; + return false; + } + return StreamAgent::fetch_device_info(base_url, api_key, info, error, cancelled); + } +}; + enum class Behavior { SilentBeforeHandshake, // Accepts the connection and never answers Silent, // Completes the upgrade, then never reads or sends @@ -785,3 +808,32 @@ TEST_CASE("Destroying the agent stops a stalled status query", "[MoonrakerPrinte // The stalled query sees the change within 1 s of curl progress. CHECK(destroys_within(agent, 2s)); } + +TEST_CASE("A connection the printer refuses at first is retried", "[MoonrakerPrinterAgent][Connect]") +{ + FakePrinter printer(Behavior::AnswersPings); + RefusedAgent agent(""); + agent.refusals = 2; + agent.ws_timings.reconnect_delay = 10ms; + agent.connect_printer(connection_to(printer)); + + // The status stream starts only once a device info query succeeds. + CHECK(printer.wait_for_ready_connections(1)); + CHECK(agent.fetches == 3); + printer.release(); +} + +TEST_CASE("Destroying the agent does not wait out a connection retry's delay", "[MoonrakerPrinterAgent][Connect]") +{ + FakePrinter printer(Behavior::AnswersPings); + auto agent = std::make_unique(""); + agent->refusals = 1; + agent->ws_timings.reconnect_delay = 10s; + agent->connect_printer(connection_to(printer)); + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (agent->fetches == 0 && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(10ms); + REQUIRE(agent->fetches == 1); + + CHECK(destroys_within(agent, 1s)); +} diff --git a/tests/slic3rutils/test_printer_agent.cpp b/tests/slic3rutils/test_printer_agent.cpp index ac4140284c..62379de103 100644 --- a/tests/slic3rutils/test_printer_agent.cpp +++ b/tests/slic3rutils/test_printer_agent.cpp @@ -57,6 +57,23 @@ TEST_CASE("unit: printer-agent registry register / lookup / duplicate-reject", " CHECK(count == 1); } +TEST_CASE("The registry records whether the native Device tab applies to an agent", "[registry][unit]") +{ + // why: ids unique to this case, as the registry is process-global + auto stub_factory = [](std::shared_ptr, const std::string&) + -> std::shared_ptr { return nullptr; }; + + REQUIRE(NetworkAgentFactory::register_printer_agent("orca-test::native-tab-default-2c91", "Default", stub_factory)); + REQUIRE(NetworkAgentFactory::register_printer_agent("orca-test::native-tab-off-2c91", "Web only", stub_factory, false)); + + const PrinterAgentInfo* with_tab = NetworkAgentFactory::get_printer_agent_info("orca-test::native-tab-default-2c91"); + const PrinterAgentInfo* web_only = NetworkAgentFactory::get_printer_agent_info("orca-test::native-tab-off-2c91"); + REQUIRE(with_tab != nullptr); + REQUIRE(web_only != nullptr); + CHECK(with_tab->native_device_tab); + CHECK_FALSE(web_only->native_device_tab); +} + // =========================================================================== // INTEGRATION - the orca.printer_agent Python binding surface. // Boots the embedded interpreter and asserts the C++ to Python contract that diff --git a/tests/slic3rutils/test_qidi_printer_agent.cpp b/tests/slic3rutils/test_qidi_printer_agent.cpp new file mode 100644 index 0000000000..ee5bb4b575 --- /dev/null +++ b/tests/slic3rutils/test_qidi_printer_agent.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +#include + +#include "slic3r/Utils/QidiPrinterAgent.hpp" + +using namespace Slic3r; + +TEST_CASE("A filament mapped to a Box slot saves that slot in its tool variable", "[QidiPrinterAgent]") +{ + // Filament 2 is mapped to slot 5; filaments 0 and 1 have no slot. + // SAVE_VARIABLE reads VALUE as a Python literal, so the slot name needs its own quotes. + CHECK(QidiPrinterAgent::build_tool_slot_script("[-1, -1, 5]") == "SAVE_VARIABLE VARIABLE=value_t2 VALUE=\"'slot5'\""); +} + +TEST_CASE("Each mapped filament gets its own tool variable line", "[QidiPrinterAgent]") +{ + CHECK(QidiPrinterAgent::build_tool_slot_script("[3, -1, 0]") == + "SAVE_VARIABLE VARIABLE=value_t0 VALUE=\"'slot3'\"\n" + "SAVE_VARIABLE VARIABLE=value_t2 VALUE=\"'slot0'\""); +} + +TEST_CASE("A mapping without a usable Box slot saves nothing", "[QidiPrinterAgent]") +{ + const std::string mapping = GENERATE(as{}, + "", // empty mapping + "[]", // no filaments + "[-1, -1]", // no filament has a slot + "[16]", // past the firmware's slot15 + "[\"slot1\"]", // not a slot index + "{\"0\": 1}", // not an array + "[1,"); // not valid JSON + CAPTURE(mapping); + CHECK(QidiPrinterAgent::build_tool_slot_script(mapping).empty()); +} + +TEST_CASE("Filaments past the firmware's last tool variable are skipped", "[QidiPrinterAgent]") +{ + // The firmware has value_t0 to value_t15: filament 15 maps to slot 1, filament 16 to slot 4. + std::string mapping = "["; + for (int filament = 0; filament < 15; ++filament) + mapping += "-1, "; + mapping += "1, 4]"; + + CHECK(QidiPrinterAgent::build_tool_slot_script(mapping) == "SAVE_VARIABLE VARIABLE=value_t15 VALUE=\"'slot1'\""); +}