From d67e0d8dc46cef66598c34eb40253fe66ea291b7 Mon Sep 17 00:00:00 2001 From: Rui Valim Date: Wed, 28 Oct 2026 10:50:51 -0300 Subject: [PATCH] Fix Creality Hi CFS filament sync over Moonraker (#15857) The Creality Hi runs Moonraker but reports its CFS in the `box` printer object, which the Moonraker agent didn't read, so filament sync found no slots. The agent now queries `box` when it finds no lane data or Happy Hare, and the parser lives in `Utils/CrealityCfs.cpp`. Creality material IDs map to filament types, with the K2 family's `same_material` list as a fallback for branded spools. `update_filament_multi_color()` no longer stops at the first slot without a multi-colour list. It uses the slot's own colour instead, so the list stays aligned with the filament list and selecting a later filament no longer writes past its end. The CrealityPrintAgent fallback no longer syncs a preset of a different material when no base preset of the reported type exists. The K2 Plus `same_material` fallback is from mattjanus. Co-authored-by: mattjanus <18539984+mattjanus@users.noreply.github.com> --- src/libslic3r/PresetBundle.cpp | 9 +- src/slic3r/CMakeLists.txt | 2 + src/slic3r/Utils/CrealityCfs.cpp | 89 ++++++++++++++++++ src/slic3r/Utils/CrealityCfs.hpp | 19 ++++ src/slic3r/Utils/CrealityPrintAgent.cpp | 12 ++- src/slic3r/Utils/MoonrakerPrinterAgent.cpp | 50 +++++++++- src/slic3r/Utils/MoonrakerPrinterAgent.hpp | 12 ++- .../libslic3r/test_preset_bundle_loading.cpp | 39 ++++++++ tests/slic3rutils/test_creality_cfs_match.cpp | 94 +++++++++++++++++++ 9 files changed, 313 insertions(+), 13 deletions(-) create mode 100644 src/slic3r/Utils/CrealityCfs.cpp create mode 100644 src/slic3r/Utils/CrealityCfs.hpp diff --git a/src/libslic3r/PresetBundle.cpp b/src/libslic3r/PresetBundle.cpp index 58afa7d344..0f25f5d15d 100644 --- a/src/libslic3r/PresetBundle.cpp +++ b/src/libslic3r/PresetBundle.cpp @@ -5067,9 +5067,16 @@ unsigned int PresetBundle::sync_ams_list(std::vector("filament_colour")->values; std::vector exsit_multi_colors; for (auto &fil_item : ams_multi_color_filment){ - if (fil_item.empty()) break; + // Orca: placeholder slots that sync_ams_list() pushes as {} carry no multi-colour list. + // Fall back to the slot's own colour so the list stays aligned with filament_colour. + if (fil_item.empty()) { + const size_t idx = exsit_multi_colors.size(); + exsit_multi_colors.push_back(idx < single_colors.size() ? single_colors[idx] : std::string()); + continue; + } if (fil_item.size() == 1) exsit_multi_colors.push_back(fil_item[0]); else { diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 5df86e4f1e..165cef3f91 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -750,6 +750,8 @@ set(SLIC3R_GUI_SOURCES Utils/CloudDeleteQueue.hpp Utils/ColorSpaceConvert.cpp Utils/ColorSpaceConvert.hpp + Utils/CrealityCfs.cpp + Utils/CrealityCfs.hpp Utils/CrealityPrint.cpp Utils/CrealityPrint.hpp Utils/CrealityPrintAgent.cpp diff --git a/src/slic3r/Utils/CrealityCfs.cpp b/src/slic3r/Utils/CrealityCfs.cpp new file mode 100644 index 0000000000..219819b547 --- /dev/null +++ b/src/slic3r/Utils/CrealityCfs.cpp @@ -0,0 +1,89 @@ +#include "CrealityCfs.hpp" +#include "MoonrakerPrinterAgent.hpp" + +#include +#include +#include + +#include + +namespace Slic3r { + +static std::string map_creality_material_id(const std::string& material_id) +{ + static const std::map types = { + {"000001", "PLA"}, {"000002", "ABS"}, {"000003", "PETG"}, + {"000004", "TPU"}, {"000005", "ASA"}, {"000006", "PA"}, + {"000007", "PC"}, {"000008", "PLA-CF"}, {"000009", "PETG-CF"}, + {"000010", "PA-CF"}, + }; + auto it = types.find(material_id); + return it == types.end() ? std::string() : it->second; +} + +// K2-family firmware reports branded/RFID spools with ids outside the generic +// 0000xx range (a Creality CR-Silk PLA reports "005001"). Those printers also +// publish the resolved name in box.same_material, whose entries are +// [material_id, color, [slots], type_name] - use it as a fallback so a slot is +// not dropped just because its id is missing from the static table above. +static std::map creality_same_material_types(const nlohmann::json& box) +{ + std::map types; + auto it = box.find("same_material"); + if (it == box.end() || !it->is_array()) + return types; + + for (const auto& entry : *it) { + if (!entry.is_array() || entry.size() < 4 || !entry[0].is_string() || !entry[3].is_string()) + continue; + const std::string id = entry[0].get(); + const std::string type = entry[3].get(); + if (!id.empty() && !type.empty()) + types.emplace(id, type); + } + return types; +} + +bool parse_creality_cfs_response(const std::string& response, std::vector& slots) +{ + slots.clear(); + const auto json = nlohmann::json::parse(response, nullptr, false, true); + if (json.is_discarded() || !json.is_object() || !json.contains("result") || + !json["result"].is_object() || !json["result"].contains("status") || + !json["result"]["status"].is_object() || !json["result"]["status"].contains("box") || + !json["result"]["status"]["box"].is_object()) + return false; + + const auto& box = json["result"]["status"]["box"]; + const auto same_material_types = creality_same_material_types(box); + for (int tray_idx = 1; tray_idx <= 4; ++tray_idx) { + auto it = box.find("T" + std::to_string(tray_idx)); + if (it == box.end() || !it->is_object() || MoonrakerPrinterAgent::safe_json_string(*it, "state") != "connect") + continue; + + const auto& tray = *it; + const int base_slot = (tray_idx - 1) * 4; + for (int slot_i = 0; slot_i < 4; ++slot_i) { + const std::string material_id = + tray.contains("material_type") ? MoonrakerPrinterAgent::safe_array_string(tray["material_type"], slot_i) : ""; + std::string type = map_creality_material_id(material_id); + if (type.empty()) { + auto same_it = same_material_types.find(material_id); + if (same_it != same_material_types.end()) + type = same_it->second; + } + if (type.empty()) + continue; + + std::string color = + tray.contains("color_value") ? MoonrakerPrinterAgent::safe_array_string(tray["color_value"], slot_i) : ""; + // Creality prefixes six-digit RGB colors with a leading zero. + if (color.size() == 7 && color.front() == '0') + color.erase(0, 1); + slots.push_back({base_slot + slot_i, type, color}); + } + } + return true; +} + +} // namespace Slic3r diff --git a/src/slic3r/Utils/CrealityCfs.hpp b/src/slic3r/Utils/CrealityCfs.hpp new file mode 100644 index 0000000000..7ed784106b --- /dev/null +++ b/src/slic3r/Utils/CrealityCfs.hpp @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace Slic3r { + +// One loaded slot of a Creality CFS, as the Creality Hi reports it in Moonraker's `box` printer object. +struct CrealityCfsSlot { + int slot_index = 0; + std::string material_type; + std::string color; +}; + +// Parse a /printer/objects/query?box response without querying printer hardware. +// Empty slots, disconnected boxes and unknown material ids are omitted. +bool parse_creality_cfs_response(const std::string& response, std::vector& slots); + +} // namespace Slic3r diff --git a/src/slic3r/Utils/CrealityPrintAgent.cpp b/src/slic3r/Utils/CrealityPrintAgent.cpp index a8910c2e09..9c5bf157ac 100644 --- a/src/slic3r/Utils/CrealityPrintAgent.cpp +++ b/src/slic3r/Utils/CrealityPrintAgent.cpp @@ -87,7 +87,7 @@ std::vector name_words(const std::string& name) // can collapse a brand-specific match back to "Generic PLA" via the inherited id. // Requires the preset's declared filament_type to equal the spool's base type // (PLA/PETG/ABS/...) so we never auto-pick a PETG preset for a PLA spool. -// Falls back to filaments.filament_id_by_type(base_type) when nothing scores. +// Falls back to a visible system base of the same type when nothing scores. std::string CrealityPrintAgent::match_filament_preset(const PresetCollection& filaments, const std::string& vendor, const std::string& brand_name, @@ -147,13 +147,17 @@ std::string CrealityPrintAgent::match_filament_preset(const PresetCollection& fi } if (matches.empty()) { - const std::string fallback = filaments.filament_id_by_type(base_type); - const bool fallback_ok = has_visible_base_preset(filaments, fallback); + // first_visible_idx_by_type() returns any visible preset when no base of this + // type exists. Never sync an unrelated material to the CFS. + const auto& fallback_preset = filaments.preset(filaments.first_visible_idx_by_type(base_type)); + const std::string fallback = fallback_preset.filament_id; + const bool fallback_ok = fallback_preset.config.opt_string("filament_type", 0u) == base_type && + has_visible_base_preset(filaments, fallback); BOOST_LOG_TRIVIAL(info) << "CrealityPrintAgent: no preset scored for spool {" << vendor << " " << brand_name << " (" << base_type << ")} after considering " << considered << " presets; falling back to generic preset id \"" << fallback << "\"" - << (fallback_ok ? "" : " (NOT visible — returning empty)"); + << (fallback_ok ? "" : " (no visible base of this type; returning empty)"); return fallback_ok ? fallback : std::string(); } diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp index 37503b1338..de6ecc320d 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.cpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.cpp @@ -1,5 +1,6 @@ #include "MoonrakerPrinterAgent.hpp" #include "AsioUtils.hpp" +#include "CrealityCfs.hpp" #include "Http.hpp" #include "IPrinterAgent.hpp" #include "NetworkAgentFactory.hpp" @@ -541,7 +542,6 @@ void MoonrakerPrinterAgent::build_ams_payload(int ams_count, int max_lane_index, tray_json["tray_info_idx"] = tray->tray_info_idx; tray_json["tray_type"] = tray->tray_type; tray_json["tray_color"] = normalize_color_value(tray->tray_color); - // Sent for every tray, since update_filament_multi_color() stops at the first tray without "cols". // "ctype" uses the filament_colour_type values (0 = gradient, 1 = solid or segments). const bool multi = tray->tray_colors.size() > 1; nlohmann::json cols = nlohmann::json::array(); @@ -643,8 +643,16 @@ bool MoonrakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSync return true; } - // No MMU detected - this is normal for printers without MMU, not an error - BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_filament_info: No MMU system detected (neither HH nor Moonraker)"; + // Creality Hi exposes CFS slots as a Moonraker box printer object. + if (fetch_creality_cfs_data(trays, max_lane_index)) { + BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_filament_info: Detected Creality CFS with " + << (max_lane_index + 1) << " slots"; + build_ams_payload((max_lane_index + 4) / 4, max_lane_index, trays); + return true; + } + + // No MMU detected - this is normal for printers without MMU, not an error. + BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_filament_info: No MMU system detected"; return false; } @@ -728,6 +736,42 @@ std::string MoonrakerPrinterAgent::map_filament_type_to_generic_id(const std::st return UNKNOWN_FILAMENT_ID; } +bool MoonrakerPrinterAgent::fetch_creality_cfs_data(std::vector& trays, int& max_lane_index) +{ + const std::string url = join_url(device_info.base_url, "/printer/objects/query?box"); + std::string response_body; + auto http = Http::get(url); + if (!device_info.api_key.empty()) + http.header("X-Api-Key", device_info.api_key); + http.timeout_connect(5).timeout_max(10) + .on_complete([&](std::string body, unsigned status) { + if (status == 200) + response_body = std::move(body); + }) + .perform_sync(); + + std::vector slots; + if (response_body.empty() || !parse_creality_cfs_response(response_body, slots) || slots.empty()) + return false; + + trays.clear(); + max_lane_index = 0; + auto* bundle = GUI::wxGetApp().preset_bundle; + for (const auto& slot : slots) { + AmsTrayData data; + data.slot_index = slot.slot_index; + data.tray_type = slot.material_type; + data.tray_color = slot.color; + data.has_filament = true; + data.tray_info_idx = bundle ? bundle->filaments.filament_id_by_type(data.tray_type) + : map_filament_type_to_generic_id(data.tray_type); + max_lane_index = std::max(max_lane_index, data.slot_index); + trays.push_back(std::move(data)); + } + BOOST_LOG_TRIVIAL(info) << "MoonrakerPrinterAgent::fetch_creality_cfs_data: Detected " << trays.size() << " CFS slots"; + return true; +} + // JSON helper methods - null-safe accessors std::string MoonrakerPrinterAgent::safe_json_string(const nlohmann::json& obj, const char* key) { diff --git a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp index fd322d531e..0bccb58f2b 100644 --- a/src/slic3r/Utils/MoonrakerPrinterAgent.hpp +++ b/src/slic3r/Utils/MoonrakerPrinterAgent.hpp @@ -71,6 +71,12 @@ public: FilamentSyncMode get_filament_sync_mode() const override { return FilamentSyncMode::pull; } bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; + // JSON helper methods + static std::string safe_json_string(const nlohmann::json& obj, const char* key); + static int safe_json_int(const nlohmann::json& obj, const char* key); + static std::string safe_array_string(const nlohmann::json& arr, int idx); + static int safe_array_int(const nlohmann::json& arr, int idx); + protected: struct MoonrakerDeviceInfo { @@ -204,12 +210,8 @@ private: // System-specific filament fetch methods bool fetch_hh_filament_info(std::vector& trays, int& max_lane_index); bool fetch_moonraker_filament_data(std::vector& trays, int& max_lane_index); + bool fetch_creality_cfs_data(std::vector& trays, int& max_lane_index); - // JSON helper methods - static std::string safe_json_string(const nlohmann::json& obj, const char* key); - static int safe_json_int(const nlohmann::json& obj, const char* key); - static std::string safe_array_string(const nlohmann::json& arr, int idx); - static int safe_array_int(const nlohmann::json& arr, int idx); static std::string normalize_color_value(const std::string& color); std::string ssdp_announced_host; diff --git a/tests/libslic3r/test_preset_bundle_loading.cpp b/tests/libslic3r/test_preset_bundle_loading.cpp index 0dd35a7855..0ae438f2fe 100644 --- a/tests/libslic3r/test_preset_bundle_loading.cpp +++ b/tests/libslic3r/test_preset_bundle_loading.cpp @@ -5652,6 +5652,45 @@ TEST_CASE("Published 3MF overrides each extruder slot on a similar multi-extrude } } +// Trays from printers that report a single colour per slot (Creality CFS via Moonraker) carry an +// empty filament_multi_colour. An empty slot between loaded ones used to cut the multi-colour list +// short, which crashed the filament combo; each loaded slot must instead fall back to its own colour. +TEST_CASE("An empty AMS slot between loaded single-colour slots keeps every slot's colour", "[Preset][Bundle][AMS]") +{ + PresetBundle bundle; + bundle.set_num_filaments(4u, std::string("#111111")); + auto add_ams_slot = [&](int slot, const std::string& id, const std::string& colour, bool placeholder) { + DynamicPrintConfig config; + config.set_key_value("filament_id", new ConfigOptionStrings{id}); + config.set_key_value("filament_colour", new ConfigOptionStrings{colour}); + config.set_key_value("filament_colour_type", new ConfigOptionStrings{"1"}); + config.set_key_value("filament_multi_colour", new ConfigOptionStrings{}); + config.set_key_value("ams_id", new ConfigOptionStrings{"0"}); + config.set_key_value("slot_id", new ConfigOptionStrings{std::to_string(slot)}); + config.set_key_value("filament_type", new ConfigOptionStrings{placeholder ? "" : "PETG"}); + config.set_key_value("filament_slot_placeholder", new ConfigOptionBools{placeholder}); + bundle.filament_ams_list.emplace(slot, std::move(config)); + }; + add_ams_slot(0, "CFS-PETG", "#000000", false); + add_ams_slot(1, "CFS-PETG", "#FF1E1E", false); + add_ams_slot(2, "", "", true); + add_ams_slot(3, "CFS-PETG", "#FFFFFF", false); + std::vector> unknowns; + std::map maps; + MergeFilamentInfo merge_info; + REQUIRE(bundle.sync_ams_list(unknowns, false, maps, true, merge_info, false) == 4); + + const auto& colours = bundle.project_config.option("filament_colour")->values; + const auto& multi = bundle.project_config.option("filament_multi_colour")->values; + REQUIRE(colours.size() == 4); + REQUIRE(multi.size() == colours.size()); + CHECK(colours[0] == "#000000"); + CHECK(colours[1] == "#FF1E1E"); + CHECK(colours[3] == "#FFFFFF"); + for (size_t i = 0; i < colours.size(); ++i) + CHECK(multi[i] == colours[i]); +} + TEST_CASE("Loading incomplete mixed metadata normalizes slots before adding a filament", "[Preset][Bundle][FilamentMixer]") { DynamicPrintConfig config = DynamicPrintConfig::full_print_config(); diff --git a/tests/slic3rutils/test_creality_cfs_match.cpp b/tests/slic3rutils/test_creality_cfs_match.cpp index 6b8faf4b79..58f57b170c 100644 --- a/tests/slic3rutils/test_creality_cfs_match.cpp +++ b/tests/slic3rutils/test_creality_cfs_match.cpp @@ -5,6 +5,7 @@ #include "libslic3r/Preset.hpp" #include "libslic3r/PresetBundle.hpp" #include "libslic3r/PrintConfig.hpp" +#include "slic3r/Utils/CrealityCfs.hpp" #include "slic3r/Utils/CrealityPrintAgent.hpp" using namespace Slic3r; @@ -82,6 +83,91 @@ std::string match(const std::vector &specs, const std::string &spo } // namespace +TEST_CASE("The Creality Hi Moonraker box response exposes loaded CFS slots", "[CFS][Creality]") +{ + const std::string response = R"({"result":{"status":{"box":{ + "T1":{"state":"connect","material_type":["","000003","-1", "000001"], + "color_value":["","0FF1E1E","-1","000FF00"]}, + "T2":{"state":"None","material_type":["000002","-1","-1","-1"], + "color_value":["0FFFFFF","-1","-1","-1"]} + }}}})"; + std::vector slots; + REQUIRE(parse_creality_cfs_response(response, slots)); + REQUIRE(slots.size() == 2); + CHECK(slots[0].slot_index == 1); + CHECK(slots[0].material_type == "PETG"); + CHECK(slots[0].color == "FF1E1E"); + CHECK(slots[1].slot_index == 3); + CHECK(slots[1].material_type == "PLA"); + CHECK(slots[1].color == "00FF00"); +} + +TEST_CASE("The Creality Hi CFS parser rejects malformed and absent box responses", "[CFS][Creality]") +{ + std::vector slots; + CHECK_FALSE(parse_creality_cfs_response("{", slots)); + CHECK_FALSE(parse_creality_cfs_response(R"({"result":{"status":{}}})", slots)); + CHECK(slots.empty()); +} + +TEST_CASE("The Creality Hi CFS parser skips unknown material IDs", "[CFS][Creality]") +{ + const std::string response = R"({"result":{"status":{"box":{"T1":{"state":"connect", + "material_type":["999999","000003",null,"-1"],"color_value":["0FFFFFF","0FF1E1E","-1","-1"]}}}}})"; + std::vector slots; + REQUIRE(parse_creality_cfs_response(response, slots)); + REQUIRE(slots.size() == 1); + CHECK(slots[0].slot_index == 1); + CHECK(slots[0].material_type == "PETG"); +} + +// K2-family firmware reports branded/RFID spools with ids outside the generic 0000xx range: a +// Creality CR-Silk PLA (RFID 05001) reports "005001". The printer resolves the name itself in +// box.same_material, so a slot is only dropped when the printer cannot name it either. +TEST_CASE("The Creality K2 Plus CFS parser resolves branded IDs via same_material", "[CFS][Creality]") +{ + const std::string response = R"({"result":{"status":{"box":{ + "same_material":[["005001","0ffffff",["T1A"],"PLA"]], + "T1":{"state":"connect","material_type":["005001","-1","-1","-1"], + "color_value":["0ffffff","-1","-1","-1"]}, + "T2":{"state":"None","material_type":["-1","-1","-1","-1"], + "color_value":["-1","-1","-1","-1"]} + }}}})"; + std::vector slots; + REQUIRE(parse_creality_cfs_response(response, slots)); + REQUIRE(slots.size() == 1); + CHECK(slots[0].slot_index == 0); + CHECK(slots[0].material_type == "PLA"); + CHECK(slots[0].color == "ffffff"); +} + +TEST_CASE("The Creality CFS parser skips IDs that same_material cannot name", "[CFS][Creality]") +{ + const std::string response = R"({"result":{"status":{"box":{ + "same_material":[["0e1003","0fff014",["T1A"],""]], + "T1":{"state":"connect","material_type":["0e1003","000003","-1","-1"], + "color_value":["0fff014","0FF1E1E","-1","-1"]} + }}}})"; + std::vector slots; + REQUIRE(parse_creality_cfs_response(response, slots)); + REQUIRE(slots.size() == 1); + CHECK(slots[0].slot_index == 1); + CHECK(slots[0].material_type == "PETG"); +} + +TEST_CASE("The Creality CFS parser tolerates a malformed same_material list", "[CFS][Creality]") +{ + const std::string response = R"({"result":{"status":{"box":{ + "same_material":[["005001"],"nonsense",[1,2,3,4]], + "T1":{"state":"connect","material_type":["000001","-1","-1","-1"], + "color_value":["0FFFFFF","-1","-1","-1"]} + }}}})"; + std::vector slots; + REQUIRE(parse_creality_cfs_response(response, slots)); + REQUIRE(slots.size() == 1); + CHECK(slots[0].material_type == "PLA"); +} + // Orca: a CFS spool that names no recognised product must map to the vendor's plain generic. The // subtype variants ("High Speed", "Matte", "Silk") score just as well on vendor alone, and since // each is its own product with its own filament_id, letting one of them win sends the printer the @@ -126,6 +212,14 @@ TEST_CASE("A CFS spool from an unknown vendor falls back to a preset of the same CHECK(std::string(spec->filament_type) == "PLA"); } +TEST_CASE("A CFS fallback never selects another material when its type is unavailable", "[CFS][Creality]") +{ + const std::vector no_system_abs{ + {"Generic TPU @System", "TPU-GENERIC", "TPU", /*is_library=*/true}, + {"My ABS", "ABS-USER", "ABS", /*is_library=*/false, /*is_system=*/false}, + }; + CHECK(match(no_system_abs, "Unknown", "", "ABS").empty()); +} // Orca: Creality's bundle also ships third party filaments ("eSUN PLA+ @K2 Plus-all"). Those carry // Creality's VendorProfile but name their real brand, so the vendor bonus has to accept a name