Compare commits

..
Author SHA1 Message Date
Hanif Koh ee7bd58a9f Stop Exporting Names Through Usings in the Remaining Headers
The last headers with a using or namespace alias at namespace scope:

- TCPConsole.hpp imported boost::asio::ip::tcp into Slic3r::Utils for
  two member declarations. The alias is now a private member of the
  class.
- WebSocketClient.hpp declared four namespace aliases and a tcp alias
  at global scope, each used only by the header. The names are spelled
  out.
- Repair.hpp aliased CGAL::Polygon_mesh_processing as PMP in
  Slic3r::tex2color. The three functions that use it declare the alias
  themselves.
- PreciseSeam.hpp, Thumbnails.hpp and MarchingSquares.hpp used a
  using-declaration or directive for one or two spots each; those spots
  are qualified. Thumbnails.hpp's "PNG"sv default argument becomes
  "PNG", which converts to the std::string_view parameter the same way.
- tests/sla_print/sla_test_utils.hpp had "using namespace Slic3r;" and
  tests/filament_group/fg_test_serialization.hpp "using json =
  nlohmann::json;" at global scope. The headers qualify their own names;
  the two SLA test sources get the directive themselves.

Also removed: twelve type aliases in headers that nothing references
(ConflictObjName, CircleSqf, CircleSqd, TRawBuffer, DistanceFunction,
SamePair, ExtruderNozzleInfos, Vec2dEvent, Vec2dsEvent, Vec3dEvent,
t_option, t_optgroups, Plater::fs_path) and a duplicate
fn_ft_job_msg_destroy alias in FileTransferUtils.hpp.
2026-10-07 18:31:22 +08:00
35 changed files with 547 additions and 2676 deletions
+1 -1
View File
@@ -311,7 +311,7 @@ function CreatePrinterBlock(OneModel)
return '<div class="PrinterBlock" onClick="ChooseModel(\''+vendor+'\',\''+OneModel['model']+'\')">'+ return '<div class="PrinterBlock" onClick="ChooseModel(\''+vendor+'\',\''+OneModel['model']+'\')">'+
' <div class="PImg">'+ ' <div class="PImg">'+
' <img class="ModelThumbnail" src="' + OneModel['cover'] + '" onerror="this.onerror=null;this.src=\'../img/printer-dummy.png\';"/>'+ ' <img class="ModelThumbnail" src="' + OneModel['cover'] + '" />'+
' </div>'+ ' </div>'+
' <div class="PrinterInfoMark">?</div>'+ ' <div class="PrinterInfoMark">?</div>'+
' <div class="PrinterInfo">'+ ' <div class="PrinterInfo">'+
Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

-2
View File
@@ -148,8 +148,6 @@ struct ConflictComputeResult
using ConflictComputeOpt = std::optional<ConflictComputeResult>; using ConflictComputeOpt = std::optional<ConflictComputeResult>;
using ConflictObjName = std::optional<std::pair<std::string, std::string>>;
struct ConflictChecker struct ConflictChecker
{ {
static ConflictResultOpt find_inter_of_lines_in_diff_objs(PrintObjectPtrs objs, std::optional<const FakeWipeTower *> wtdptr); static ConflictResultOpt find_inter_of_lines_in_diff_objs(PrintObjectPtrs objs, std::optional<const FakeWipeTower *> wtdptr);
+1 -4
View File
@@ -22,9 +22,6 @@
namespace Slic3r { namespace Slic3r {
namespace PreciseSeam { namespace PreciseSeam {
// Import EnforcedBlockedSeamPoint from SeamPlacerImpl namespace for convenience
using SeamPlacerImpl::EnforcedBlockedSeamPoint;
// Geometry and its exterior bounds are prepared together, then treated as read-only. // Geometry and its exterior bounds are prepared together, then treated as read-only.
struct ModifierRegion { struct ModifierRegion {
ExPolygon polygon; ExPolygon polygon;
@@ -137,7 +134,7 @@ SegmentExtraction extract_perimeter_segments(const PreparedPerimeter &prepared,
// Result of weak modifier segment processing // Result of weak modifier segment processing
struct WeakModifierSegment { struct WeakModifierSegment {
EnforcedBlockedSeamPoint type; // Enforced/Blocked/Neutral SeamPlacerImpl::EnforcedBlockedSeamPoint type; // Enforced/Blocked/Neutral
Point left_point; // Coordinates of left (first) point of segment Point left_point; // Coordinates of left (first) point of segment
PerimeterPosition left_position; // Position on the source perimeter before insertion/refinement. PerimeterPosition left_position; // Position on the source perimeter before insertion/refinement.
Point right_point; // Coordinates of right (last) point of segment Point right_point; // Coordinates of right (last) point of segment
+1 -2
View File
@@ -40,8 +40,7 @@ std::string get_error_string(const ThumbnailErrors& errors);
typedef std::vector<std::pair<GCodeThumbnailsFormat, Vec2d>> GCodeThumbnailDefinitionsList; typedef std::vector<std::pair<GCodeThumbnailsFormat, Vec2d>> GCodeThumbnailDefinitionsList;
using namespace std::literals; std::pair<GCodeThumbnailDefinitionsList, ThumbnailErrors> make_and_check_thumbnail_list(const std::string& thumbnails_string, const std::string_view def_ext = "PNG");
std::pair<GCodeThumbnailDefinitionsList, ThumbnailErrors> make_and_check_thumbnail_list(const std::string& thumbnails_string, const std::string_view def_ext = "PNG"sv);
std::pair<GCodeThumbnailDefinitionsList, ThumbnailErrors> make_and_check_thumbnail_list(const ConfigBase &config); std::pair<GCodeThumbnailDefinitionsList, ThumbnailErrors> make_and_check_thumbnail_list(const ConfigBase &config);
-2
View File
@@ -94,8 +94,6 @@ struct Circle {
using Circlef = Circle<Vec2f>; using Circlef = Circle<Vec2f>;
using Circled = Circle<Vec2d>; using Circled = Circle<Vec2d>;
using CircleSqf = CircleSq<Vec2f>;
using CircleSqd = CircleSq<Vec2d>;
/// Find the center of the circle corresponding to the vector of Points as an arc. /// Find the center of the circle corresponding to the vector of Points as an arc.
Point circle_center_taubin_newton(const Points::const_iterator& input_start, const Points::const_iterator& input_end, size_t cycles = 20); Point circle_center_taubin_newton(const Points::const_iterator& input_start, const Points::const_iterator& input_end, size_t cycles = 20);
+3 -4
View File
@@ -154,13 +154,12 @@ template<class ExecutionPolicy, class Enable = void> struct _Loop
}; };
// Add Specialization for using ExecutionTBB for parallel loops. // Add Specialization for using ExecutionTBB for parallel loops.
using namespace Slic3r; template<> struct _Loop<Slic3r::ExecutionTBB>
template<> struct _Loop<ExecutionTBB>
{ {
template<class It, class Fn> static void for_each_idx(It from, It to, Fn&& fn) template<class It, class Fn> static void for_each_idx(It from, It to, Fn&& fn)
{ {
execution::for_each( Slic3r::execution::for_each(
ex_tbb, size_t(0), size_t(to - from), [&from, &fn](size_t i) { fn(from[i], i); }, execution::max_concurrency(ex_tbb)); Slic3r::ex_tbb, size_t(0), size_t(to - from), [&from, &fn](size_t i) { fn(from[i], i); }, Slic3r::execution::max_concurrency(Slic3r::ex_tbb));
} }
}; };
-1
View File
@@ -49,7 +49,6 @@ public:
using TColor = typename PixelRenderer::color_type; using TColor = typename PixelRenderer::color_type;
using TValue = typename TColor::value_type; using TValue = typename TColor::value_type;
using TPixel = typename PixelRenderer::pixel_type; using TPixel = typename PixelRenderer::pixel_type;
using TRawBuffer = agg::rendering_buffer;
protected: protected:
@@ -17,9 +17,6 @@ typedef std::vector<Color> ColorList;
typedef std::array<double, 3> ColorDouble; typedef std::array<double, 3> ColorDouble;
typedef std::array<std::size_t, 3> RGB; typedef std::array<std::size_t, 3> RGB;
// Function pointer type that points to a specific color-difference function based on the chosen method.
using DistanceFunction = double (*)(const Color&, const Color&);
// Color space used for computing color differences. // Color space used for computing color differences.
enum struct ColorDifferenceMethod : std::size_t { enum struct ColorDifferenceMethod : std::size_t {
RGB = 0, // Simplest and fastest RGB = 0, // Simplest and fastest
+3 -2
View File
@@ -23,8 +23,6 @@
namespace Slic3r { namespace tex2color { namespace Slic3r { namespace tex2color {
namespace PMP = CGAL::Polygon_mesh_processing;
// Default upper bound on the number of half-edges in any single boundary cycle // Default upper bound on the number of half-edges in any single boundary cycle
// that CloseBoundariesAndRepairManifoldness will attempt to triangulate. The // that CloseBoundariesAndRepairManifoldness will attempt to triangulate. The
// cost of triangulate_hole grows non-linearly with cycle length, so this caps // cost of triangulate_hole grows non-linearly with cycle length, so this caps
@@ -60,6 +58,7 @@ struct BoundaryEdgeStats
// any pre-processing (e.g. stitch_borders) needed for the count to be meaningful. // any pre-processing (e.g. stitch_borders) needed for the count to be meaningful.
inline BoundaryEdgeStats ComputeBoundaryEdgeStats(const cgalutils::CGALMesh& cgal_mesh) inline BoundaryEdgeStats ComputeBoundaryEdgeStats(const cgalutils::CGALMesh& cgal_mesh)
{ {
namespace PMP = CGAL::Polygon_mesh_processing;
using CGALMesh = cgalutils::CGALMesh; using CGALMesh = cgalutils::CGALMesh;
using HalfedgeDescriptor = boost::graph_traits<CGALMesh>::halfedge_descriptor; using HalfedgeDescriptor = boost::graph_traits<CGALMesh>::halfedge_descriptor;
@@ -86,6 +85,7 @@ inline BoundaryEdgeStats ComputeBoundaryEdgeStats(const cgalutils::CGALMesh& cga
// boundary statistics; entering this function always triggers triangulation. // boundary statistics; entering this function always triggers triangulation.
inline void CloseBoundariesAndRepairManifoldness(cgalutils::CGALMesh& cgal_mesh) inline void CloseBoundariesAndRepairManifoldness(cgalutils::CGALMesh& cgal_mesh)
{ {
namespace PMP = CGAL::Polygon_mesh_processing;
using CGALMesh = cgalutils::CGALMesh; using CGALMesh = cgalutils::CGALMesh;
using HalfedgeDescriptor = boost::graph_traits<CGALMesh>::halfedge_descriptor; using HalfedgeDescriptor = boost::graph_traits<CGALMesh>::halfedge_descriptor;
using FaceDescriptor = boost::graph_traits<CGALMesh>::face_descriptor; using FaceDescriptor = boost::graph_traits<CGALMesh>::face_descriptor;
@@ -111,6 +111,7 @@ inline bool RepairMesh(const TriMesh& mesh,
AlgoCancelCallback cancel_callback = nullptr, AlgoCancelCallback cancel_callback = nullptr,
const RepairSetting& setting = RepairSetting{}) const RepairSetting& setting = RepairSetting{})
{ {
namespace PMP = CGAL::Polygon_mesh_processing;
using Clock = std::chrono::steady_clock; using Clock = std::chrono::steady_clock;
auto elapsed_ms = [](Clock::time_point t0) { auto elapsed_ms = [](Clock::time_point t0) {
return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - t0).count(); return std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - t0).count();
-2
View File
@@ -432,8 +432,6 @@ inline IntegerOnly<I, I> fast_round_up(double a)
return a == 0.49999999999999994 ? I(0) : I(floor(a + 0.5)); return a == 0.49999999999999994 ? I(0) : I(floor(a + 0.5));
} }
template<class T> using SamePair = std::pair<T, T>;
} // namespace Slic3r } // namespace Slic3r
#endif #endif
-3
View File
@@ -198,6 +198,3 @@ template<> struct std::hash<NozzleDef>
return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2)); return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
}; };
}; };
// key(extruder_id) -> { key1(nozzle type info), val1( number of the nozzle type)}
using ExtruderNozzleInfos = std::unordered_map<int, std::unordered_map<NozzleDef, int>>;
-3
View File
@@ -183,13 +183,10 @@ wxDECLARE_EVENT(EVT_GLCANVAS_PLATE_NAME_CHANGE, SimpleEvent);
//BBS: declare EVT_GLCANVAS_PLATE_SELECT //BBS: declare EVT_GLCANVAS_PLATE_SELECT
wxDECLARE_EVENT(EVT_GLCANVAS_PLATE_SELECT, SimpleEvent); wxDECLARE_EVENT(EVT_GLCANVAS_PLATE_SELECT, SimpleEvent);
using Vec2dEvent = Event<Vec2d>;
// _bool_ value is used as a indicator of selection in the 3DScene // _bool_ value is used as a indicator of selection in the 3DScene
using RBtnEvent = Event<std::pair<Vec2d, bool>>; using RBtnEvent = Event<std::pair<Vec2d, bool>>;
using RBtnPlateEvent = Event<std::pair<Vec2d, int>>; using RBtnPlateEvent = Event<std::pair<Vec2d, int>>;
template <size_t N> using Vec2dsEvent = ArrayEvent<Vec2d, N>;
using Vec3dEvent = Event<Vec3d>;
template <size_t N> using Vec3dsEvent = ArrayEvent<Vec3d, N>; template <size_t N> using Vec3dsEvent = ArrayEvent<Vec3d, N>;
using HeightProfileSmoothEvent = Event<HeightProfileSmoothingParams>; using HeightProfileSmoothEvent = Event<HeightProfileSmoothingParams>;
-1
View File
@@ -54,7 +54,6 @@ struct Option {
Option(const ConfigOptionDef& _opt, t_config_option_key id) : Option(const ConfigOptionDef& _opt, t_config_option_key id) :
opt(_opt), opt_id(id) {} opt(_opt), opt_id(id) {}
}; };
using t_option = std::unique_ptr<Option>; //!
/// Represents option lines /// Represents option lines
class Line : public UndoValueUIManager class Line : public UndoValueUIManager
-2
View File
@@ -108,7 +108,6 @@ class PlaterPresetComboBox;
class PartPlateList; class PartPlateList;
class SyncNozzleAndAmsDialog; class SyncNozzleAndAmsDialog;
class FinishSyncAmsDialog; class FinishSyncAmsDialog;
using t_optgroups = std::vector <std::shared_ptr<ConfigOptionsGroup>>;
class Plater; class Plater;
enum class ActionButtonType : int; enum class ActionButtonType : int;
@@ -325,7 +324,6 @@ private:
class Plater: public wxPanel class Plater: public wxPanel
{ {
public: public:
using fs_path = boost::filesystem::path;
Plater(wxWindow *parent, MainFrame *main_frame); Plater(wxWindow *parent, MainFrame *main_frame);
Plater(Plater &&) = delete; Plater(Plater &&) = delete;
+6 -22
View File
@@ -204,9 +204,8 @@ int BBLPrinterAgent::command_axis_control(std::string dev_id, std::string axis,
int dir = input_val > 0 ? 1 : -1; int dir = input_val > 0 ? 1 : -1;
// i3-arch printers move the bed for Y/Z, so the on-screen direction is // i3-arch printers move the bed for Y/Z, so the on-screen direction is
// reversed -- same negation the g-code fallback below applies. // reversed -- same negation the g-code fallback below applies.
if (!is_core_xy && (axis == "Y" || axis == "Z")) { if (!is_core_xy && (axis == "Y" || axis == "Z"))
dir = -dir; dir = -dir;
}
j["print"]["command"] = "xyz_ctrl"; j["print"]["command"] = "xyz_ctrl";
j["print"]["axis"] = axis; j["print"]["axis"] = axis;
@@ -216,9 +215,8 @@ int BBLPrinterAgent::command_axis_control(std::string dev_id, std::string axis,
} }
double value = input_val; double value = input_val;
if (!is_core_xy && (axis == "Y" || axis == "Z")) { if (!is_core_xy && (axis == "Y" || axis == "Z"))
value = -1.0 * input_val; value = -input_val;
}
std::string value_str = (boost::format("%.1f") % (value * unit)).str(); std::string value_str = (boost::format("%.1f") % (value * unit)).str();
std::string gcode; std::string gcode;
@@ -239,11 +237,10 @@ int BBLPrinterAgent::command_axis_control(std::string dev_id, std::string axis,
int BBLPrinterAgent::publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode) int BBLPrinterAgent::publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode)
{ {
const int rtn = lan_mode ? send_message_to_printer(dev_id, j.dump(), 0, 0) : send_message(dev_id, j.dump(), 0, 0); const int rtn = lan_mode ? send_message_to_printer(dev_id, j.dump(), 0, 0) : send_message(dev_id, j.dump(), 0, 0);
if (rtn == 0) { if (rtn == 0)
BOOST_LOG_TRIVIAL(info) << "publish_json: " << j.dump() << " code: " << rtn; BOOST_LOG_TRIVIAL(info) << "publish_json: " << j.dump() << " code: " << rtn;
} else { else
BOOST_LOG_TRIVIAL(error) << "publish_json: " << j.dump() << " code: " << rtn; BOOST_LOG_TRIVIAL(error) << "publish_json: " << j.dump() << " code: " << rtn;
}
return rtn; return rtn;
} }
@@ -589,21 +586,8 @@ int BBLPrinterAgent::start_local_print_with_record(PrintParams params, OnUpdateS
int BBLPrinterAgent::start_send_gcode_to_sdcard(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) int BBLPrinterAgent::start_send_gcode_to_sdcard(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn)
{ {
// dispatch_start() moves out of `params`, so snapshot the diagnostic fields first; return dispatch_start<func_start_send_gcode_to_sdcard_legacy, func_start_send_gcode_to_sdcard_0203>(
// logging them after the call would print empty strings.
const bool try_emmc_print = params.try_emmc_print;
const std::string dev_ip = params.dev_ip;
const std::string dev_id = params.dev_id;
int result = dispatch_start<func_start_send_gcode_to_sdcard_legacy, func_start_send_gcode_to_sdcard_0203>(
BBLNetworkPlugin::instance().get_start_send_gcode_to_sdcard(), params, update_fn, cancel_fn, wait_fn); BBLNetworkPlugin::instance().get_start_send_gcode_to_sdcard(), params, update_fn, cancel_fn, wait_fn);
if (result != 0) {
BOOST_LOG_TRIVIAL(error) << "start_send_gcode_to_sdcard failed: result=" << result
<< ", try_emmc_print=" << try_emmc_print
<< ", legacy_mode=" << BBLNetworkPlugin::instance().use_legacy_network()
<< ", dev_ip=" << dev_ip << ", dev_id=" << dev_id;
}
return result;
} }
int BBLPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) int BBLPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn)
-1
View File
@@ -110,7 +110,6 @@ public:
static std::string from_orca_payload(std::string json_text); static std::string from_orca_payload(std::string json_text);
private: private:
// why: the lan/cloud DECISION stays machine-side; keep this mechanical branch in sync with publish_json.
int publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode); int publish(const std::string& dev_id, const nlohmann::json& j, bool lan_mode);
}; };
+4 -9
View File
@@ -288,14 +288,9 @@ bool CrealityPrintAgent::parse_cfs_response(const std::string& response,
return true; return true;
} }
bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode) bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/)
{ {
if (sync_mode != get_filament_sync_mode()) if (device_info.dev_ip.empty()) {
return false;
const MoonrakerDeviceInfo info = snapshot_device_info();
if (info.dev_ip.empty()) {
BOOST_LOG_TRIVIAL(warning) BOOST_LOG_TRIVIAL(warning)
<< "CrealityPrintAgent::fetch_filament_info: no device IP, falling back to base agent"; << "CrealityPrintAgent::fetch_filament_info: no device IP, falling back to base agent";
return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id)); return MoonrakerPrinterAgent::fetch_filament_info(std::move(dev_id));
@@ -304,11 +299,11 @@ bool CrealityPrintAgent::fetch_filament_info(std::string dev_id, FilamentSyncMod
// Build a CrealityPrint helper so we can use its model detection + WS helpers // Build a CrealityPrint helper so we can use its model detection + WS helpers
// (added in upstream PR #13291). // (added in upstream PR #13291).
DynamicPrintConfig cfg; DynamicPrintConfig cfg;
cfg.set_key_value("print_host", new ConfigOptionString("http://" + info.dev_ip)); cfg.set_key_value("print_host", new ConfigOptionString("http://" + device_info.dev_ip));
cfg.set_key_value("print_host_webui", new ConfigOptionString("")); cfg.set_key_value("print_host_webui", new ConfigOptionString(""));
cfg.set_key_value("printhost_cafile", new ConfigOptionString("")); cfg.set_key_value("printhost_cafile", new ConfigOptionString(""));
cfg.set_key_value("printhost_port", new ConfigOptionString("")); cfg.set_key_value("printhost_port", new ConfigOptionString(""));
cfg.set_key_value("printhost_apikey", new ConfigOptionString(info.api_key)); cfg.set_key_value("printhost_apikey", new ConfigOptionString(device_info.api_key));
cfg.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false)); cfg.set_key_value("printhost_ssl_ignore_revoke", new ConfigOptionBool(false));
CrealityPrint host(&cfg); CrealityPrint host(&cfg);
+1 -1
View File
@@ -37,7 +37,7 @@ public:
}; };
explicit CrealityPrintAgent(std::string log_dir); explicit CrealityPrintAgent(std::string log_dir);
~CrealityPrintAgent() override { shutdown(); } ~CrealityPrintAgent() override = default;
static AgentInfo get_agent_info_static(); static AgentInfo get_agent_info_static();
AgentInfo get_agent_info() override { return get_agent_info_static(); } AgentInfo get_agent_info() override { return get_agent_info_static(); }
-1
View File
@@ -89,7 +89,6 @@ using fn_ft_job_get_result = ft_err(FT_CALL *)(FT_JobHandle *, uint32_t timeo
using fn_ft_tunnel_start_job = ft_err(FT_CALL *)(FT_TunnelHandle *, FT_JobHandle *); using fn_ft_tunnel_start_job = ft_err(FT_CALL *)(FT_TunnelHandle *, FT_JobHandle *);
using fn_ft_job_cancel = ft_err(FT_CALL *)(FT_JobHandle *); using fn_ft_job_cancel = ft_err(FT_CALL *)(FT_JobHandle *);
using fn_ft_job_msg_destroy = void(FT_CALL *)(ft_job_msg *);
using fn_ft_job_set_msg_cb = ft_err(FT_CALL *)(FT_JobHandle *, void(FT_CALL *)(void *user, ft_job_msg msg), void *user); using fn_ft_job_set_msg_cb = ft_err(FT_CALL *)(FT_JobHandle *, void(FT_CALL *)(void *user, ft_job_msg msg), void *user);
using fn_ft_job_try_get_msg = ft_err(FT_CALL *)(FT_JobHandle *, ft_job_msg *out_msg); using fn_ft_job_try_get_msg = ft_err(FT_CALL *)(FT_JobHandle *, ft_job_msg *out_msg);
using fn_ft_job_get_msg = ft_err(FT_CALL *)(FT_JobHandle *, uint32_t timeout_ms, ft_job_msg *out_msg); using fn_ft_job_get_msg = ft_err(FT_CALL *)(FT_JobHandle *, uint32_t timeout_ms, ft_job_msg *out_msg);
File diff suppressed because it is too large Load Diff
+25 -172
View File
@@ -12,10 +12,6 @@
#include <set> #include <set>
#include <string> #include <string>
#include <thread> #include <thread>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <functional>
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <vector> #include <vector>
@@ -24,56 +20,6 @@ namespace Slic3r { class ICloudServiceAgent; }
namespace Slic3r { namespace Slic3r {
class Http;
bool moonraker_is_light_name(const std::string& name);
// Direction encoded by a light name: +1 turns on, -1 turns off, 0 is an ambiguous toggle.
// e.g. LIGHT_ON -> +1, LIGHT_OFF -> -1, LIGHT -> 0.
int moonraker_light_name_direction(const std::string& name);
struct MoonrakerWebcamSelection
{
std::string url;
CameraStreamMode mode = CameraStreamMode::none;
std::string name;
std::string error; // set when no selectable webcam was found
};
// Selects a webcam from a parsed /server/webcams/list response (the top-level JSON or its
// "result" value). Returns true and fills url/mode/name on success; on failure returns
// false and sets error.
bool moonraker_parse_webcam_list(const nlohmann::json& response, const std::string& base_url,
MoonrakerWebcamSelection& out);
class MoonrakerWebsocket
{
public:
enum class ReadResult
{
message,
timeout,
closed,
error,
};
MoonrakerWebsocket(bool secure, std::string api_key, std::string ca_file);
~MoonrakerWebsocket();
void connect(const std::string& host, const std::string& port, std::chrono::seconds timeout);
void tls_handshake(const std::string& host);
void handshake(const std::string& host, const std::string& target);
void text(bool enabled);
void write(const std::string& body);
ReadResult read(std::string& payload, std::string& error_message);
void close();
void expires_after(std::chrono::seconds timeout);
void abort();
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
class MoonrakerPrinterAgent : public IPrinterAgent class MoonrakerPrinterAgent : public IPrinterAgent
{ {
public: public:
@@ -119,24 +65,12 @@ public:
int set_on_local_connect_fn(OnLocalConnectedFn fn) override; int set_on_local_connect_fn(OnLocalConnectedFn fn) override;
int set_on_local_message_fn(OnMessageFn fn) override; int set_on_local_message_fn(OnMessageFn fn) override;
int set_queue_on_main_fn(QueueOnMainFn fn) override; int set_queue_on_main_fn(QueueOnMainFn fn) override;
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override;
CameraStreamMode get_camera_stream_mode() const override;
std::string get_camera_url() const override;
// Called by the fetch-thread RAII guard when a background filament fetch finishes. // Pull-mode agent (on-demand filament sync)
// Serialized with the reservation so shutdown()'s wait cannot miss the transition to 0. FilamentSyncMode get_filament_sync_mode() const override { return FilamentSyncMode::pull; }
void release_fetch_slot() noexcept; bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override;
protected: protected:
struct ConnectionSettings
{
std::string dev_id;
std::string base_url;
std::string api_key;
bool use_ssl = false;
std::string ca_file;
};
struct MoonrakerDeviceInfo struct MoonrakerDeviceInfo
{ {
std::string dev_id; std::string dev_id;
@@ -148,9 +82,7 @@ protected:
std::string dev_name; std::string dev_name;
std::string version; std::string version;
std::string klippy_state; std::string klippy_state;
float nozzle_diameter = 0.0f;
bool use_ssl = false; bool use_ssl = false;
std::string ca_file;
} device_info; } device_info;
// Tray data for AMS payload building // Tray data for AMS payload building
@@ -168,29 +100,12 @@ protected:
void build_ams_payload(int ams_count, int max_lane_index, const std::vector<AmsTrayData>& trays); void build_ams_payload(int ams_count, int max_lane_index, const std::vector<AmsTrayData>& trays);
// Methods that derived classes may need to override or access // Methods that derived classes may need to override or access
virtual bool init_device_info(const PrinterConnectionParams& params); 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);
virtual bool fetch_device_info(const ConnectionSettings& connection, MoonrakerDeviceInfo& info, std::string& error) const; virtual bool fetch_device_info(const std::string& base_url, const std::string& api_key, MoonrakerDeviceInfo& info, std::string& error) const;
ConnectionSettings get_connection_settings() const;
// Copy of the mutable connection state, taken under connect_mutex. Background threads
// must use this instead of reading device_info directly.
MoonrakerDeviceInfo snapshot_device_info() const;
void configure_http(Http& http, const ConnectionSettings& connection) const;
static float parse_nozzle_diameter(const nlohmann::json& response);
// State access for derived classes // State access for derived classes
mutable std::recursive_mutex state_mutex; mutable std::recursive_mutex state_mutex;
// Detached fetch threads hold a raw `this`; shutdown() waits for this to reach 0.
std::atomic<int> filament_fetch_in_flight{0};
// Idempotent teardown; must be called from the most-derived destructor.
void shutdown();
std::atomic<bool> shutting_down{false};
// Serializes the shutting_down check with the in-flight reservation.
std::mutex fetch_lifecycle_mutex;
std::condition_variable fetch_done_cv; // notified when filament_fetch_in_flight reaches 0
// Helpers // Helpers
bool is_numeric(const std::string& value); bool is_numeric(const std::string& value);
std::string normalize_base_url(bool use_ssl, const std::string& host, const std::string& port); std::string normalize_base_url(bool use_ssl, const std::string& host, const std::string& port);
@@ -203,30 +118,13 @@ protected:
// Map filament type to OrcaFilamentLibrary preset ID for AMS sync compatibility // Map filament type to OrcaFilamentLibrary preset ID for AMS sync compatibility
static std::string map_filament_type_to_generic_id(const std::string& filament_type); static std::string map_filament_type_to_generic_id(const std::string& filament_type);
// Send a G-code script via Moonraker (/printer/gcode/script)
bool send_gcode(const std::string& dev_id, const std::string& gcode) const;
bool send_gcode(const std::string& dev_id, const std::string& gcode,
const ConnectionSettings& connection) const;
bool post_print_action(const std::string& action) const;
bool post_print_action(const std::string& action,
const ConnectionSettings& connection) const;
bool send_ws_rpc(const std::string& method, const nlohmann::json& params);
virtual void on_status_loop_tick(const std::string& dev_id) {}
// Queue work that may use agent state. The command worker is joined during
// destruction, so queued commands cannot outlive the agent.
void enqueue_command(std::function<void()> fn);
mutable std::recursive_mutex connect_mutex;
private: private:
int handle_request(const std::string& dev_id, const std::string& json_str); int handle_request(const std::string& dev_id, const std::string& json_str);
int send_version_info(const std::string& dev_id); int send_version_info(const std::string& dev_id);
int send_access_code(const std::string& dev_id); int send_access_code(const std::string& dev_id);
bool fetch_object_list(const ConnectionSettings& connection, std::set<std::string>& objects, std::string& error) const; bool fetch_object_list(const std::string& base_url, const std::string& api_key, std::set<std::string>& objects, std::string& error) const;
bool query_printer_status(const ConnectionSettings& connection, nlohmann::json& status, std::string& error) const; bool query_printer_status(const std::string& base_url, const std::string& api_key, nlohmann::json& status, std::string& error) const;
bool send_gcode_sync(const std::string& dev_id, const std::string& gcode) 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, void send_gcode_async(const std::string& dev_id, const std::string& gcode,
std::function<void(bool)> on_result = {}) const; std::function<void(bool)> on_result = {}) const;
@@ -234,48 +132,37 @@ private:
void announce_printhost_device(); void announce_printhost_device();
void dispatch_local_connect(int state, const std::string& dev_id, const std::string& msg); void dispatch_local_connect(int state, const std::string& dev_id, const std::string& msg);
void dispatch_printer_connected(const std::string& dev_id); void dispatch_printer_connected(const std::string& dev_id);
// Self-contained snapshot of the message callbacks. Async completions capture this
// by value so they never dereference `this` after the agent may have been destroyed.
struct MessageRouter
{
OnMessageFn local_fn;
OnMessageFn cloud_fn;
QueueOnMainFn queue_fn;
std::string dev_id;
void deliver(std::string payload) const;
};
MessageRouter make_message_router(const std::string& dev_id) const;
void dispatch_message(const std::string& dev_id, const std::string& payload); void dispatch_message(const std::string& dev_id, const std::string& payload);
void start_status_stream(const std::string& dev_id, ConnectionSettings connection); void start_status_stream(const std::string& dev_id, const std::string& base_url, const std::string& api_key);
void stop_status_stream(); void stop_status_stream();
void run_status_stream(std::string dev_id, ConnectionSettings connection); void run_status_stream(std::string dev_id, std::string base_url, std::string api_key);
void handle_ws_message(std::string dev_id, std::string payload, ConnectionSettings connection); void handle_ws_message(const std::string& dev_id, const std::string& payload);
void refresh_thumbnail_url(const ConnectionSettings& connection);
void update_status_cache(const nlohmann::json& updates); void update_status_cache(const nlohmann::json& updates);
nlohmann::json build_print_payload_locked() const; nlohmann::json build_print_payload_locked() const;
// Print control helpers
int pause_print(const std::string& dev_id);
int resume_print(const std::string& dev_id);
int cancel_print(const std::string& dev_id);
// File upload // File upload
bool upload_gcode(const std::string& local_path, const std::string& filename, bool upload_gcode(const std::string& local_path, const std::string& filename,
const ConnectionSettings& connection, const std::string& base_url, const std::string& api_key,
OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn); 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 // Connection thread management
void perform_connection_async(const std::string& dev_id, void perform_connection_async(const std::string& dev_id,
ConnectionSettings connection, const std::string& base_url,
const std::string& api_key,
uint64_t generation); uint64_t generation);
// why: a printer with no /server/webcams/list entry can still name its stream directly;
// subclasses (e.g. printers with a fixed webcam path) can override this instead.
virtual std::string webcam_stream_override(const std::string& base_url) const { return {}; }
void refresh_webcam_info() const;
bool fetch_webcam_info(const ConnectionSettings& connection, uint64_t generation) const;
// System-specific filament fetch methods // System-specific filament fetch methods
bool fetch_hh_filament_info(const ConnectionSettings& connection, std::vector<AmsTrayData>& trays, int& max_lane_index); bool fetch_hh_filament_info(std::vector<AmsTrayData>& trays, int& max_lane_index);
bool fetch_moonraker_filament_data(const ConnectionSettings& connection, std::vector<AmsTrayData>& trays, int& max_lane_index); bool fetch_moonraker_filament_data(std::vector<AmsTrayData>& trays, int& max_lane_index);
// JSON helper methods // JSON helper methods
static std::string safe_json_string(const nlohmann::json& obj, const char* key); static std::string safe_json_string(const nlohmann::json& obj, const char* key);
@@ -301,43 +188,15 @@ private:
mutable std::recursive_mutex payload_mutex; mutable std::recursive_mutex payload_mutex;
nlohmann::json status_cache; nlohmann::json status_cache;
// note: guarded by payload_mutex; filled by refresh_thumbnail_url(), empty url = looked up, none found
std::string thumbnail_filename;
std::string thumbnail_url;
mutable std::string webcam_stream_url;
mutable CameraStreamMode webcam_stream_mode = CameraStreamMode::none;
// Next time the status loop may look the webcam up again (steady_clock ms).
mutable std::atomic<uint64_t> webcam_info_next_attempt_ms{0};
unsigned thumbnail_lookup_attempts = 0;
static constexpr uint64_t WEBCAM_INFO_REFRESH_INTERVAL_MS = 30000;
static constexpr uint64_t WEBCAM_INFO_FAILURE_BACKOFF_MS = 60000;
std::atomic<int> next_jsonrpc_id{1}; std::atomic<int> next_jsonrpc_id{1};
std::set<std::string> available_objects; // Track for feature detection std::set<std::string> available_objects; // Track for feature detection
bool assumed_light_on = false;
std::atomic<bool> ws_stop{false}; std::atomic<bool> ws_stop{false};
std::atomic<bool> ws_reconnect_requested{false}; // Flag to trigger reconnection std::atomic<bool> ws_reconnect_requested{false}; // Flag to trigger reconnection
std::atomic<uint64_t> ws_last_emit_ms{0}; std::atomic<uint64_t> ws_last_emit_ms{0};
std::thread ws_thread; std::thread ws_thread;
// stop_status_stream() invokes ws_abort_io to wake a blocked synchronous
// ws.read()/ws.write()/handshake in run_status_stream(): ws_stop is only
// observed between reads, and Beast's expires_after() does not bound
// synchronous operations.
std::mutex ws_abort_mutex;
std::function<void()> ws_abort_io; // guarded by ws_abort_mutex
// Interrupts the exponential reconnect backoff in run_status_stream() when stopping.
std::mutex ws_wait_mutex;
std::condition_variable ws_wait_cv;
// AMS/filament refresh cadence, independent of telemetry dispatch so a steady
// stream of status updates can't starve it (ws_last_emit_ms is reset by those).
static constexpr uint64_t AMS_REFRESH_INTERVAL_MS = 10000;
std::atomic<uint64_t> ams_last_fetch_ms{0};
// Throttling configuration for WebSocket updates // Throttling configuration for WebSocket updates
// Critical changes (state transitions) dispatch immediately; telemetry is throttled // Critical changes (state transitions) dispatch immediately; telemetry is throttled
static constexpr uint64_t STATUS_UPDATE_INTERVAL_MS = 1000; // 1 update/sec for telemetry static constexpr uint64_t STATUS_UPDATE_INTERVAL_MS = 1000; // 1 update/sec for telemetry
@@ -347,13 +206,7 @@ private:
// Connection thread management // Connection thread management
std::atomic<uint64_t> connect_generation{0}; std::atomic<uint64_t> connect_generation{0};
std::thread connect_thread; std::thread connect_thread;
std::recursive_mutex connect_mutex;
void run_command_worker();
std::thread cmd_thread;
std::deque<std::function<void()>> cmd_queue;
std::mutex cmd_mutex;
std::condition_variable cmd_cv;
bool cmd_stop = false;
}; };
} // namespace Slic3r } // namespace Slic3r
+57 -214
View File
@@ -2,24 +2,18 @@
#include "Http.hpp" #include "Http.hpp"
#include "MoonrakerPrinterAgent.hpp" #include "MoonrakerPrinterAgent.hpp"
#include "IPrinterAgent.hpp" #include "IPrinterAgent.hpp"
#include "bambu_networking.hpp"
#include "libslic3r/PresetBundle.hpp" #include "libslic3r/PresetBundle.hpp"
#include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_App.hpp"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include <atomic>
#include <boost/algorithm/string.hpp> #include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp> #include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/case_conv.hpp> #include <boost/algorithm/string/case_conv.hpp>
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <cctype> #include <cctype>
#include "libslic3r/Preset.hpp" #include "libslic3r/Preset.hpp"
#include <cstddef>
#include <exception>
#include <map> #include <map>
#include <mutex>
#include <sstream> #include <sstream>
#include <thread>
#include <string> #include <string>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -40,26 +34,6 @@ bool has_visible_base_preset(const PresetCollection& filaments, const std::strin
return false; return false;
} }
// RAII release of the in-flight fetch slot; movable so a failed thread start still releases it.
struct InFlightGuard
{
MoonrakerPrinterAgent* owner;
explicit InFlightGuard(MoonrakerPrinterAgent& o) noexcept : owner(&o) {}
InFlightGuard(InFlightGuard&& other) noexcept : owner(other.owner) { other.owner = nullptr; }
InFlightGuard(const InFlightGuard&) = delete;
InFlightGuard& operator=(const InFlightGuard&) = delete;
InFlightGuard& operator=(InFlightGuard&&) = delete;
~InFlightGuard() { if (owner) owner->release_fetch_slot(); }
};
// nlohmann::json::value() returns the default only when the key is absent; a present but
// null/wrong-typed value throws. Firmware JSON is untrusted, so read defensively.
int read_int_or(const nlohmann::json& obj, const std::string& key, int fallback)
{
auto it = obj.find(key);
return (it != obj.end() && it->is_number_integer()) ? it->get<int>() : fallback;
}
} // anonymous namespace } // anonymous namespace
const std::string QidiPrinterAgent_VERSION = "0.0.1"; const std::string QidiPrinterAgent_VERSION = "0.0.1";
@@ -73,166 +47,51 @@ AgentInfo QidiPrinterAgent::get_agent_info_static()
return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"}; return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"};
} }
FilamentSyncMode QidiPrinterAgent::get_filament_sync_mode() const bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/)
{ {
if (GUI::wxGetApp().app_config->get_bool("use_printer_agents")) std::string error;
return FilamentSyncMode::subscription;
return FilamentSyncMode::pull;
}
bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode) // 1. Fetch device info and infer series_id
{ std::string series_id;
if (sync_mode != get_filament_sync_mode())
return false;
// Snapshot what the fetch needs; a reconnect can rewrite device_info meanwhile.
ConnectionSettings connection = get_connection_settings();
std::string model_id;
std::string model_name;
{ {
std::lock_guard<std::recursive_mutex> lock(connect_mutex); MoonrakerDeviceInfo info;
model_id = device_info.model_id; if (fetch_device_info(device_info.base_url, device_info.api_key, info, error)) {
model_name = device_info.model_name; series_id = infer_series_id(info.model_id, info.dev_name);
}
// Reserve under the same mutex shutdown() uses, so the flag and the count can't race.
{
std::lock_guard<std::mutex> lock(fetch_lifecycle_mutex);
if (shutting_down.load())
return false;
if (filament_fetch_in_flight.load() > 0)
return true; // a fetch is already running; don't pile on
filament_fetch_in_flight.fetch_add(1, std::memory_order_relaxed);
}
InFlightGuard guard{*this};
std::thread([this, guard = std::move(guard), connection = std::move(connection), model_id, model_name]() mutable {
try {
std::string error;
// 1. Fetch device info and infer series_id
std::string series_id;
{
MoonrakerDeviceInfo info;
if (fetch_device_info(connection, info, error)) {
series_id = infer_series_id(info.model_id, info.dev_name);
}
}
if (series_id.empty()) {
// Fall back to the configured Orca model if Moonraker doesn't expose a usable identifier.
series_id = infer_series_id(model_id, model_name);
}
// 2. Fetch filament dictionary
QidiFilamentDict dict;
if (!fetch_filament_dict(connection, dict, error)) {
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::fetch_filament_info: Failed to fetch filament dict: " << error;
}
// 3. Fetch slot info and build AmsTrayData directly
std::vector<AmsTrayData> trays;
int box_count = 0;
if (!fetch_slot_info(connection, dict, series_id, trays, box_count, error)) {
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::fetch_filament_info: Failed to fetch slot info: " << error;
return;
}
// 4. Build the AMS payload
build_ams_payload(box_count, box_count * 4 - 1, trays);
} catch (const std::exception& e) {
// why: an exception escaping a detached thread is std::terminate, and firmware
// JSON is untrusted; mirror run_command_worker and swallow it here.
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::fetch_filament_info: unhandled exception: " << e.what();
} catch (...) {
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::fetch_filament_info: unhandled exception";
} }
}).detach(); }
if (series_id.empty()) {
// Fall back to the configured Orca model if Moonraker doesn't expose a usable identifier.
series_id = infer_series_id(device_info.model_id, device_info.model_name);
}
// 2. Fetch filament dictionary
QidiFilamentDict dict;
if (!fetch_filament_dict(device_info.base_url, device_info.api_key, dict, error)) {
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::fetch_filament_info: Failed to fetch filament dict: " << error;
}
// 3. Fetch slot info and build AmsTrayData directly
std::vector<AmsTrayData> trays;
int box_count = 0;
if (!fetch_slot_info(device_info.base_url, device_info.api_key, dict, series_id, trays, box_count, error)) {
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::fetch_filament_info: Failed to fetch slot info: " << error;
return false;
}
// 4. Build the AMS payload
build_ams_payload(box_count, box_count * 4 - 1, trays);
return true; return true;
} }
bool QidiPrinterAgent::apply_box_mapping(const PrintParams& params) const bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url,
{ const std::string& api_key,
// enable_box mirrors task_use_ams: engage the multi-color box only when this
// job actually routes filament through it. (See qidi-ams-findings.md §2/§8.3 —
// if firmware treats enable_box as "a box exists" rather than "use it this job",
// switch this gate to HasAms()/box_count instead.)
const int enable = params.task_use_ams ? 1 : 0;
const std::string dev_id = get_connection_settings().dev_id;
// Build one gcode/script request instead of N blocking HTTP calls: apply_box_mapping
// runs on the caller's (GUI) thread before the print starts, so per-tool round trips
// would freeze the UI.
std::string script = "SAVE_VARIABLE VARIABLE=enable_box VALUE=" + std::to_string(enable);
// When the box isn't used this job, leave the existing value_t<tool> slot
// assignments untouched (enable_box=0 is enough to disengage it).
if (enable) {
if (params.ams_mapping.empty()) {
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::apply_box_mapping: enable_box set but ams_mapping is empty";
} else {
// ams_mapping (v0) is a JSON array indexed by filament/tool; each value is the
// physical box slot (-1 = unmapped). Mirror it onto value_t<tool>.
auto mapping = nlohmann::json::parse(params.ams_mapping, nullptr, /*allow_exceptions*/ false);
if (mapping.is_discarded() || !mapping.is_array()) {
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::apply_box_mapping: invalid ams_mapping: " << params.ams_mapping;
return false;
}
for (size_t tool = 0; tool < mapping.size(); ++tool) {
if (!mapping[tool].is_number_integer())
continue;
const int slot = mapping[tool].get<int>();
if (slot < 0)
continue; // unmapped filament — skip
script += "\nSAVE_VARIABLE VARIABLE=value_t" + std::to_string(tool) +
" VALUE=\"'slot" + std::to_string(slot) + "'\"";
}
}
}
if (!send_gcode(dev_id, script)) {
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::apply_box_mapping: failed to send box mapping";
return false;
}
return true;
}
int QidiPrinterAgent::start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn)
{
if (!apply_box_mapping(params))
return BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED;
return MoonrakerPrinterAgent::start_local_print(std::move(params), update_fn, cancel_fn);
}
int QidiPrinterAgent::start_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn)
{
if (!apply_box_mapping(params))
return BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED;
return MoonrakerPrinterAgent::start_print(std::move(params), update_fn, cancel_fn, wait_fn);
}
int QidiPrinterAgent::start_local_print_with_record(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn)
{
// A failed box mapping is a send failure, not an upload failure.
if (!apply_box_mapping(params))
return BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED;
return MoonrakerPrinterAgent::start_local_print_with_record(std::move(params), update_fn, cancel_fn, wait_fn);
}
int QidiPrinterAgent::start_sdcard_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn)
{
if (!apply_box_mapping(params))
return BAMBU_NETWORK_ERR_PRINT_LP_PUBLISH_MSG_FAILED;
return MoonrakerPrinterAgent::start_sdcard_print(std::move(params), update_fn, cancel_fn);
}
bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
const QidiFilamentDict& dict, const QidiFilamentDict& dict,
const std::string& series_id, const std::string& series_id,
std::vector<AmsTrayData>& trays, std::vector<AmsTrayData>& trays,
int& box_count, int& box_count,
std::string& error) std::string& error)
{ {
std::string url = join_url(connection.base_url, "/printer/objects/query?save_variables=variables"); std::string url = join_url(base_url, "/printer/objects/query?save_variables=variables");
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i) {
url += "&box_stepper%20slot" + std::to_string(i) + "=runout_button"; url += "&box_stepper%20slot" + std::to_string(i) + "=runout_button";
} }
@@ -242,9 +101,8 @@ bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
std::string http_error; std::string http_error;
auto http = Http::get(url); auto http = Http::get(url);
configure_http(http, connection); if (!api_key.empty()) {
if (!connection.api_key.empty()) { http.header("X-Api-Key", api_key);
http.header("X-Api-Key", connection.api_key);
} }
http.timeout_connect(5) http.timeout_connect(5)
.timeout_max(10) .timeout_max(10)
@@ -269,12 +127,22 @@ bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
return false; return false;
} }
nlohmann::json status; auto json = nlohmann::json::parse(response_body, nullptr, false, true);
nlohmann::json variables; if (json.is_discarded()) {
if (!parse_slot_response(response_body, status, variables, error)) error = "Invalid JSON response";
return false; return false;
}
box_count = read_int_or(variables, "box_count", 1); if (!json.contains("result") || !json["result"].contains("status") || !json["result"]["status"].contains("save_variables") ||
!json["result"]["status"]["save_variables"].contains("variables")) {
error = "Unexpected JSON structure";
return false;
}
auto& variables = json["result"]["status"]["save_variables"]["variables"];
auto& status = json["result"]["status"];
box_count = variables.value("box_count", 1);
if (box_count < 0) { if (box_count < 0) {
box_count = 0; box_count = 0;
} }
@@ -297,9 +165,9 @@ bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
tray.slot_index = i; tray.slot_index = i;
// Read slot variables // Read slot variables
const int color_index = read_int_or(variables, "color_slot" + std::to_string(i), 1); const int color_index = variables.value("color_slot" + std::to_string(i), 1);
const int filament_type = read_int_or(variables, "filament_slot" + std::to_string(i), 1); const int filament_type = variables.value("filament_slot" + std::to_string(i), 1);
const int vendor_type = read_int_or(variables, "vendor_slot" + std::to_string(i), 0); const int vendor_type = variables.value("vendor_slot" + std::to_string(i), 0);
// Check filament presence via runout sensor // Check filament presence via runout sensor
std::string box_stepper_key = "box_stepper slot" + std::to_string(i); std::string box_stepper_key = "box_stepper slot" + std::to_string(i);
@@ -307,7 +175,7 @@ bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
if (status.contains(box_stepper_key)) { if (status.contains(box_stepper_key)) {
auto& box_stepper = status[box_stepper_key]; auto& box_stepper = status[box_stepper_key];
if (box_stepper.contains("runout_button") && !box_stepper["runout_button"].is_null()) { if (box_stepper.contains("runout_button") && !box_stepper["runout_button"].is_null()) {
const int runout_button = read_int_or(box_stepper, "runout_button", 0); int runout_button = box_stepper["runout_button"].template get<int>();
tray.has_filament = (runout_button == 0); tray.has_filament = (runout_button == 0);
} }
} }
@@ -347,45 +215,20 @@ bool QidiPrinterAgent::fetch_slot_info(const ConnectionSettings& connection,
return true; return true;
} }
bool QidiPrinterAgent::parse_slot_response(const std::string& response_body, bool QidiPrinterAgent::fetch_filament_dict(const std::string& base_url,
nlohmann::json& status, const std::string& api_key,
nlohmann::json& variables,
std::string& error)
{
auto json = nlohmann::json::parse(response_body, nullptr, false, true);
if (json.is_discarded()) {
error = "Invalid JSON response";
return false;
}
if (!json.is_object() || !json.contains("result") || !json["result"].is_object() || !json["result"].contains("status") ||
!json["result"]["status"].is_object() || !json["result"]["status"].contains("save_variables") ||
!json["result"]["status"]["save_variables"].is_object() || !json["result"]["status"]["save_variables"].contains("variables") ||
!json["result"]["status"]["save_variables"]["variables"].is_object()) {
// why: Qidi firmware may send null here, but json::value() throws for it.
error = "Unexpected JSON structure: save_variables.variables must be an object";
return false;
}
status = json["result"]["status"];
variables = status["save_variables"]["variables"];
return true;
}
bool QidiPrinterAgent::fetch_filament_dict(const ConnectionSettings& connection,
QidiFilamentDict& dict, QidiFilamentDict& dict,
std::string& error) const std::string& error) const
{ {
std::string url = join_url(connection.base_url, "/server/files/config/officiall_filas_list.cfg"); std::string url = join_url(base_url, "/server/files/config/officiall_filas_list.cfg");
std::string response_body; std::string response_body;
bool success = false; bool success = false;
std::string http_error; std::string http_error;
auto http = Http::get(url); auto http = Http::get(url);
configure_http(http, connection); if (!api_key.empty()) {
if (!connection.api_key.empty()) { http.header("X-Api-Key", api_key);
http.header("X-Api-Key", connection.api_key);
} }
http.timeout_connect(5) http.timeout_connect(5)
.timeout_max(10) .timeout_max(10)
+4 -21
View File
@@ -3,8 +3,6 @@
#include "IPrinterAgent.hpp" #include "IPrinterAgent.hpp"
#include "MoonrakerPrinterAgent.hpp" #include "MoonrakerPrinterAgent.hpp"
#include "bambu_networking.hpp"
#include "nlohmann/json_fwd.hpp"
#include <map> #include <map>
#include <string> #include <string>
@@ -16,7 +14,7 @@ class QidiPrinterAgent final : public MoonrakerPrinterAgent
{ {
public: public:
explicit QidiPrinterAgent(std::string log_dir); explicit QidiPrinterAgent(std::string log_dir);
~QidiPrinterAgent() override { shutdown(); } ~QidiPrinterAgent() override = default;
static AgentInfo get_agent_info_static(); static AgentInfo get_agent_info_static();
AgentInfo get_agent_info() override { return get_agent_info_static(); } AgentInfo get_agent_info() override { return get_agent_info_static(); }
@@ -24,23 +22,7 @@ public:
// Override filament sync (Qidi-specific implementation) // Override filament sync (Qidi-specific implementation)
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override;
static bool parse_slot_response(const std::string& response_body,
nlohmann::json& status,
nlohmann::json& variables,
std::string& error);
// Print operations — emit QiDi multi-color box config, then delegate to base.
int start_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) override;
int start_local_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) override;
int start_local_print_with_record(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn, OnWaitFn wait_fn) override;
int start_sdcard_print(PrintParams params, OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn) override;
FilamentSyncMode get_filament_sync_mode() const override;
private: private:
// Push enable_box + value_t<tool> SAVE_VARIABLEs before a print starts.
// Returns false if any command fails (caller should abort the print).
bool apply_box_mapping(const PrintParams& params) const;
struct QidiFilamentDict struct QidiFilamentDict
{ {
std::map<int, std::string> colors; std::map<int, std::string> colors;
@@ -48,13 +30,14 @@ private:
}; };
// Qidi-specific methods // Qidi-specific methods
bool fetch_slot_info(const ConnectionSettings& connection, bool fetch_slot_info(const std::string& base_url,
const std::string& api_key,
const QidiFilamentDict& dict, const QidiFilamentDict& dict,
const std::string& series_id, const std::string& series_id,
std::vector<AmsTrayData>& trays, std::vector<AmsTrayData>& trays,
int& box_count, int& box_count,
std::string& error); std::string& error);
bool fetch_filament_dict(const ConnectionSettings& connection, QidiFilamentDict& dict, std::string& error) const; bool fetch_filament_dict(const std::string& base_url, const std::string& api_key, QidiFilamentDict& dict, std::string& error) const;
std::string normalize_filament_type(const std::string& filament_type); std::string normalize_filament_type(const std::string& filament_type);
std::string infer_series_id(const std::string& model_id, const std::string& dev_name); std::string infer_series_id(const std::string& model_id, const std::string& dev_name);
std::string normalize_model_key(std::string value); std::string normalize_model_key(std::string value);
+105 -254
View File
@@ -2,19 +2,11 @@
#include "Http.hpp" #include "Http.hpp"
#include "MoonrakerPrinterAgent.hpp" #include "MoonrakerPrinterAgent.hpp"
#include "IPrinterAgent.hpp" #include "IPrinterAgent.hpp"
#include "bambu_networking.hpp"
#include "libslic3r/PresetBundle.hpp" #include "libslic3r/PresetBundle.hpp"
#include "slic3r/GUI/GUI_App.hpp" #include "slic3r/GUI/GUI_App.hpp"
#include "nlohmann/json.hpp" #include "nlohmann/json.hpp"
#include <atomic>
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <chrono>
#include <cstdint>
#include <exception>
#include <mutex>
#include <sstream>
#include <thread>
#include <vector> #include <vector>
#include <string> #include <string>
#include "libslic3r/Preset.hpp" #include "libslic3r/Preset.hpp"
@@ -26,77 +18,6 @@ namespace Slic3r {
namespace { namespace {
constexpr const char* SNAPMAKER_AGENT_VERSION = "0.0.1"; constexpr const char* SNAPMAKER_AGENT_VERSION = "0.0.1";
constexpr int64_t CAMERA_REFRESH_INTERVAL_MS = 300'000;
int64_t now_ms()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
}
// RAII release of the in-flight fetch slot; movable so a failed thread start still releases it.
struct InFlightGuard
{
MoonrakerPrinterAgent* owner;
explicit InFlightGuard(MoonrakerPrinterAgent& o) noexcept : owner(&o) {}
InFlightGuard(InFlightGuard&& other) noexcept : owner(other.owner) { other.owner = nullptr; }
InFlightGuard(const InFlightGuard&) = delete;
InFlightGuard& operator=(const InFlightGuard&) = delete;
InFlightGuard& operator=(InFlightGuard&&) = delete;
~InFlightGuard() { if (owner) owner->release_fetch_slot(); }
};
// nlohmann::json::value() returns the default only when the key is absent; a present but
// null/wrong-typed value throws. Firmware JSON is untrusted, so read defensively.
int read_int_or(const nlohmann::json& obj, const char* key, int fallback)
{
auto it = obj.find(key);
return (it != obj.end() && it->is_number_integer()) ? it->get<int>() : fallback;
}
std::vector<std::string> read_string_array_or(const nlohmann::json& obj, const char* key)
{
auto it = obj.find(key);
if (it == obj.end() || !it->is_array())
return {};
std::vector<std::string> out;
out.reserve(it->size());
for (const auto& v : *it)
out.push_back(v.is_string() ? v.get<std::string>() : std::string{});
return out;
}
std::vector<bool> read_bool_array_or(const nlohmann::json& obj, const char* key)
{
auto it = obj.find(key);
if (it == obj.end() || !it->is_array())
return {};
std::vector<bool> out;
out.reserve(it->size());
for (const auto& v : *it)
out.push_back(v.is_boolean() ? v.get<bool>() : false);
return out;
}
// Parse a hex colour, stopping at the first non-hex character. std::stoul throws on
// empty/non-hex input, which must not escape the detached fetch thread.
unsigned int parse_hex_color(const std::string& hex)
{
unsigned int value = 0;
for (char c : hex) {
int digit;
if (c >= '0' && c <= '9')
digit = c - '0';
else if (c >= 'a' && c <= 'f')
digit = c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
digit = c - 'A' + 10;
else
break;
value = (value << 4) | static_cast<unsigned int>(digit);
}
return value;
}
// Safely access a parallel array by index, returning a fallback if out of bounds. // Safely access a parallel array by index, returning a fallback if out of bounds.
template<typename T> template<typename T>
@@ -119,16 +40,14 @@ std::string find_closest_color_preset_by_vendor_and_type(const PresetCollection&
filaments.get_preset_base(p) == &p && p.config.opt_string("filament_vendor", 0u) == vendor_name && filaments.get_preset_base(p) == &p && p.config.opt_string("filament_vendor", 0u) == vendor_name &&
p.config.opt_string("filament_type", 0u) == filament_type) { p.config.opt_string("filament_type", 0u) == filament_type) {
// The printer returns RGBA in the format RRGGBBAA, but profiles store color as #RRGGBB, // The printer returns RGBA in the format RRGGBBAA, but profiles store color as #RRGGBB,
// so we must remove # and ignore alpha channel for distance calculation. Firmware // so we must remove # and ignore alpha channel for distance calculation
// colours are untrusted; parse_hex_color tolerates empty/non-hex instead of throwing. unsigned int target_color_value = std::stoul(color_rgba.substr(0, color_rgba.length() - 2), nullptr, 16);
unsigned int target_color_value =
parse_hex_color(color_rgba.substr(0, color_rgba.size() >= 2 ? color_rgba.size() - 2 : 0));
std::string p_color = p.config.opt_string("default_filament_colour", 0u); std::string p_color = p.config.opt_string("default_filament_colour", 0u);
unsigned int p_color_value = 0; unsigned int p_color_value;
if (!p_color.empty()) { if (!p_color.empty()) {
size_t hash_pos = p_color.find("#"); size_t hash_pos = p_color.find("#");
p_color_value = parse_hex_color(p_color.substr(hash_pos != std::string::npos ? hash_pos + 1 : 0)); p_color_value = std::stoul(p_color.substr(hash_pos != std::string::npos ? hash_pos + 1 : 0), nullptr, 16);
} else { } else {
// Default to black if no color specified in profile. Assume other profiles might be a closer color match. // Default to black if no color specified in profile. Assume other profiles might be a closer color match.
// Could be a problem if the target color is also black and there exist a specific profile for that type, vendor and color // Could be a problem if the target color is also black and there exist a specific profile for that type, vendor and color
@@ -155,31 +74,6 @@ std::string find_closest_color_preset_by_vendor_and_type(const PresetCollection&
SnapmakerPrinterAgent::SnapmakerPrinterAgent(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {} SnapmakerPrinterAgent::SnapmakerPrinterAgent(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {}
void SnapmakerPrinterAgent::start_camera_monitor()
{
enqueue_command([this] {
send_ws_rpc("camera.start_monitor",
{{"domain", "lan"}, {"interval", 0}, {"expect_pw", false}});
});
m_camera_last_fire_ms.store(now_ms());
}
void SnapmakerPrinterAgent::on_status_loop_tick(const std::string& dev_id)
{
(void) dev_id;
const int64_t last = m_camera_last_fire_ms.load();
if (last == 0 || now_ms() - last >= CAMERA_REFRESH_INTERVAL_MS) {
start_camera_monitor();
}
}
int SnapmakerPrinterAgent::command_start_camera(std::string dev_id)
{
(void) dev_id;
start_camera_monitor();
return BAMBU_NETWORK_SUCCESS;
}
AgentInfo SnapmakerPrinterAgent::get_agent_info_static() AgentInfo SnapmakerPrinterAgent::get_agent_info_static()
{ {
return AgentInfo{"snapmaker", "Snapmaker", SNAPMAKER_AGENT_VERSION, "Snapmaker printer agent"}; return AgentInfo{"snapmaker", "Snapmaker", SNAPMAKER_AGENT_VERSION, "Snapmaker printer agent"};
@@ -215,170 +109,127 @@ std::string SnapmakerPrinterAgent::combine_filament_type(const std::string& type
return base; return base;
} }
bool SnapmakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode) bool SnapmakerPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/)
{ {
(void) dev_id; std::string url = join_url(device_info.base_url, "/printer/objects/query?print_task_config&filament_detect");
if (sync_mode != get_filament_sync_mode())
std::string response_body;
bool success = false;
std::string http_error;
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 = 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) {
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: HTTP request failed: " << http_error;
return false; return false;
// Snapshot everything the fetch needs (URL, api key, TLS/CA): a reconnect can rewrite
// device_info meanwhile.
const ConnectionSettings connection = get_connection_settings();
// Reserve under the same mutex shutdown() uses, so the flag and the count can't race.
{
std::lock_guard<std::mutex> lock(fetch_lifecycle_mutex);
if (shutting_down.load())
return false;
if (filament_fetch_in_flight.load() > 0)
return true; // a fetch is already running; don't pile on
filament_fetch_in_flight.fetch_add(1, std::memory_order_relaxed);
} }
InFlightGuard guard{*this}; auto json = nlohmann::json::parse(response_body, nullptr, false, true);
std::thread([this, guard = std::move(guard), connection]() { if (json.is_discarded()) {
try { BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Invalid JSON response";
const std::string url = join_url(connection.base_url, "/printer/objects/query?print_task_config&filament_detect"); return false;
}
std::string response_body; // Navigate to result.status.print_task_config
bool success = false; if (!json.contains("result") || !json["result"].contains("status") ||
std::string http_error; !json["result"]["status"].contains("print_task_config")) {
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Missing print_task_config in response";
return false;
}
auto http = Http::get(url); auto& ptc = json["result"]["status"]["print_task_config"];
configure_http(http, connection);
if (!connection.api_key.empty()) {
http.header("X-Api-Key", connection.api_key);
}
http.timeout_connect(5)
.timeout_max(10)
.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) { // Read parallel arrays from print_task_config
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: HTTP request failed: " << http_error; auto filament_exist = ptc.value("filament_exist", std::vector<bool>{});
return; auto filament_type = ptc.value("filament_type", std::vector<std::string>{});
} auto filament_sub_type = ptc.value("filament_sub_type", std::vector<std::string>{});
auto filament_color = ptc.value("filament_color_rgba", std::vector<std::string>{});
auto filament_vendor = ptc.value("filament_vendor", std::vector<std::string>{});
auto json = nlohmann::json::parse(response_body, nullptr, false, true); const int slot_count = static_cast<int>(filament_exist.size());
if (json.is_discarded()) { if (slot_count == 0) {
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Invalid JSON response"; BOOST_LOG_TRIVIAL(info) << "SnapmakerPrinterAgent::fetch_filament_info: No filament slots reported";
return; return false;
} }
// Navigate to result.status.print_task_config // Read NFC filament_detect data for temperature info (optional)
if (!json.contains("result") || !json["result"].contains("status") || !json["result"]["status"].contains("print_task_config")) { nlohmann::json nfc_info;
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Missing print_task_config in response"; if (json["result"]["status"].contains("filament_detect") &&
return; json["result"]["status"]["filament_detect"].contains("info")) {
} nfc_info = json["result"]["status"]["filament_detect"]["info"];
}
auto& ptc = json["result"]["status"]["print_task_config"]; static const std::string empty_str;
static const std::string default_color = "FFFFFFFF";
// Read parallel arrays from print_task_config std::vector<AmsTrayData> trays;
auto filament_exist = read_bool_array_or(ptc, "filament_exist"); trays.reserve(slot_count);
auto filament_type = read_string_array_or(ptc, "filament_type");
auto filament_sub_type = read_string_array_or(ptc, "filament_sub_type");
auto filament_color = read_string_array_or(ptc, "filament_color_rgba");
auto filament_vendor = read_string_array_or(ptc, "filament_vendor");
const int slot_count = static_cast<int>(filament_exist.size()); for (int i = 0; i < slot_count; ++i) {
if (slot_count == 0) { AmsTrayData tray;
BOOST_LOG_TRIVIAL(info) << "SnapmakerPrinterAgent::fetch_filament_info: No filament slots reported"; tray.slot_index = i;
return; tray.has_filament = filament_exist[i];
}
// Read NFC filament_detect data for temperature info (optional) if (tray.has_filament) {
nlohmann::json nfc_info; tray.tray_type = combine_filament_type(safe_at(filament_type, i, empty_str),
if (json["result"]["status"].contains("filament_detect") && json["result"]["status"]["filament_detect"].contains("info")) { safe_at(filament_sub_type, i, empty_str));
nfc_info = json["result"]["status"]["filament_detect"]["info"]; tray.tray_color = safe_at(filament_color, i, default_color);
}
static const std::string empty_str; auto* bundle = GUI::wxGetApp().preset_bundle;
static const std::string default_color = "FFFFFFFF"; // Try to find a matching preset for this filament based on vendor, type and color.
// If not found, default to traditional search by type only or generic type mapping.
if (bundle) {
std::string vendor = safe_at(filament_vendor, i, empty_str);
std::string filament_id = find_closest_color_preset_by_vendor_and_type(bundle->filaments, vendor, tray.tray_type,
tray.tray_color);
std::vector<AmsTrayData> trays; if (!filament_id.empty()) {
trays.reserve(slot_count); tray.tray_info_idx = filament_id;
BOOST_LOG_TRIVIAL(warning) << "Filament sync: Found manufacturer-specific profile for slot " << i << ": "
for (int i = 0; i < slot_count; ++i) { << filament_id;
AmsTrayData tray; } else {
tray.slot_index = i; tray.tray_info_idx = bundle->filaments.filament_id_by_type(tray.tray_type);
tray.has_filament = filament_exist[i];
if (tray.has_filament) {
tray.tray_type = combine_filament_type(safe_at(filament_type, i, empty_str), safe_at(filament_sub_type, i, empty_str));
tray.tray_color = safe_at(filament_color, i, default_color);
auto* bundle = GUI::wxGetApp().preset_bundle;
// Try to find a matching preset for this filament based on vendor, type and color.
// If not found, default to traditional search by type only or generic type mapping.
if (bundle) {
std::string vendor = safe_at(filament_vendor, i, empty_str);
std::string filament_id = find_closest_color_preset_by_vendor_and_type(bundle->filaments, vendor, tray.tray_type,
tray.tray_color);
if (!filament_id.empty()) {
tray.tray_info_idx = filament_id;
BOOST_LOG_TRIVIAL(warning)
<< "Filament sync: Found manufacturer-specific profile for slot " << i << ": " << filament_id;
} else {
tray.tray_info_idx = bundle->filaments.filament_id_by_type(tray.tray_type);
}
} else {
tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type);
}
// Extract NFC temperature data if available
if (nfc_info.is_array() && i < static_cast<int>(nfc_info.size()) && nfc_info[i].is_object()) {
auto& nfc_slot = nfc_info[i];
std::string vendor = "NONE";
if (auto vendor_it = nfc_slot.find("VENDOR"); vendor_it != nfc_slot.end() && vendor_it->is_string()) {
vendor = vendor_it->get<std::string>();
}
if (vendor != "NONE" && !vendor.empty()) {
tray.bed_temp = read_int_or(nfc_slot, "BED_TEMP", 0);
tray.nozzle_temp = read_int_or(nfc_slot, "FIRST_LAYER_TEMP", 0);
}
}
} }
} else {
trays.emplace_back(std::move(tray)); tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type);
} }
build_ams_payload(1, slot_count - 1, trays); // Extract NFC temperature data if available
} catch (const std::exception& e) { if (nfc_info.is_array() && i < static_cast<int>(nfc_info.size()) && nfc_info[i].is_object()) {
// why: an exception escaping a detached thread is std::terminate, and firmware auto& nfc_slot = nfc_info[i];
// JSON is untrusted; mirror run_command_worker and swallow it here. std::string vendor = nfc_slot.value("VENDOR", "NONE");
BOOST_LOG_TRIVIAL(error) << "SnapmakerPrinterAgent::fetch_filament_info: unhandled exception: " << e.what(); if (vendor != "NONE" && !vendor.empty()) {
} catch (...) { tray.bed_temp = nfc_slot.value("BED_TEMP", 0);
BOOST_LOG_TRIVIAL(error) << "SnapmakerPrinterAgent::fetch_filament_info: unhandled exception"; tray.nozzle_temp = nfc_slot.value("FIRST_LAYER_TEMP", 0);
}
}
} }
}).detach();
trays.emplace_back(std::move(tray));
}
build_ams_payload(1, slot_count - 1, trays);
return true; return true;
} }
std::string SnapmakerPrinterAgent::get_camera_url() const
{
return get_connection_settings().base_url + "/server/files/camera/monitor.jpg";
}
FilamentSyncMode SnapmakerPrinterAgent::get_filament_sync_mode() const
{
if (GUI::wxGetApp().app_config->get_bool("use_printer_agents"))
return FilamentSyncMode::subscription;
return FilamentSyncMode::pull;
}
} // namespace Slic3r } // namespace Slic3r
+1 -12
View File
@@ -3,8 +3,6 @@
#include "IPrinterAgent.hpp" #include "IPrinterAgent.hpp"
#include "MoonrakerPrinterAgent.hpp" #include "MoonrakerPrinterAgent.hpp"
#include <atomic>
#include <cstdint>
#include <string> #include <string>
namespace Slic3r { namespace Slic3r {
@@ -13,25 +11,16 @@ class SnapmakerPrinterAgent final : public MoonrakerPrinterAgent
{ {
public: public:
explicit SnapmakerPrinterAgent(std::string log_dir); explicit SnapmakerPrinterAgent(std::string log_dir);
~SnapmakerPrinterAgent() override { shutdown(); } ~SnapmakerPrinterAgent() override = default;
static AgentInfo get_agent_info_static(); static AgentInfo get_agent_info_static();
AgentInfo get_agent_info() override { return get_agent_info_static(); } AgentInfo get_agent_info() override { return get_agent_info_static(); }
bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override; bool fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode = FilamentSyncMode::pull) override;
FilamentSyncMode get_filament_sync_mode() const override;
int command_start_camera(std::string dev_id) override;
CameraStreamMode get_camera_stream_mode() const override { return CameraStreamMode::http_snapshot; }
std::string get_camera_url() const override;
private: private:
// Combine filament_type + filament_sub_type into a unified type string // Combine filament_type + filament_sub_type into a unified type string
static std::string combine_filament_type(const std::string& type, const std::string& sub_type); static std::string combine_filament_type(const std::string& type, const std::string& sub_type);
void start_camera_monitor();
void on_status_loop_tick(const std::string& dev_id) override;
std::atomic<int64_t> m_camera_last_fire_ms{0};
}; };
} // namespace Slic3r } // namespace Slic3r
+2 -2
View File
@@ -16,12 +16,12 @@
namespace Slic3r { namespace Slic3r {
namespace Utils { namespace Utils {
using boost::asio::ip::tcp;
// Generic command / response TCP telnet like console class. // Generic command / response TCP telnet like console class.
// Used by the MKS host to send G-code commands to test connection ("M105") and to start printing ("M23 filename", "M24"). // Used by the MKS host to send G-code commands to test connection ("M105") and to start printing ("M23 filename", "M24").
class TCPConsole class TCPConsole
{ {
using tcp = boost::asio::ip::tcp;
public: public:
TCPConsole() : m_resolver(m_io_context), m_socket(m_io_context) { set_defaults(); } TCPConsole() : m_resolver(m_io_context), m_socket(m_io_context) { set_defaults(); }
TCPConsole(const std::string& host_name, const std::string& port_name) : m_resolver(m_io_context), m_socket(m_io_context) TCPConsole(const std::string& host_name, const std::string& port_name) : m_resolver(m_io_context), m_socket(m_io_context)
+11 -16
View File
@@ -16,11 +16,6 @@
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <chrono> #include <chrono>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
class WebSocketClient { class WebSocketClient {
public: public:
@@ -36,7 +31,7 @@ public:
} }
try { try {
// Close the WebSocket connection // Close the WebSocket connection
ws_.close(websocket::close_code::normal); ws_.close(boost::beast::websocket::close_code::normal);
} catch (const std::exception& e) { } catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl; std::cerr << "Error: " << e.what() << std::endl;
} }
@@ -49,7 +44,7 @@ public:
auto const results = resolver_.resolve(host, port); auto const results = resolver_.resolve(host, port);
// Make the connection on the IP address we get from a lookup // Make the connection on the IP address we get from a lookup
auto ep = net::connect(ws_.next_layer(), results); auto ep = boost::asio::connect(ws_.next_layer(), results);
std::string _host = host; std::string _host = host;
//if _host last char is '/', remove it //if _host last char is '/', remove it
if(_host.size()>0&&_host[host.size()-1] == '/'){ if(_host.size()>0&&_host[host.size()-1] == '/'){
@@ -58,10 +53,10 @@ public:
// _host += ':' + std::to_string(ep.port()); // _host += ':' + std::to_string(ep.port());
// Set a decorator to change the User-Agent of the handshake // Set a decorator to change the User-Agent of the handshake
ws_.set_option(websocket::stream_base::decorator( ws_.set_option(boost::beast::websocket::stream_base::decorator(
[](websocket::request_type& req) [](boost::beast::websocket::request_type& req)
{ {
req.set(http::field::user_agent,"ElegooSlicer"); req.set(boost::beast::http::field::user_agent,"ElegooSlicer");
})); }));
// Perform the WebSocket handshake // Perform the WebSocket handshake
ws_.handshake(_host, path); ws_.handshake(_host, path);
@@ -70,25 +65,25 @@ public:
void send(const std::string& message){ void send(const std::string& message){
// Send a message // Send a message
ws_.write(net::buffer(message)); ws_.write(boost::asio::buffer(message));
} }
std::string receive(int timeout = 0){ std::string receive(int timeout = 0){
// This buffer will hold the incoming message // This buffer will hold the incoming message
beast::flat_buffer buffer; boost::beast::flat_buffer buffer;
// Read a message into our buffer // Read a message into our buffer
ws_.read(buffer); ws_.read(buffer);
// Return the message as a string // Return the message as a string
return beast::buffers_to_string(buffer.data()); return boost::beast::buffers_to_string(buffer.data());
} }
private: private:
net::io_context ioc_; boost::asio::io_context ioc_;
tcp::resolver resolver_; boost::asio::ip::tcp::resolver resolver_;
websocket::stream<tcp::socket> ws_; boost::beast::websocket::stream<boost::asio::ip::tcp::socket> ws_;
bool is_connect; bool is_connect;
}; };
+58 -60
View File
@@ -17,20 +17,18 @@
#include <map> #include <map>
#include <unordered_map> #include <unordered_map>
using json = nlohmann::json;
// Put serializers in correct ADL namespaces for each type // Put serializers in correct ADL namespaces for each type
namespace Slic3r { namespace Slic3r {
namespace FilamentGroupUtils { namespace FilamentGroupUtils {
inline void to_json(json& j, const Color& c) { inline void to_json(nlohmann::json& j, const Color& c) {
char buf[10]; char buf[10];
snprintf(buf, sizeof(buf), "#%02X%02X%02X%02X", c.r, c.g, c.b, c.a); snprintf(buf, sizeof(buf), "#%02X%02X%02X%02X", c.r, c.g, c.b, c.a);
j = std::string(buf); j = std::string(buf);
} }
inline void from_json(const json& j, Color& c) { inline void from_json(const nlohmann::json& j, Color& c) {
std::string s = j.get<std::string>(); std::string s = j.get<std::string>();
if (s.size() >= 7 && s[0] == '#') { if (s.size() >= 7 && s[0] == '#') {
c.r = (unsigned char)std::stoi(s.substr(1, 2), nullptr, 16); c.r = (unsigned char)std::stoi(s.substr(1, 2), nullptr, 16);
@@ -40,8 +38,8 @@ inline void from_json(const json& j, Color& c) {
} }
} }
inline void to_json(json& j, const FilamentInfo& fi) { inline void to_json(nlohmann::json& j, const FilamentInfo& fi) {
j = json{ j = nlohmann::json{
{"color", fi.color}, {"color", fi.color},
{"type", fi.type}, {"type", fi.type},
{"is_support", fi.is_support}, {"is_support", fi.is_support},
@@ -49,15 +47,15 @@ inline void to_json(json& j, const FilamentInfo& fi) {
}; };
} }
inline void from_json(const json& j, FilamentInfo& fi) { inline void from_json(const nlohmann::json& j, FilamentInfo& fi) {
fi.color = j.at("color").get<Color>(); fi.color = j.at("color").get<Color>();
j.at("type").get_to(fi.type); j.at("type").get_to(fi.type);
j.at("is_support").get_to(fi.is_support); j.at("is_support").get_to(fi.is_support);
fi.usage_type = (FilamentUsageType)j.at("usage_type").get<int>(); fi.usage_type = (FilamentUsageType)j.at("usage_type").get<int>();
} }
inline void to_json(json& j, const MachineFilamentInfo& mfi) { inline void to_json(nlohmann::json& j, const MachineFilamentInfo& mfi) {
j = json{ j = nlohmann::json{
{"color", mfi.color}, {"color", mfi.color},
{"type", mfi.type}, {"type", mfi.type},
{"is_support", mfi.is_support}, {"is_support", mfi.is_support},
@@ -67,7 +65,7 @@ inline void to_json(json& j, const MachineFilamentInfo& mfi) {
}; };
} }
inline void from_json(const json& j, MachineFilamentInfo& mfi) { inline void from_json(const nlohmann::json& j, MachineFilamentInfo& mfi) {
mfi.color = j.at("color").get<Color>(); mfi.color = j.at("color").get<Color>();
j.at("type").get_to(mfi.type); j.at("type").get_to(mfi.type);
j.at("is_support").get_to(mfi.is_support); j.at("is_support").get_to(mfi.is_support);
@@ -80,8 +78,8 @@ inline void from_json(const json& j, MachineFilamentInfo& mfi) {
namespace MultiNozzleUtils { namespace MultiNozzleUtils {
inline void to_json(json& j, const NozzleInfo& ni) { inline void to_json(nlohmann::json& j, const NozzleInfo& ni) {
j = json{ j = nlohmann::json{
{"diameter", ni.diameter}, {"diameter", ni.diameter},
{"volume_type", (int)ni.volume_type}, {"volume_type", (int)ni.volume_type},
{"extruder_id", ni.extruder_id}, {"extruder_id", ni.extruder_id},
@@ -89,15 +87,15 @@ inline void to_json(json& j, const NozzleInfo& ni) {
}; };
} }
inline void from_json(const json& j, NozzleInfo& ni) { inline void from_json(const nlohmann::json& j, NozzleInfo& ni) {
j.at("diameter").get_to(ni.diameter); j.at("diameter").get_to(ni.diameter);
ni.volume_type = (NozzleVolumeType)j.at("volume_type").get<int>(); ni.volume_type = (NozzleVolumeType)j.at("volume_type").get<int>();
j.at("extruder_id").get_to(ni.extruder_id); j.at("extruder_id").get_to(ni.extruder_id);
j.at("group_id").get_to(ni.group_id); j.at("group_id").get_to(ni.group_id);
} }
inline void to_json(json& j, const FilamentChangeTimeParams& p) { inline void to_json(nlohmann::json& j, const FilamentChangeTimeParams& p) {
j = json{ j = nlohmann::json{
{"selector_load_time", p.selector_load_time}, {"selector_load_time", p.selector_load_time},
{"selector_unload_time", p.selector_unload_time}, {"selector_unload_time", p.selector_unload_time},
{"standard_load_time", p.standard_load_time}, {"standard_load_time", p.standard_load_time},
@@ -105,7 +103,7 @@ inline void to_json(json& j, const FilamentChangeTimeParams& p) {
}; };
} }
inline void from_json(const json& j, FilamentChangeTimeParams& p) { inline void from_json(const nlohmann::json& j, FilamentChangeTimeParams& p) {
j.at("selector_load_time").get_to(p.selector_load_time); j.at("selector_load_time").get_to(p.selector_load_time);
j.at("selector_unload_time").get_to(p.selector_unload_time); j.at("selector_unload_time").get_to(p.selector_unload_time);
j.at("standard_load_time").get_to(p.standard_load_time); j.at("standard_load_time").get_to(p.standard_load_time);
@@ -116,22 +114,22 @@ inline void from_json(const json& j, FilamentChangeTimeParams& p) {
// ============ Helper: set<int> as JSON array ============ // ============ Helper: set<int> as JSON array ============
namespace FGTestDetail { namespace FGTestDetail {
inline json set_to_json(const std::set<int>& s) { inline nlohmann::json set_to_json(const std::set<int>& s) {
return json(std::vector<int>(s.begin(), s.end())); return nlohmann::json(std::vector<int>(s.begin(), s.end()));
} }
inline std::set<int> json_to_set(const json& j) { inline std::set<int> json_to_set(const nlohmann::json& j) {
auto v = j.get<std::vector<int>>(); auto v = j.get<std::vector<int>>();
return std::set<int>(v.begin(), v.end()); return std::set<int>(v.begin(), v.end());
} }
inline json nvt_set_to_json(const std::set<NozzleVolumeType>& s) { inline nlohmann::json nvt_set_to_json(const std::set<NozzleVolumeType>& s) {
std::vector<int> v; std::vector<int> v;
for (auto t : s) v.push_back((int)t); for (auto t : s) v.push_back((int)t);
return json(v); return nlohmann::json(v);
} }
inline std::set<NozzleVolumeType> json_to_nvt_set(const json& j) { inline std::set<NozzleVolumeType> json_to_nvt_set(const nlohmann::json& j) {
std::set<NozzleVolumeType> s; std::set<NozzleVolumeType> s;
for (auto& item : j) s.insert((NozzleVolumeType)item.get<int>()); for (auto& item : j) s.insert((NozzleVolumeType)item.get<int>());
return s; return s;
@@ -139,28 +137,28 @@ inline std::set<NozzleVolumeType> json_to_nvt_set(const json& j) {
} // namespace FGTestDetail } // namespace FGTestDetail
// ============ FilamentGroupContext::ModelInfo ============ // ============ FilamentGroupContext::ModelInfo ============
inline void to_json(json& j, const FilamentGroupContext::ModelInfo& mi) { inline void to_json(nlohmann::json& j, const FilamentGroupContext::ModelInfo& mi) {
using namespace FGTestDetail; using namespace FGTestDetail;
j["flush_matrix"] = mi.flush_matrix; j["flush_matrix"] = mi.flush_matrix;
j["layer_filaments"] = mi.layer_filaments; j["layer_filaments"] = mi.layer_filaments;
j["filament_info"] = json::array(); j["filament_info"] = nlohmann::json::array();
for (auto& fi : mi.filament_info) for (auto& fi : mi.filament_info)
j["filament_info"].push_back(fi); j["filament_info"].push_back(fi);
j["filament_ids"] = mi.filament_ids; j["filament_ids"] = mi.filament_ids;
j["unprintable_filaments"] = json::array(); j["unprintable_filaments"] = nlohmann::json::array();
for (auto& s : mi.unprintable_filaments) for (auto& s : mi.unprintable_filaments)
j["unprintable_filaments"].push_back(set_to_json(s)); j["unprintable_filaments"].push_back(set_to_json(s));
json uv = json::object(); nlohmann::json uv = nlohmann::json::object();
for (auto& [fil, types] : mi.unprintable_volumes) for (auto& [fil, types] : mi.unprintable_volumes)
uv[std::to_string(fil)] = nvt_set_to_json(types); uv[std::to_string(fil)] = nvt_set_to_json(types);
j["unprintable_volumes"] = uv; j["unprintable_volumes"] = uv;
} }
inline void from_json(const json& j, FilamentGroupContext::ModelInfo& mi) { inline void from_json(const nlohmann::json& j, FilamentGroupContext::ModelInfo& mi) {
using namespace FGTestDetail; using namespace FGTestDetail;
j.at("flush_matrix").get_to(mi.flush_matrix); j.at("flush_matrix").get_to(mi.flush_matrix);
j.at("layer_filaments").get_to(mi.layer_filaments); j.at("layer_filaments").get_to(mi.layer_filaments);
@@ -183,8 +181,8 @@ inline void from_json(const json& j, FilamentGroupContext::ModelInfo& mi) {
} }
// ============ FilamentGroupContext::GroupInfo ============ // ============ FilamentGroupContext::GroupInfo ============
inline void to_json(json& j, const FilamentGroupContext::GroupInfo& gi) { inline void to_json(nlohmann::json& j, const FilamentGroupContext::GroupInfo& gi) {
j = json{ j = nlohmann::json{
{"total_filament_num", gi.total_filament_num}, {"total_filament_num", gi.total_filament_num},
{"max_gap_threshold", gi.max_gap_threshold}, {"max_gap_threshold", gi.max_gap_threshold},
{"mode", (int)gi.mode}, {"mode", (int)gi.mode},
@@ -195,7 +193,7 @@ inline void to_json(json& j, const FilamentGroupContext::GroupInfo& gi) {
}; };
} }
inline void from_json(const json& j, FilamentGroupContext::GroupInfo& gi) { inline void from_json(const nlohmann::json& j, FilamentGroupContext::GroupInfo& gi) {
j.at("total_filament_num").get_to(gi.total_filament_num); j.at("total_filament_num").get_to(gi.total_filament_num);
j.at("max_gap_threshold").get_to(gi.max_gap_threshold); j.at("max_gap_threshold").get_to(gi.max_gap_threshold);
gi.mode = (FGMode)j.at("mode").get<int>(); gi.mode = (FGMode)j.at("mode").get<int>();
@@ -206,12 +204,12 @@ inline void from_json(const json& j, FilamentGroupContext::GroupInfo& gi) {
} }
// ============ FilamentGroupContext::MachineInfo ============ // ============ FilamentGroupContext::MachineInfo ============
inline void to_json(json& j, const FilamentGroupContext::MachineInfo& mi) { inline void to_json(nlohmann::json& j, const FilamentGroupContext::MachineInfo& mi) {
j["max_group_size"] = mi.max_group_size; j["max_group_size"] = mi.max_group_size;
j["machine_filament_info"] = json::array(); j["machine_filament_info"] = nlohmann::json::array();
for (auto& vec : mi.machine_filament_info) { for (auto& vec : mi.machine_filament_info) {
json arr = json::array(); nlohmann::json arr = nlohmann::json::array();
for (auto& mfi : vec) arr.push_back(mfi); for (auto& mfi : vec) arr.push_back(mfi);
j["machine_filament_info"].push_back(arr); j["machine_filament_info"].push_back(arr);
} }
@@ -220,7 +218,7 @@ inline void to_json(json& j, const FilamentGroupContext::MachineInfo& mi) {
j["master_extruder_id"] = mi.master_extruder_id; j["master_extruder_id"] = mi.master_extruder_id;
} }
inline void from_json(const json& j, FilamentGroupContext::MachineInfo& mi) { inline void from_json(const nlohmann::json& j, FilamentGroupContext::MachineInfo& mi) {
j.at("max_group_size").get_to(mi.max_group_size); j.at("max_group_size").get_to(mi.max_group_size);
mi.machine_filament_info.clear(); mi.machine_filament_info.clear();
@@ -236,10 +234,10 @@ inline void from_json(const json& j, FilamentGroupContext::MachineInfo& mi) {
} }
// ============ FilamentGroupContext::SpeedInfo ============ // ============ FilamentGroupContext::SpeedInfo ============
inline void to_json(json& j, const FilamentGroupContext::SpeedInfo& si) { inline void to_json(nlohmann::json& j, const FilamentGroupContext::SpeedInfo& si) {
json fpt = json::object(); nlohmann::json fpt = nlohmann::json::object();
for (auto& [fil, inner] : si.filament_print_time) { for (auto& [fil, inner] : si.filament_print_time) {
json inner_j = json::object(); nlohmann::json inner_j = nlohmann::json::object();
for (auto& [layer, time] : inner) for (auto& [layer, time] : inner)
inner_j[std::to_string(layer)] = time; inner_j[std::to_string(layer)] = time;
fpt[std::to_string(fil)] = inner_j; fpt[std::to_string(fil)] = inner_j;
@@ -252,7 +250,7 @@ inline void to_json(json& j, const FilamentGroupContext::SpeedInfo& si) {
j["ams_preload_enabled"] = si.ams_preload_enabled; j["ams_preload_enabled"] = si.ams_preload_enabled;
} }
inline void from_json(const json& j, FilamentGroupContext::SpeedInfo& si) { inline void from_json(const nlohmann::json& j, FilamentGroupContext::SpeedInfo& si) {
si.filament_print_time.clear(); si.filament_print_time.clear();
if (j.contains("filament_print_time")) { if (j.contains("filament_print_time")) {
for (auto& [k, v] : j.at("filament_print_time").items()) { for (auto& [k, v] : j.at("filament_print_time").items()) {
@@ -269,23 +267,23 @@ inline void from_json(const json& j, FilamentGroupContext::SpeedInfo& si) {
} }
// ============ FilamentGroupContext::NozzleInfo ============ // ============ FilamentGroupContext::NozzleInfo ============
inline void to_json(json& j, const FilamentGroupContext::NozzleInfo& ni) { inline void to_json(nlohmann::json& j, const FilamentGroupContext::NozzleInfo& ni) {
json enl = json::object(); nlohmann::json enl = nlohmann::json::object();
for (auto& [ext, nozzles] : ni.extruder_nozzle_list) for (auto& [ext, nozzles] : ni.extruder_nozzle_list)
enl[std::to_string(ext)] = nozzles; enl[std::to_string(ext)] = nozzles;
j["extruder_nozzle_list"] = enl; j["extruder_nozzle_list"] = enl;
j["nozzle_list"] = json::array(); j["nozzle_list"] = nlohmann::json::array();
for (auto& n : ni.nozzle_list) for (auto& n : ni.nozzle_list)
j["nozzle_list"].push_back(n); j["nozzle_list"].push_back(n);
json ns = json::object(); nlohmann::json ns = nlohmann::json::object();
for (auto& [noz, fil] : ni.nozzle_status) for (auto& [noz, fil] : ni.nozzle_status)
ns[std::to_string(noz)] = fil; ns[std::to_string(noz)] = fil;
j["nozzle_status"] = ns; j["nozzle_status"] = ns;
} }
inline void from_json(const json& j, FilamentGroupContext::NozzleInfo& ni) { inline void from_json(const nlohmann::json& j, FilamentGroupContext::NozzleInfo& ni) {
ni.extruder_nozzle_list.clear(); ni.extruder_nozzle_list.clear();
for (auto& [k, v] : j.at("extruder_nozzle_list").items()) for (auto& [k, v] : j.at("extruder_nozzle_list").items())
ni.extruder_nozzle_list[std::stoi(k)] = v.get<std::vector<int>>(); ni.extruder_nozzle_list[std::stoi(k)] = v.get<std::vector<int>>();
@@ -302,8 +300,8 @@ inline void from_json(const json& j, FilamentGroupContext::NozzleInfo& ni) {
} }
// ============ Full FilamentGroupContext ============ // ============ Full FilamentGroupContext ============
inline void to_json(json& j, const FilamentGroupContext& ctx) { inline void to_json(nlohmann::json& j, const FilamentGroupContext& ctx) {
json mi, gi, mai, si, ni; nlohmann::json mi, gi, mai, si, ni;
to_json(mi, ctx.model_info); to_json(mi, ctx.model_info);
to_json(gi, ctx.group_info); to_json(gi, ctx.group_info);
to_json(mai, ctx.machine_info); to_json(mai, ctx.machine_info);
@@ -316,7 +314,7 @@ inline void to_json(json& j, const FilamentGroupContext& ctx) {
j["nozzle_info"] = ni; j["nozzle_info"] = ni;
} }
inline void from_json(const json& j, FilamentGroupContext& ctx) { inline void from_json(const nlohmann::json& j, FilamentGroupContext& ctx) {
from_json(j.at("model_info"), ctx.model_info); from_json(j.at("model_info"), ctx.model_info);
from_json(j.at("group_info"), ctx.group_info); from_json(j.at("group_info"), ctx.group_info);
from_json(j.at("machine_info"), ctx.machine_info); from_json(j.at("machine_info"), ctx.machine_info);
@@ -336,11 +334,11 @@ struct TestMetadata {
int seed = 0; int seed = 0;
}; };
inline void to_json(json& j, const TestMetadata& m) { inline void to_json(nlohmann::json& j, const TestMetadata& m) {
j = json{{"id", m.id}, {"config_type", m.config_type}, {"seed", m.seed}}; j = nlohmann::json{{"id", m.id}, {"config_type", m.config_type}, {"seed", m.seed}};
} }
inline void from_json(const json& j, TestMetadata& m) { inline void from_json(const nlohmann::json& j, TestMetadata& m) {
j.at("id").get_to(m.id); j.at("id").get_to(m.id);
j.at("config_type").get_to(m.config_type); j.at("config_type").get_to(m.config_type);
j.at("seed").get_to(m.seed); j.at("seed").get_to(m.seed);
@@ -354,8 +352,8 @@ struct TestResult {
std::vector<std::string> violations; std::vector<std::string> violations;
}; };
inline void to_json(json& j, const TestResult& r) { inline void to_json(nlohmann::json& j, const TestResult& r) {
j = json{ j = nlohmann::json{
{"filament_map", r.filament_map}, {"filament_map", r.filament_map},
{"flush_cost", r.flush_cost}, {"flush_cost", r.flush_cost},
{"elapsed_ms", r.elapsed_ms}, {"elapsed_ms", r.elapsed_ms},
@@ -364,7 +362,7 @@ inline void to_json(json& j, const TestResult& r) {
}; };
} }
inline void from_json(const json& j, TestResult& r) { inline void from_json(const nlohmann::json& j, TestResult& r) {
j.at("filament_map").get_to(r.filament_map); j.at("filament_map").get_to(r.filament_map);
j.at("flush_cost").get_to(r.flush_cost); j.at("flush_cost").get_to(r.flush_cost);
j.at("elapsed_ms").get_to(r.elapsed_ms); j.at("elapsed_ms").get_to(r.elapsed_ms);
@@ -380,15 +378,15 @@ struct BaseResult {
bool constraints_ok = true; bool constraints_ok = true;
}; };
inline void to_json(json& j, const BaseResult& g) { inline void to_json(nlohmann::json& j, const BaseResult& g) {
j = json{ j = nlohmann::json{
{"full_score", g.full_score}, {"full_score", g.full_score},
{"flush_cost", g.flush_cost}, {"flush_cost", g.flush_cost},
{"constraints_ok", g.constraints_ok} {"constraints_ok", g.constraints_ok}
}; };
} }
inline void from_json(const json& j, BaseResult& g) { inline void from_json(const nlohmann::json& j, BaseResult& g) {
j.at("full_score").get_to(g.full_score); j.at("full_score").get_to(g.full_score);
j.at("flush_cost").get_to(g.flush_cost); j.at("flush_cost").get_to(g.flush_cost);
j.at("constraints_ok").get_to(g.constraints_ok); j.at("constraints_ok").get_to(g.constraints_ok);
@@ -403,7 +401,7 @@ struct TestCase {
inline TestCase load_test_case(const std::string& path) { inline TestCase load_test_case(const std::string& path) {
std::ifstream f(path); std::ifstream f(path);
json j = json::parse(f); nlohmann::json j = nlohmann::json::parse(f);
TestCase tc; TestCase tc;
tc.metadata = j.at("metadata").get<TestMetadata>(); tc.metadata = j.at("metadata").get<TestMetadata>();
Slic3r::from_json(j.at("context"), tc.context); Slic3r::from_json(j.at("context"), tc.context);
@@ -413,9 +411,9 @@ inline TestCase load_test_case(const std::string& path) {
} }
inline void save_test_case(const std::string& path, const TestCase& tc) { inline void save_test_case(const std::string& path, const TestCase& tc) {
json j; nlohmann::json j;
j["metadata"] = tc.metadata; j["metadata"] = tc.metadata;
json ctx_j; nlohmann::json ctx_j;
Slic3r::to_json(ctx_j, tc.context); Slic3r::to_json(ctx_j, tc.context);
j["context"] = ctx_j; j["context"] = ctx_j;
if (tc.base_result) if (tc.base_result)
@@ -432,14 +430,14 @@ inline void save_result(const std::string& case_path, const TestResult& result)
else else
result_path += ".result.json"; result_path += ".result.json";
json j = result; nlohmann::json j = result;
std::ofstream f(result_path); std::ofstream f(result_path);
f << j.dump(2); f << j.dump(2);
} }
inline TestResult load_result(const std::string& result_path) { inline TestResult load_result(const std::string& result_path) {
std::ifstream f(result_path); std::ifstream f(result_path);
json j = json::parse(f); nlohmann::json j = nlohmann::json::parse(f);
return j.get<TestResult>(); return j.get<TestResult>();
} }
+2
View File
@@ -31,6 +31,8 @@
#include "libslic3r/BoundingBox.hpp" #include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ExtrusionEntity.hpp" #include "libslic3r/ExtrusionEntity.hpp"
using namespace Slic3r;
namespace { namespace {
const char *const BELOW_PAD_TEST_OBJECTS[] = { const char *const BELOW_PAD_TEST_OBJECTS[] = {
+2
View File
@@ -36,6 +36,8 @@
#include "libslic3r/BoundingBox.hpp" #include "libslic3r/BoundingBox.hpp"
#include "libslic3r/Line.hpp" #include "libslic3r/Line.hpp"
using namespace Slic3r;
void test_support_model_collision(const std::string &obj_filename, void test_support_model_collision(const std::string &obj_filename,
const sla::SupportTreeConfig &input_supportcfg, const sla::SupportTreeConfig &input_supportcfg,
const sla::HollowingConfig &hollowingcfg, const sla::HollowingConfig &hollowingcfg,
+36 -38
View File
@@ -33,33 +33,31 @@ namespace Slic3r::sla { struct PadConfig; }
namespace Slic3r::sla { struct SupportTreeConfig; } namespace Slic3r::sla { struct SupportTreeConfig; }
using namespace Slic3r;
enum e_validity { enum e_validity {
ASSUME_NO_EMPTY = 1, ASSUME_NO_EMPTY = 1,
ASSUME_MANIFOLD = 2, ASSUME_MANIFOLD = 2,
ASSUME_NO_REPAIR = 4 ASSUME_NO_REPAIR = 4
}; };
void check_validity(const TriangleMesh &input_mesh, void check_validity(const Slic3r::TriangleMesh &input_mesh,
int flags = ASSUME_NO_EMPTY | ASSUME_MANIFOLD | int flags = ASSUME_NO_EMPTY | ASSUME_MANIFOLD |
ASSUME_NO_REPAIR); ASSUME_NO_REPAIR);
struct PadByproducts struct PadByproducts
{ {
ExPolygons model_contours; Slic3r::ExPolygons model_contours;
ExPolygons support_contours; Slic3r::ExPolygons support_contours;
TriangleMesh mesh; Slic3r::TriangleMesh mesh;
}; };
void test_concave_hull(const ExPolygons &polys); void test_concave_hull(const Slic3r::ExPolygons &polys);
void test_pad(const std::string & obj_filename, void test_pad(const std::string & obj_filename,
const sla::PadConfig &padcfg, const Slic3r::sla::PadConfig &padcfg,
PadByproducts & out); PadByproducts & out);
inline void test_pad(const std::string & obj_filename, inline void test_pad(const std::string & obj_filename,
const sla::PadConfig &padcfg = {}) const Slic3r::sla::PadConfig &padcfg = {})
{ {
PadByproducts byproducts; PadByproducts byproducts;
test_pad(obj_filename, padcfg, byproducts); test_pad(obj_filename, padcfg, byproducts);
@@ -69,53 +67,53 @@ struct SupportByproducts
{ {
std::string obj_fname; std::string obj_fname;
std::vector<float> slicegrid; std::vector<float> slicegrid;
std::vector<ExPolygons> model_slices; std::vector<Slic3r::ExPolygons> model_slices;
sla::SupportTreeBuilder supporttree; Slic3r::sla::SupportTreeBuilder supporttree;
TriangleMesh input_mesh; Slic3r::TriangleMesh input_mesh;
}; };
const constexpr float CLOSING_RADIUS = 0.005f; const constexpr float CLOSING_RADIUS = 0.005f;
void check_support_tree_integrity(const sla::SupportTreeBuilder &stree, void check_support_tree_integrity(const Slic3r::sla::SupportTreeBuilder &stree,
const sla::SupportTreeConfig &cfg); const Slic3r::sla::SupportTreeConfig &cfg);
void test_supports(const std::string &obj_filename, void test_supports(const std::string &obj_filename,
const sla::SupportTreeConfig &supportcfg, const Slic3r::sla::SupportTreeConfig &supportcfg,
const sla::HollowingConfig &hollowingcfg, const Slic3r::sla::HollowingConfig &hollowingcfg,
const sla::DrainHoles &drainholes, const Slic3r::sla::DrainHoles &drainholes,
SupportByproducts &out); SupportByproducts &out);
inline void test_supports(const std::string &obj_filename, inline void test_supports(const std::string &obj_filename,
const sla::SupportTreeConfig &supportcfg, const Slic3r::sla::SupportTreeConfig &supportcfg,
SupportByproducts &out) SupportByproducts &out)
{ {
sla::HollowingConfig hcfg; Slic3r::sla::HollowingConfig hcfg;
hcfg.enabled = false; hcfg.enabled = false;
test_supports(obj_filename, supportcfg, hcfg, {}, out); test_supports(obj_filename, supportcfg, hcfg, {}, out);
} }
inline void test_supports(const std::string &obj_filename, inline void test_supports(const std::string &obj_filename,
const sla::SupportTreeConfig &supportcfg = {}) const Slic3r::sla::SupportTreeConfig &supportcfg = {})
{ {
SupportByproducts byproducts; SupportByproducts byproducts;
test_supports(obj_filename, supportcfg, byproducts); test_supports(obj_filename, supportcfg, byproducts);
} }
void export_failed_case(const std::vector<ExPolygons> &support_slices, void export_failed_case(const std::vector<Slic3r::ExPolygons> &support_slices,
const SupportByproducts &byproducts); const SupportByproducts &byproducts);
void test_support_model_collision( void test_support_model_collision(
const std::string &obj_filename, const std::string &obj_filename,
const sla::SupportTreeConfig &input_supportcfg, const Slic3r::sla::SupportTreeConfig &input_supportcfg,
const sla::HollowingConfig &hollowingcfg, const Slic3r::sla::HollowingConfig &hollowingcfg,
const sla::DrainHoles &drainholes); const Slic3r::sla::DrainHoles &drainholes);
inline void test_support_model_collision( inline void test_support_model_collision(
const std::string &obj_filename, const std::string &obj_filename,
const sla::SupportTreeConfig &input_supportcfg = {}) const Slic3r::sla::SupportTreeConfig &input_supportcfg = {})
{ {
sla::HollowingConfig hcfg; Slic3r::sla::HollowingConfig hcfg;
hcfg.enabled = false; hcfg.enabled = false;
test_support_model_collision(obj_filename, input_supportcfg, hcfg, {}); test_support_model_collision(obj_filename, input_supportcfg, hcfg, {});
} }
@@ -156,8 +154,8 @@ template <class I, class II> void test_pairhash()
REQUIRE(a != b); REQUIRE(a != b);
II hash_ab = sla::pairhash<I, II>(a, b); II hash_ab = Slic3r::sla::pairhash<I, II>(a, b);
II hash_ba = sla::pairhash<I, II>(b, a); II hash_ba = Slic3r::sla::pairhash<I, II>(b, a);
REQUIRE(hash_ab == hash_ba); REQUIRE(hash_ab == hash_ba);
auto it = ints.find(hash_ab); auto it = ints.find(hash_ab);
@@ -180,23 +178,23 @@ static constexpr const TPixel FullBlack = 0;
template <class A, int N> constexpr int arraysize(const A (&)[N]) { return N; } template <class A, int N> constexpr int arraysize(const A (&)[N]) { return N; }
void check_raster_transformations(sla::RasterBase::Orientation o, void check_raster_transformations(Slic3r::sla::RasterBase::Orientation o,
sla::RasterBase::TMirroring mirroring); Slic3r::sla::RasterBase::TMirroring mirroring);
ExPolygon square_with_hole(double v); Slic3r::ExPolygon square_with_hole(double v);
inline double pixel_area(TPixel px, const sla::PixelDim &pxdim) inline double pixel_area(TPixel px, const Slic3r::sla::PixelDim &pxdim)
{ {
return (pxdim.h_mm * pxdim.w_mm) * px * 1. / (FullWhite - FullBlack); return (pxdim.h_mm * pxdim.w_mm) * px * 1. / (FullWhite - FullBlack);
} }
double raster_white_area(const sla::RasterGrayscaleAA &raster); double raster_white_area(const Slic3r::sla::RasterGrayscaleAA &raster);
long raster_pxsum(const sla::RasterGrayscaleAA &raster); long raster_pxsum(const Slic3r::sla::RasterGrayscaleAA &raster);
double predict_error(const ExPolygon &p, const sla::PixelDim &pd); double predict_error(const Slic3r::ExPolygon &p, const Slic3r::sla::PixelDim &pd);
sla::SupportPoints calc_support_pts( Slic3r::sla::SupportPoints calc_support_pts(
const TriangleMesh & mesh, const Slic3r::TriangleMesh & mesh,
const sla::SupportPointGenerator::Config &cfg = {}); const Slic3r::sla::SupportPointGenerator::Config &cfg = {});
#endif // SLA_TEST_UTILS_HPP #endif // SLA_TEST_UTILS_HPP
-1
View File
@@ -25,7 +25,6 @@ add_executable(${_TEST_NAME}_tests
test_plugin_capabilities_in_use.cpp test_plugin_capabilities_in_use.cpp
test_plugin_status.cpp test_plugin_status.cpp
test_printer_agent.cpp test_printer_agent.cpp
test_qidi_printer_agent.cpp
test_plugin_install.cpp test_plugin_install.cpp
test_plugin_lifecycle.cpp test_plugin_lifecycle.cpp
test_plugin_printer_agent.cpp test_plugin_printer_agent.cpp
-384
View File
@@ -1,29 +1,18 @@
#include <catch2/catch_all.hpp> #include <catch2/catch_all.hpp>
#include <functional>
#include <slic3r/Utils/BBLPrinterAgent.hpp>
#include <slic3r/Utils/IPrinterAgent.hpp>
#include <slic3r/Utils/MoonrakerPrinterAgent.hpp>
#include <memory> #include <memory>
#include <slic3r/Utils/NetworkAgentFactory.hpp> #include <slic3r/Utils/NetworkAgentFactory.hpp>
#include <catch2/catch_test_macros.hpp> #include <catch2/catch_test_macros.hpp>
#include <pybind11/pytypes.h> #include <pybind11/pytypes.h>
#include <catch2/catch_message.hpp> #include <catch2/catch_message.hpp>
#include "catch2/catch_approx.hpp"
#include "python_test_support.hpp" #include "python_test_support.hpp"
#include <pybind11/embed.h> #include <pybind11/embed.h>
#include <pybind11/pybind11.h> #include <pybind11/pybind11.h>
#include <atomic>
#include <chrono>
#include <future>
#include <slic3r/Utils/bambu_networking.hpp>
#include <string> #include <string>
#include <thread>
#include <pybind11/cast.h> #include <pybind11/cast.h>
#include <utility>
namespace Slic3r { class ICloudServiceAgent; } namespace Slic3r { class ICloudServiceAgent; }
namespace Slic3r { class IPrinterAgent; } namespace Slic3r { class IPrinterAgent; }
@@ -31,379 +20,6 @@ namespace Slic3r { class IPrinterAgent; }
using namespace Slic3r; using namespace Slic3r;
namespace py = pybind11; namespace py = pybind11;
namespace {
// Releases a promise on scope exit, so a throwing REQUIRE cannot leave a parked detached
// thread (and any destructor that joins it) blocked forever.
class ScopedPromiseRelease
{
public:
explicit ScopedPromiseRelease(std::shared_ptr<std::promise<void>> p) : m_p(std::move(p)) {}
~ScopedPromiseRelease()
{
if (m_p) {
try {
m_p->set_value();
} catch (...) {
// promise already satisfied
}
}
}
ScopedPromiseRelease(const ScopedPromiseRelease&) = delete;
ScopedPromiseRelease& operator=(const ScopedPromiseRelease&) = delete;
private:
std::shared_ptr<std::promise<void>> m_p;
};
} // namespace
class MoonrakerParserProbe : public MoonrakerPrinterAgent
{
public:
using MoonrakerPrinterAgent::parse_nozzle_diameter;
explicit MoonrakerParserProbe(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {}
};
TEST_CASE("Moonraker parses nozzle diameter from configfile settings", "[unit][moonraker]")
{
const auto response = nlohmann::json::parse(R"({
"result": {
"status": {
"configfile": {
"settings": {
"extruder": {
"nozzle_diameter": 0.6
}
}
}
}
}
})");
CHECK(MoonrakerParserProbe::parse_nozzle_diameter(response) == Catch::Approx(0.6f));
}
TEST_CASE("Moonraker parses nozzle diameter from raw config and tolerates missing data", "[unit][moonraker]")
{
const auto raw_config_response = nlohmann::json::parse(R"({
"result": {
"status": {
"configfile": {
"config": {
"extruder": {
"nozzle_diameter": "0.8"
}
}
}
}
}
})");
const auto missing_response = nlohmann::json::object();
CHECK(MoonrakerParserProbe::parse_nozzle_diameter(raw_config_response) == Catch::Approx(0.8f));
CHECK(MoonrakerParserProbe::parse_nozzle_diameter(missing_response) == 0.0f);
}
// why: an agent without a Bambu-dialect translation must refuse these commands before any network or wx path.
TEST_CASE("unit: default AMS commands report not supported", "[unit][moonraker]")
{
MoonrakerPrinterAgent agent("");
CHECK(agent.command_ams_refresh_rfid("dev", 123, 1, 0, false) == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
CHECK(agent.command_ams_calibrate("dev", 1, 2, false) == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
CHECK(agent.command_ams_select_tray("dev", "123", 3, false) == ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
}
TEST_CASE("unit: Moonraker light name matching", "[unit][moonraker]")
{
CHECK(moonraker_is_light_name("caselight"));
CHECK(moonraker_is_light_name("LED_STRIP"));
CHECK_FALSE(moonraker_is_light_name("beeper"));
CHECK(moonraker_is_light_name("FLASHLIGHT_SWITCH"));
CHECK(moonraker_is_light_name("MODLELIGHT_SWITCH"));
}
TEST_CASE("Moonraker webcam selection skips disabled webcams and prefers the first enabled one",
"[unit][moonraker]")
{
const auto response = nlohmann::json::parse(R"({
"result": { "webcams": [
{ "name": "disabled", "enabled": false, "stream_url": "http://192.168.1.9:8080/stream" },
{ "name": "enabled", "enabled": true, "stream_url": "http://192.168.1.9:8080/stream" }
]}
})");
MoonrakerWebcamSelection selection;
REQUIRE(moonraker_parse_webcam_list(response, "http://192.168.1.9:7125", selection));
CHECK(selection.name == "enabled");
CHECK(selection.url == "http://192.168.1.9:8080/stream");
CHECK(selection.mode == CameraStreamMode::http);
CHECK(selection.error.empty());
}
TEST_CASE("Moonraker webcam selection resolves relative URLs, maps rtsp, and rejects other schemes",
"[unit][moonraker]")
{
const auto relative = nlohmann::json::parse(R"({
"result": { "webcams": [ { "name": "cam", "snapshot_url": "/webcam/?action=snapshot" } ] }
})");
MoonrakerWebcamSelection rel;
REQUIRE(moonraker_parse_webcam_list(relative, "http://192.168.1.9:7125", rel));
// Relative URLs use the printer web root, without the Moonraker API port.
CHECK(rel.url == "http://192.168.1.9/webcam/?action=snapshot");
CHECK(rel.mode == CameraStreamMode::http_snapshot);
const auto rtsp = nlohmann::json::parse(R"({
"result": { "webcams": [ { "name": "cam", "stream_url": "rtsp://192.168.1.9:554/live" } ] }
})");
MoonrakerWebcamSelection rt;
REQUIRE(moonraker_parse_webcam_list(rtsp, "http://192.168.1.9:7125", rt));
CHECK(rt.mode == CameraStreamMode::rtsp);
const auto unsupported = nlohmann::json::parse(R"({
"result": { "webcams": [ { "name": "cam", "stream_url": "weird://host/x" } ] }
})");
MoonrakerWebcamSelection bad;
CHECK_FALSE(moonraker_parse_webcam_list(unsupported, "http://192.168.1.9:7125", bad));
CHECK(bad.error == "Unsupported webcam URL");
}
TEST_CASE("Moonraker webcam selection reports no webcam and malformed structure", "[unit][moonraker]")
{
const auto empty = nlohmann::json::parse(R"({ "result": { "webcams": [] } })");
MoonrakerWebcamSelection none;
CHECK_FALSE(moonraker_parse_webcam_list(empty, "http://host:7125", none));
CHECK(none.error == "No enabled webcam");
const auto disabled_only = nlohmann::json::parse(R"({
"result": { "webcams": [ { "name": "disabled", "enabled": false, "stream_url": "http://host/stream" } ] }
})");
MoonrakerWebcamSelection off;
CHECK_FALSE(moonraker_parse_webcam_list(disabled_only, "http://host:7125", off));
const auto malformed = nlohmann::json::parse(R"({ "result": { "nope": 1 } })");
MoonrakerWebcamSelection shape;
CHECK_FALSE(moonraker_parse_webcam_list(malformed, "http://host:7125", shape));
CHECK(shape.error == "Unexpected JSON structure");
}
// ===========================================================================
// UNIT - handle_request's not-supported default.
// The agent is the only thing that knows what it can translate, so an untranslated
// command has to say so instead of returning success and letting the UI believe the
// control worked. Guards the inverse too: the pushing namespace is genuinely
// satisfied by the websocket status stream, and it re-fires from the keepalive timer
// roughly once a second, so it must stay a success or it would raise a dialog on a
// timer. Only branches that touch neither the network nor wx are exercised.
// ===========================================================================
TEST_CASE("unit: Moonraker reports untranslated commands as not supported", "[unit][moonraker]")
{
MoonrakerPrinterAgent agent("");
CHECK(agent.send_message("dev", R"({"print":{"command":"ams_change_filament"}})", 0, 0) ==
ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
CHECK(agent.send_message("dev", R"({"system":{"command":"set_door_stat"}})", 0, 0) ==
ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
CHECK(agent.send_message("dev", R"({"xcam":{"command":"xcam_control_set"}})", 0, 0) ==
ORCA_NETWORK_ERR_CMD_NOT_SUPPORTED);
CHECK(agent.send_message("dev", R"({"pushing":{"command":"pushall"}})", 0, 0) == BAMBU_NETWORK_SUCCESS);
CHECK(agent.send_message("dev", R"({"pushing":{"command":"start"}})", 0, 0) == BAMBU_NETWORK_SUCCESS);
// why: malformed input is a different failure than an untranslated command, and the
// default must not swallow it into a misleading not-supported verdict.
CHECK(agent.send_message("dev", "{not json", 0, 0) == BAMBU_NETWORK_ERR_INVALID_RESULT);
}
// why: IPrinterAgent::fetch_filament_info is the single virtual hook derived agents override
// (MoonrakerPrinterAgent's own override is synchronous, but QidiPrinterAgent's override is
// fire-and-forget: it spawns a detached thread and returns immediately). QidiPrinterAgent is
// `final`, so this probes the same contract with a controllable double instead.
TEST_CASE("unit: a fire-and-forget override of fetch_filament_info is not waited on by the caller",
"[unit][moonraker]")
{
class RecordingAgent : public Slic3r::MoonrakerPrinterAgent
{
public:
explicit RecordingAgent(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {}
// Shared so the detached proxy fetch never touches `this`: a throwing REQUIRE
// then cannot leave it dereferencing a destroyed agent.
std::shared_ptr<std::atomic<bool>> invoked{std::make_shared<std::atomic<bool>>(false)};
std::shared_ptr<std::promise<void>> release_gate{std::make_shared<std::promise<void>>()};
std::shared_ptr<std::promise<void>> done_promise{std::make_shared<std::promise<void>>()};
bool fetch_filament_info(std::string /*dev_id*/, FilamentSyncMode /*sync_mode*/ = FilamentSyncMode::pull) override
{
auto invoked_p = invoked;
auto release_gate_p = release_gate;
auto done_promise_p = done_promise;
std::thread([invoked_p, release_gate_p, done_promise_p]() {
invoked_p->store(true);
// Block here until the test explicitly releases us, proving the caller
// (fetch_filament_info) does not wait for this to run.
release_gate_p->get_future().wait();
done_promise_p->set_value();
}).detach();
return true;
}
};
auto agent = std::make_shared<RecordingAgent>(std::string{});
auto done_future = agent->done_promise->get_future();
ScopedPromiseRelease release_gate_guard{agent->release_gate};
bool immediate_result = agent->fetch_filament_info("test-dev");
// fetch_filament_info must return before its background work completes — prove
// it by confirming the background call is still blocked on the gate right now.
REQUIRE(immediate_result == true);
REQUIRE(done_future.wait_for(std::chrono::milliseconds(100)) == std::future_status::timeout);
// Now let the background call finish and confirm it actually ran (polymorphic dispatch).
agent->release_gate->set_value();
REQUIRE(done_future.wait_for(std::chrono::seconds(2)) == std::future_status::ready);
REQUIRE(agent->invoked->load() == true);
}
namespace {
// Globals so a parked proxy fetch thread never dereferences a freed agent.
std::atomic<int> g_deferred_fetch_running{0};
std::atomic<bool> g_deferred_destroy_returned{false};
// Releases the given gates, then joins on scope exit: so a throwing REQUIRE cannot leave
// the thread blocked (deadlocking the join) or let it std::terminate.
class ScopedJoiner
{
public:
ScopedJoiner(std::thread& t, std::shared_ptr<std::promise<void>> gate1, std::shared_ptr<std::promise<void>> gate2)
: m_thread(t), m_gates{std::move(gate1), std::move(gate2)}
{}
~ScopedJoiner()
{
for (auto& gate : m_gates) {
if (gate) {
try {
gate->set_value();
} catch (...) {
// promise already satisfied
}
}
}
if (m_thread.joinable()) m_thread.join();
}
ScopedJoiner(const ScopedJoiner&) = delete;
ScopedJoiner& operator=(const ScopedJoiner&) = delete;
private:
std::thread& m_thread;
std::shared_ptr<std::promise<void>> m_gates[2];
};
// A fetch that parks before touching the in-flight counter, so teardown's wait can
// observe zero first.
class DeferredFetchAgent : public MoonrakerPrinterAgent
{
public:
explicit DeferredFetchAgent(std::string log_dir) : MoonrakerPrinterAgent(std::move(log_dir)) {}
// Shared so a parked proxy fetch can never outlive the stack that owns it.
std::shared_ptr<std::promise<void>> entered{std::make_shared<std::promise<void>>()};
std::shared_ptr<std::promise<void>> allow_fetch{std::make_shared<std::promise<void>>()};
std::shared_ptr<std::promise<void>> allow_finish{std::make_shared<std::promise<void>>()};
std::shared_ptr<std::promise<void>> running{std::make_shared<std::promise<void>>()};
// Runs the callable on the command worker, which teardown joins.
void post(std::function<void()> fn) { enqueue_command(std::move(fn)); }
bool fetch_filament_info(std::string /*dev_id*/, FilamentSyncMode /*sync_mode*/ = FilamentSyncMode::pull) override
{
// Resumes after ~DeferredFetchAgent destroyed these members; snapshot up front.
auto entered_p = entered;
auto allow_fetch_p = allow_fetch;
auto allow_finish_p = allow_finish;
auto running_p = running;
entered_p->set_value();
allow_fetch_p->get_future().wait();
filament_fetch_in_flight.fetch_add(1, std::memory_order_relaxed);
std::thread([this, finish = std::move(allow_finish_p), running = std::move(running_p)] {
struct InFlightGuard
{
MoonrakerPrinterAgent& owner;
~InFlightGuard() { owner.release_fetch_slot(); }
} guard{*this};
g_deferred_fetch_running.fetch_add(1, std::memory_order_relaxed);
running->set_value();
finish->get_future().wait();
g_deferred_fetch_running.fetch_sub(1, std::memory_order_relaxed);
}).detach();
return true;
}
};
} // namespace
// REGRESSION - teardown must not return while a fetch it started is in flight.
// The command worker parks a fetch before it reserves the in-flight slot, forcing
// the "wait already observed zero" interleaving deterministically.
TEST_CASE("an agent's destruction waits for a fetch started by its worker during teardown",
"[unit][moonraker][Regression]")
{
g_deferred_fetch_running.store(0);
g_deferred_destroy_returned.store(false);
auto agent = std::make_shared<DeferredFetchAgent>(std::string{});
auto entered = agent->entered;
auto allow_fetch = agent->allow_fetch;
auto allow_finish = agent->allow_finish;
auto running = agent->running;
// Safety net for the pre-destroyer failure paths: release both gates before the
// agent is destroyed (declared after it, so destroyed before it).
ScopedPromiseRelease release_finish{allow_finish};
ScopedPromiseRelease release_fetch{allow_fetch};
// Park a fetch inside the command worker while the agent is still complete.
agent->post([ptr = agent.get()] { ptr->fetch_filament_info("dev", FilamentSyncMode::pull); });
REQUIRE(entered->get_future().wait_for(std::chrono::seconds(5)) == std::future_status::ready);
// Destroy on another thread so this one can drive the parked fetch.
std::thread destroyer([owned = std::move(agent)]() mutable {
owned.reset();
g_deferred_destroy_returned.store(true);
});
// Releases both gates before joining, so a failing REQUIRE cannot deadlock the join.
ScopedJoiner join_destroyer{destroyer, allow_fetch, allow_finish};
// Let the worker reserve the in-flight slot and spawn its fetch, then wait until it
// is genuinely parked (no polling).
allow_fetch->set_value();
REQUIRE(running->get_future().wait_for(std::chrono::seconds(5)) == std::future_status::ready);
REQUIRE(g_deferred_fetch_running.load() == 1);
// A correct teardown cannot return while the fetch is parked; give a buggy one time.
for (int i = 0; i < 200 && !g_deferred_destroy_returned.load(); ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if (g_deferred_destroy_returned.load()) {
// Bug: teardown returned with a fetch still running. Don't release allow_finish.
CHECK(g_deferred_fetch_running.load() == 0);
return;
}
// Fixed order: destruction is still blocked on the in-flight fetch.
allow_finish->set_value();
destroyer.join();
CHECK(g_deferred_destroy_returned.load());
CHECK(g_deferred_fetch_running.load() == 0);
}
// =========================================================================== // ===========================================================================
// UNIT - printer-agent registry duplicate handling. // UNIT - printer-agent registry duplicate handling.
// Confirms a duplicate agent id is rejected so a plugin cannot shadow a built-in // Confirms a duplicate agent id is rejected so a plugin cannot shadow a built-in
@@ -1,134 +0,0 @@
#include "catch2/catch_test_macros.hpp"
#include "catch2/matchers/catch_matchers.hpp"
#include "catch2/matchers/catch_matchers_string.hpp"
#include <catch2/catch_all.hpp>
#include <nlohmann/json.hpp>
#include <slic3r/Utils/QidiPrinterAgent.hpp>
#include <string>
using namespace Slic3r;
TEST_CASE("Qidi slot response rejects null variables without throwing", "[QidiPrinterAgent]")
{
const std::string response = R"({
"result": {
"status": {
"save_variables": {
"variables": null
}
}
}
})";
nlohmann::json status;
nlohmann::json variables;
std::string error;
bool parsed = true;
REQUIRE_NOTHROW(parsed = QidiPrinterAgent::parse_slot_response(response, status, variables, error));
CHECK_FALSE(parsed);
CHECK_THAT(error, Catch::Matchers::ContainsSubstring("variables"));
CHECK_THAT(error, Catch::Matchers::ContainsSubstring("object"));
}
TEST_CASE("Qidi slot response rejects missing and non-object fields without throwing", "[QidiPrinterAgent]")
{
std::string response;
SECTION("missing result")
{
response = R"({})";
}
SECTION("non-object result")
{
response = R"({"result":null})";
}
SECTION("missing status")
{
response = R"({"result":{}})";
}
SECTION("non-object status")
{
response = R"({"result":{"status":null}})";
}
SECTION("missing save_variables")
{
response = R"({"result":{"status":{}}})";
}
SECTION("non-object save_variables")
{
response = R"({"result":{"status":{"save_variables":null}}})";
}
SECTION("missing variables")
{
response = R"({"result":{"status":{"save_variables":{}}}})";
}
SECTION("scalar")
{
response = R"({"result":{"status":{"save_variables":{"variables":42}}}})";
}
SECTION("array")
{
response = R"({"result":{"status":{"save_variables":{"variables":[]}}}})";
}
nlohmann::json status;
nlohmann::json variables;
std::string error;
bool parsed = true;
REQUIRE_NOTHROW(parsed = QidiPrinterAgent::parse_slot_response(response, status, variables, error));
CHECK_FALSE(parsed);
}
TEST_CASE("Qidi slot response exposes valid status and variables", "[QidiPrinterAgent]")
{
const std::string response = R"({
"result": {
"status": {
"save_variables": {
"variables": {
"box_count": 2,
"color_slot0": 3
}
},
"box_stepper slot0": {
"runout_button": 0
}
}
}
})";
nlohmann::json status;
nlohmann::json variables;
std::string error;
bool parsed = false;
REQUIRE_NOTHROW(parsed = QidiPrinterAgent::parse_slot_response(response, status, variables, error));
REQUIRE(parsed);
CHECK(status.is_object());
CHECK(variables.is_object());
CHECK(variables.at("box_count") == 2);
CHECK(status.contains("box_stepper slot0"));
}
TEST_CASE("Qidi slot response rejects invalid JSON", "[QidiPrinterAgent]")
{
nlohmann::json status;
nlohmann::json variables;
std::string error;
bool parsed = true;
REQUIRE_NOTHROW(parsed = QidiPrinterAgent::parse_slot_response("{not json", status, variables, error));
CHECK_FALSE(parsed);
CHECK(error == "Invalid JSON response");
}