mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-10-06 15:21:09 +00:00
Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
17b0eda7f8 | ||
|
|
ec22321a4b | ||
|
|
5e861b31f9 | ||
|
|
334ba8f84d | ||
|
|
418623e2c5 | ||
|
|
cf476637d4 | ||
|
|
ceadec4e2d | ||
|
|
92b3068cf6 | ||
|
|
e45f5846b2 | ||
|
|
f0be15df9e | ||
|
|
0ddb86bec7 | ||
|
|
fe30bfe7c7 | ||
|
|
44675778e2 | ||
|
|
b870835b01 | ||
|
|
ea464401be | ||
|
|
4540a98c58 | ||
|
|
76cf64d6c9 | ||
|
|
8d7df2684d | ||
|
|
62bd8c3743 | ||
|
|
936daee0e6 | ||
|
|
9a161692b5 | ||
|
|
eb071f30f8 | ||
|
|
931b07364a | ||
|
|
34c2c926d1 | ||
|
|
fc56ad002a | ||
|
|
7b75fe02c8 | ||
|
|
2f6de2ed86 | ||
|
|
172f492b74 | ||
|
|
b74fac92a5 | ||
|
|
e098c933f0 | ||
|
|
d1afb1fed6 |
+45
-14
@@ -8,6 +8,9 @@ include) fails wherever the error is. Headers are compiled on their own, and
|
|||||||
fail only on errors in their changed lines. Deleting an #include also fails
|
fail only on errors in their changed lines. Deleting an #include also fails
|
||||||
on every use, changed or not, that now lacks the header it provided.
|
on every use, changed or not, that now lacks the header it provided.
|
||||||
|
|
||||||
|
With -- --fix, clang-tidy adds the missing includes, on those lines only, and
|
||||||
|
each file it changed is checked again so that only what remains is reported.
|
||||||
|
|
||||||
The checks come from .clang-tidy at the repository root. The compile database
|
The checks come from .clang-tidy at the repository root. The compile database
|
||||||
must come from a configure with SLIC3R_PCH=OFF, or the precompiled header hides
|
must come from a configure with SLIC3R_PCH=OFF, or the precompiled header hides
|
||||||
missing includes.
|
missing includes.
|
||||||
@@ -102,9 +105,10 @@ def is_checked(path):
|
|||||||
|
|
||||||
def changed_files(merge_base):
|
def changed_files(merge_base):
|
||||||
# Against the working tree, so a local run covers uncommitted edits too.
|
# Against the working tree, so a local run covers uncommitted edits too.
|
||||||
# core.quotePath=false keeps a non-ASCII path unquoted, so parse_diff sees its b/ prefix.
|
# core.quotePath=false keeps a non-ASCII path unquoted, and the explicit prefixes
|
||||||
|
# override diff.noprefix and diff.mnemonicPrefix, so parse_diff sees its b/ prefix.
|
||||||
diff = subprocess.run(["git", "-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff",
|
diff = subprocess.run(["git", "-c", "core.quotePath=false", "diff", "-U0", "--no-color", "--no-ext-diff",
|
||||||
"--diff-filter=AMR", merge_base],
|
"--src-prefix=a/", "--dst-prefix=b/", "--diff-filter=AMR", merge_base],
|
||||||
check=True, capture_output=True, **UTF8).stdout
|
check=True, capture_output=True, **UTF8).stdout
|
||||||
return {path: change for path, change in parse_diff(diff).items() if is_checked(path)}
|
return {path: change for path, change in parse_diff(diff).items() if is_checked(path)}
|
||||||
|
|
||||||
@@ -201,13 +205,19 @@ def errors_alone_at(revision, clang_tidy, build_dir, path):
|
|||||||
|
|
||||||
|
|
||||||
def check_file(clang_tidy, build_dir, merge_base, path, change, extra_args):
|
def check_file(clang_tidy, build_dir, merge_base, path, change, extra_args):
|
||||||
"""Run clang-tidy on one file and return (failed, output, failing diagnostics)."""
|
"""Run clang-tidy on one file and return (failed, output, failing diagnostics, fixed)."""
|
||||||
|
fixing = any(arg.startswith("--fix") for arg in extra_args)
|
||||||
|
if fixing:
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
before = f.read()
|
||||||
# A deleted include can orphan uses on unchanged lines, so such a file is
|
# A deleted include can orphan uses on unchanged lines, so such a file is
|
||||||
# checked whole and the findings narrowed here. --fix keeps the line filter
|
# checked whole and the findings narrowed here. --fix keeps a line filter so
|
||||||
# so it never rewrites unrelated code.
|
# it never rewrites unrelated code, which for such a file means a second,
|
||||||
whole = bool(change.removed_includes) and not extra_args
|
# fixing run limited to the lines the first one found wanting.
|
||||||
|
whole = bool(change.removed_includes)
|
||||||
returncode, output, diagnostics = run_clang_tidy(clang_tidy, build_dir, path,
|
returncode, output, diagnostics = run_clang_tidy(clang_tidy, build_dir, path,
|
||||||
None if whole else change.lines, extra_args)
|
None if whole else change.lines,
|
||||||
|
[] if whole else extra_args)
|
||||||
real = os.path.realpath(path)
|
real = os.path.realpath(path)
|
||||||
|
|
||||||
def introduced(d):
|
def introduced(d):
|
||||||
@@ -223,14 +233,25 @@ def check_file(clang_tidy, build_dir, merge_base, path, change, extra_args):
|
|||||||
if errors and change.removed_includes:
|
if errors and change.removed_includes:
|
||||||
with open(path, encoding="utf-8") as f:
|
with open(path, encoding="utf-8") as f:
|
||||||
text = f.read()
|
text = f.read()
|
||||||
before = errors_alone_at(merge_base, clang_tidy, build_dir, path)
|
before_sites = errors_alone_at(merge_base, clang_tidy, build_dir, path)
|
||||||
failing += [d for d in errors if d not in failing
|
failing += [d for d in errors if d not in failing
|
||||||
and (error_sites([d], text) - before)]
|
and (error_sites([d], text) - before_sites)]
|
||||||
return bool(failing), output, failing
|
failed = bool(failing)
|
||||||
if whole:
|
elif whole:
|
||||||
failing = [d for d in diagnostics if d.is_compile_error or introduced(d)]
|
failing = [d for d in diagnostics if d.is_compile_error or introduced(d)]
|
||||||
return bool(failing), output, failing
|
failed = bool(failing)
|
||||||
return returncode != 0, output, diagnostics
|
else:
|
||||||
|
failing, failed = diagnostics, returncode != 0
|
||||||
|
if not fixing:
|
||||||
|
return failed, output, failing, False
|
||||||
|
if whole and failing:
|
||||||
|
lines = change.lines + [[d.line, d.line] for d in failing if os.path.realpath(d.file) == real]
|
||||||
|
run_clang_tidy(clang_tidy, build_dir, path, lines, extra_args)
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
if f.read() == before:
|
||||||
|
return failed, output, failing, False
|
||||||
|
# Checked again, so what is reported is what the fixes left.
|
||||||
|
return check_file(clang_tidy, build_dir, merge_base, path, change, [])[:3] + (True,)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
@@ -263,11 +284,14 @@ def main():
|
|||||||
annotate = os.environ.get("GITHUB_ACTIONS") == "true"
|
annotate = os.environ.get("GITHUB_ACTIONS") == "true"
|
||||||
root = os.getcwd() + os.sep
|
root = os.getcwd() + os.sep
|
||||||
failed = []
|
failed = []
|
||||||
|
fixed = []
|
||||||
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
with ThreadPoolExecutor(max_workers=args.jobs) as pool:
|
||||||
jobs = {path: pool.submit(check_file, args.clang_tidy, args.build_dir, merge_base, path, change, args.extra_args)
|
jobs = {path: pool.submit(check_file, args.clang_tidy, args.build_dir, merge_base, path, change, args.extra_args)
|
||||||
for path, change in todo}
|
for path, change in todo}
|
||||||
for path, job in jobs.items():
|
for path, job in jobs.items():
|
||||||
file_failed, output, diagnostics = job.result()
|
file_failed, output, diagnostics, file_fixed = job.result()
|
||||||
|
if file_fixed:
|
||||||
|
fixed.append(path)
|
||||||
if not file_failed:
|
if not file_failed:
|
||||||
continue
|
continue
|
||||||
failed.append(path)
|
failed.append(path)
|
||||||
@@ -282,6 +306,13 @@ def main():
|
|||||||
if len(diagnostics) > MAX_REPORTED:
|
if len(diagnostics) > MAX_REPORTED:
|
||||||
print(f"... and {len(diagnostics) - MAX_REPORTED} more")
|
print(f"... and {len(diagnostics) - MAX_REPORTED} more")
|
||||||
|
|
||||||
|
if fixed:
|
||||||
|
print(f"\nAdded includes to {len(fixed)} file(s):")
|
||||||
|
for path in fixed:
|
||||||
|
print(f" {path}")
|
||||||
|
if failed and fixed:
|
||||||
|
print(f"\nclang-tidy still fails on {len(failed)} file(s); the findings above are what --fix could not add.")
|
||||||
|
return 1
|
||||||
if failed:
|
if failed:
|
||||||
print(f"\nclang-tidy failed on {len(failed)} file(s). Add the includes it names, or apply its "
|
print(f"\nclang-tidy failed on {len(failed)} file(s). Add the includes it names, or apply its "
|
||||||
"suggestions locally with scripts/run_clang_tidy.sh --fix (scripts\\run_clang_tidy.ps1 -Fix on Windows).")
|
"suggestions locally with scripts/run_clang_tidy.sh --fix (scripts\\run_clang_tidy.ps1 -Fix on Windows).")
|
||||||
|
|||||||
+40
-10
@@ -6,8 +6,9 @@
|
|||||||
# scripts/run_clang_tidy.sh --fix also add the missing includes it names
|
# scripts/run_clang_tidy.sh --fix also add the missing includes it names
|
||||||
#
|
#
|
||||||
# It configures a separate build directory (build-tidy) without the precompiled
|
# It configures a separate build directory (build-tidy) without the precompiled
|
||||||
# header, installs the pinned clang-tidy into a virtual environment inside it, and
|
# header, uses the clang-tidy on your system or installs the pinned one into a
|
||||||
# runs scripts/clang_tidy_diff.py the way CI does. Uncommitted changes are checked too.
|
# virtual environment inside it, and runs scripts/clang_tidy_diff.py the way CI
|
||||||
|
# does. Uncommitted changes are checked too.
|
||||||
|
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
@@ -23,7 +24,8 @@ Usage: scripts/run_clang_tidy.sh [options]
|
|||||||
deps/build/<arch> on macOS)
|
deps/build/<arch> on macOS)
|
||||||
-j, --jobs N parallel clang-tidy runs (default: all cores)
|
-j, --jobs N parallel clang-tidy runs (default: all cores)
|
||||||
--fix apply clang-tidy's fixes (adds the missing includes)
|
--fix apply clang-tidy's fixes (adds the missing includes)
|
||||||
-y, --yes install missing tools without asking
|
-y, --yes install missing tools without asking; another clang-tidy
|
||||||
|
version found on the system is then not offered
|
||||||
-h, --help show this help
|
-h, --help show this help
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
@@ -136,12 +138,38 @@ REQUIREMENTS="$ROOT/scripts/clang_tidy_requirements.txt"
|
|||||||
PINNED=$(sed -n 's/^clang-tidy==//p' "$REQUIREMENTS")
|
PINNED=$(sed -n 's/^clang-tidy==//p' "$REQUIREMENTS")
|
||||||
VENV="$BUILD_DIR/clang-tidy-venv"
|
VENV="$BUILD_DIR/clang-tidy-venv"
|
||||||
|
|
||||||
if [ -n "${CLANG_TIDY:-}" ]; then
|
is_pinned() {
|
||||||
|
[ -x "$1" ] && "$1" --version 2>/dev/null | grep -q "version $PINNED"
|
||||||
|
}
|
||||||
|
|
||||||
|
CLANG_TIDY="${CLANG_TIDY:-}"
|
||||||
|
if [ -n "$CLANG_TIDY" ]; then
|
||||||
# Set by the caller: use it as is.
|
# Set by the caller: use it as is.
|
||||||
:
|
is_pinned "$CLANG_TIDY" || echo "Warning: $CLANG_TIDY is not clang-tidy $PINNED, so results may differ from CI." >&2
|
||||||
else
|
else
|
||||||
|
# One already on the system comes first: the pinned version outright, another
|
||||||
|
# version if the user accepts the difference. The pinned version is installed
|
||||||
|
# into a virtual environment otherwise.
|
||||||
|
INSTALLED=""
|
||||||
|
for candidate in $(command -v clang-tidy "clang-tidy-${PINNED%%.*}" || true) \
|
||||||
|
"/usr/lib/llvm-${PINNED%%.*}/bin/clang-tidy" \
|
||||||
|
"$(brew --prefix llvm 2>/dev/null || true)/bin/clang-tidy"; do
|
||||||
|
if is_pinned "$candidate"; then
|
||||||
|
CLANG_TIDY="$candidate"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
[ -z "$INSTALLED" ] && [ -x "$candidate" ] && INSTALLED="$candidate"
|
||||||
|
done
|
||||||
|
if [ -z "$CLANG_TIDY" ] && [ -n "$INSTALLED" ] && [ "$YES" = 0 ] && ! is_pinned "$VENV/bin/clang-tidy"; then
|
||||||
|
echo "Found $INSTALLED, which is $("$INSTALLED" --version | sed -n 's/.*version \([0-9.]*\).*/\1/p' | head -n 1), not the $PINNED CI uses, so results may differ slightly."
|
||||||
|
if ask "Use it anyway?"; then
|
||||||
|
CLANG_TIDY="$INSTALLED"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ -z "$CLANG_TIDY" ]; then
|
||||||
CLANG_TIDY="$VENV/bin/clang-tidy"
|
CLANG_TIDY="$VENV/bin/clang-tidy"
|
||||||
if [ ! -x "$CLANG_TIDY" ] || ! "$CLANG_TIDY" --version | grep -q "version $PINNED"; then
|
if ! is_pinned "$CLANG_TIDY"; then
|
||||||
if ask "clang-tidy $PINNED (the version CI uses) is not installed. Install it into $VENV?"; then
|
if ask "clang-tidy $PINNED (the version CI uses) is not installed. Install it into $VENV?"; then
|
||||||
mkdir -p "$BUILD_DIR"
|
mkdir -p "$BUILD_DIR"
|
||||||
if ! python3 -m venv "$VENV"; then
|
if ! python3 -m venv "$VENV"; then
|
||||||
@@ -158,9 +186,6 @@ else
|
|||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if ! "$CLANG_TIDY" --version | grep -q "version $PINNED"; then
|
|
||||||
echo "Warning: $CLANG_TIDY is not clang-tidy $PINNED, so results may differ from CI." >&2
|
|
||||||
fi
|
|
||||||
|
|
||||||
# --- Dependencies -------------------------------------------------------------
|
# --- Dependencies -------------------------------------------------------------
|
||||||
|
|
||||||
@@ -217,7 +242,12 @@ cmake --build "$BUILD_DIR" --target git_commit_hash_header >/dev/null
|
|||||||
|
|
||||||
if [ -z "$BASE" ]; then
|
if [ -z "$BASE" ]; then
|
||||||
REMOTE=$(git remote -v | awk '/github\.com[:\/]OrcaSlicer\/OrcaSlicer(\.git)? \(fetch\)/ { print $1; exit }')
|
REMOTE=$(git remote -v | awk '/github\.com[:\/]OrcaSlicer\/OrcaSlicer(\.git)? \(fetch\)/ { print $1; exit }')
|
||||||
REMOTE="${REMOTE:-origin}"
|
if [ -z "$REMOTE" ]; then
|
||||||
|
# Against a fork's main that already has the commits, nothing is checked.
|
||||||
|
echo "Warning: no remote points at github.com/OrcaSlicer/OrcaSlicer, so this compares against origin/main." >&2
|
||||||
|
echo "If origin is your fork, add the upstream remote (git remote add upstream https://github.com/OrcaSlicer/OrcaSlicer.git) or pass --base." >&2
|
||||||
|
REMOTE=origin
|
||||||
|
fi
|
||||||
if [ "$FETCH" = 1 ]; then
|
if [ "$FETCH" = 1 ]; then
|
||||||
git fetch --quiet "$REMOTE" main
|
git fetch --quiet "$REMOTE" main
|
||||||
fi
|
fi
|
||||||
|
|||||||
@@ -155,6 +155,8 @@ class TestSubprocessCalls(unittest.TestCase):
|
|||||||
diff = "+++ b/src/libslic3r/Über.cpp\n@@ -1,0 +2 @@\n+// 打印\n"
|
diff = "+++ b/src/libslic3r/Über.cpp\n@@ -1,0 +2 @@\n+// 打印\n"
|
||||||
files, call, _ = self.run_patched(clang_tidy_diff.changed_files, "base", stdout=diff)
|
files, call, _ = self.run_patched(clang_tidy_diff.changed_files, "base", stdout=diff)
|
||||||
self.assertIn("core.quotePath=false", call.args[0])
|
self.assertIn("core.quotePath=false", call.args[0])
|
||||||
|
# Whatever diff.noprefix or diff.mnemonicPrefix a user has set.
|
||||||
|
self.assertIn("--dst-prefix=b/", call.args[0])
|
||||||
self.assertEqual(call.kwargs["encoding"], "utf-8")
|
self.assertEqual(call.kwargs["encoding"], "utf-8")
|
||||||
self.assertEqual(files["src/libslic3r/Über.cpp"].lines, [[2, 2]])
|
self.assertEqual(files["src/libslic3r/Über.cpp"].lines, [[2, 2]])
|
||||||
|
|
||||||
@@ -167,5 +169,60 @@ class TestSubprocessCalls(unittest.TestCase):
|
|||||||
self.assertEqual(call.kwargs["encoding"], "utf-8")
|
self.assertEqual(call.kwargs["encoding"], "utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
class TestCheckFileFix(unittest.TestCase):
|
||||||
|
"""check_file with -- --fix: what clang-tidy is run on, and what is reported afterwards."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.dir = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.dir.cleanup)
|
||||||
|
self.path = os.path.join(self.dir.name, "Color.cpp")
|
||||||
|
with open(self.path, "w") as f:
|
||||||
|
f.write("int x;\n")
|
||||||
|
|
||||||
|
def finding(self, line, include=""):
|
||||||
|
return clang_tidy_diff.Diagnostic(self.path, line, 1, "error",
|
||||||
|
'no header providing "x" is directly included [misc-include-cleaner]', include)
|
||||||
|
|
||||||
|
def check(self, change, results, fix_writes=None):
|
||||||
|
"""Run check_file with run_clang_tidy answering from `results` in turn; the --fix run
|
||||||
|
rewrites the file with `fix_writes` when given. Returns (result, calls)."""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def run(clang_tidy, build_dir, path, lines, extra_args):
|
||||||
|
calls.append((lines, extra_args))
|
||||||
|
if "--fix" in extra_args and fix_writes is not None:
|
||||||
|
with open(path, "w") as f:
|
||||||
|
f.write(fix_writes)
|
||||||
|
return results[len(calls) - 1]
|
||||||
|
|
||||||
|
with mock.patch.object(clang_tidy_diff, "run_clang_tidy", side_effect=run):
|
||||||
|
result = clang_tidy_diff.check_file("clang-tidy", "build", "base", self.path, change, ["--fix"])
|
||||||
|
return result, calls
|
||||||
|
|
||||||
|
def test_a_deleted_include_is_fixed_on_the_lines_it_orphaned_only(self):
|
||||||
|
change = clang_tidy_diff.FileChange(lines=[[4, 4]], removed_includes={"libslic3r/Point.hpp"})
|
||||||
|
orphaned = self.finding(50, "<libslic3r/Point.hpp>")
|
||||||
|
unrelated = self.finding(60, "<vector>")
|
||||||
|
(failed, _, failing, fixed), calls = self.check(
|
||||||
|
change, [(1, "", [orphaned, unrelated]), (1, "", [orphaned]), (0, "", [])], fix_writes="#include <libslic3r/Point.hpp>\n")
|
||||||
|
self.assertEqual(calls, [(None, []), ([[4, 4], [50, 50]], ["--fix"]), (None, [])])
|
||||||
|
self.assertEqual((failed, failing, fixed), (False, [], True))
|
||||||
|
|
||||||
|
def test_a_file_the_fix_did_not_change_keeps_its_findings(self):
|
||||||
|
change = clang_tidy_diff.FileChange(lines=[[4, 4]])
|
||||||
|
error = clang_tidy_diff.Diagnostic(self.path, 4, 1, "error", "unknown type name 'Foo' [clang-diagnostic-error]")
|
||||||
|
(failed, _, failing, fixed), calls = self.check(change, [(1, "", [error])])
|
||||||
|
self.assertEqual(calls, [([[4, 4]], ["--fix"])])
|
||||||
|
self.assertEqual((failed, failing, fixed), (True, [error], False))
|
||||||
|
|
||||||
|
def test_a_changed_file_is_checked_again_and_reports_what_is_left(self):
|
||||||
|
change = clang_tidy_diff.FileChange(lines=[[4, 4]])
|
||||||
|
error = clang_tidy_diff.Diagnostic(self.path, 4, 1, "error", "unknown type name 'Foo' [clang-diagnostic-error]")
|
||||||
|
(failed, _, failing, fixed), calls = self.check(
|
||||||
|
change, [(1, "", [self.finding(4, "<vector>"), error]), (1, "", [error])], fix_writes="#include <vector>\n")
|
||||||
|
self.assertEqual(calls, [([[4, 4]], ["--fix"]), ([[4, 4]], [])])
|
||||||
|
self.assertEqual((failed, failing, fixed), (True, [error], True))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -751,6 +751,50 @@ template<typename T>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// Writes G-code to a file in blocks and records in lines_ends the file offset after every '\n'
|
||||||
|
class GCodeFileWriter
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
GCodeFileWriter(FilePtr& out, const std::string& out_path, std::vector<size_t>& lines_ends, const char* error_message)
|
||||||
|
: m_out(out), m_out_path(out_path), m_lines_ends(lines_ends), m_error_message(error_message)
|
||||||
|
{}
|
||||||
|
~GCodeFileWriter() { assert(m_buffer.empty() || std::uncaught_exceptions() > 0); }
|
||||||
|
|
||||||
|
void append(std::string_view text)
|
||||||
|
{
|
||||||
|
const size_t text_pos = m_file_pos + m_buffer.size();
|
||||||
|
for (size_t i = text.find('\n'); i != std::string_view::npos; i = text.find('\n', i + 1))
|
||||||
|
m_lines_ends.emplace_back(text_pos + i + 1);
|
||||||
|
m_buffer += text;
|
||||||
|
if (m_buffer.size() >= GCodeProcessor::Output_Block_Size)
|
||||||
|
flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
void flush()
|
||||||
|
{
|
||||||
|
if (m_buffer.empty())
|
||||||
|
return;
|
||||||
|
fwrite(m_buffer.data(), 1, m_buffer.size(), m_out.f);
|
||||||
|
if (ferror(m_out.f)) {
|
||||||
|
m_out.close();
|
||||||
|
boost::nowide::remove(m_out_path.c_str());
|
||||||
|
throw Slic3r::RuntimeError(m_error_message);
|
||||||
|
}
|
||||||
|
m_file_pos += m_buffer.size();
|
||||||
|
m_buffer.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
FilePtr& m_out;
|
||||||
|
const std::string& m_out_path;
|
||||||
|
std::vector<size_t>& m_lines_ends;
|
||||||
|
const char* m_error_message;
|
||||||
|
std::string m_buffer;
|
||||||
|
size_t m_file_pos{0};
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
// Helper class to modify and export gcode to file
|
// Helper class to modify and export gcode to file
|
||||||
class ExportLines
|
class ExportLines
|
||||||
{
|
{
|
||||||
@@ -765,16 +809,6 @@ public:
|
|||||||
enum class EWriteType { BySize, ByTime };
|
enum class EWriteType { BySize, ByTime };
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static void update_lines_ends_and_out_file_pos(const std::string& out_string, std::vector<size_t>& lines_ends, size_t* out_file_pos)
|
|
||||||
{
|
|
||||||
for (size_t i = 0; i < out_string.size(); ++i) {
|
|
||||||
if (out_string[i] == '\n')
|
|
||||||
lines_ends.emplace_back((out_file_pos != nullptr) ? *out_file_pos + i + 1 : i + 1);
|
|
||||||
}
|
|
||||||
if (out_file_pos != nullptr)
|
|
||||||
*out_file_pos += out_string.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
struct LineData
|
struct LineData
|
||||||
{
|
{
|
||||||
std::string line;
|
std::string line;
|
||||||
@@ -814,12 +848,14 @@ private:
|
|||||||
EWriteType m_write_type{EWriteType::BySize};
|
EWriteType m_write_type{EWriteType::BySize};
|
||||||
// Time machines containing g1 times cache
|
// Time machines containing g1 times cache
|
||||||
const std::array<GCodeProcessor::TimeMachine, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)>& m_machines;
|
const std::array<GCodeProcessor::TimeMachine, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)>& m_machines;
|
||||||
|
// Output file writer
|
||||||
|
GCodeFileWriter& m_writer;
|
||||||
// Current time
|
// Current time
|
||||||
std::array<float, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)> m_times{0.0f, 0.0f};
|
std::array<float, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)> m_times{0.0f, 0.0f};
|
||||||
// Current size in bytes
|
// Current size of the cache in bytes
|
||||||
size_t m_size{0};
|
size_t m_size{0};
|
||||||
|
|
||||||
// gcode lines cache
|
// gcode lines cache, used only when writing by time
|
||||||
std::deque<LineData> m_lines;
|
std::deque<LineData> m_lines;
|
||||||
size_t m_added_lines_counter{0};
|
size_t m_added_lines_counter{0};
|
||||||
// map of gcode line ids from original to final
|
// map of gcode line ids from original to final
|
||||||
@@ -827,16 +863,16 @@ private:
|
|||||||
std::vector<std::pair<size_t, size_t>> m_gcode_lines_map;
|
std::vector<std::pair<size_t, size_t>> m_gcode_lines_map;
|
||||||
|
|
||||||
size_t m_times_cache_id{0};
|
size_t m_times_cache_id{0};
|
||||||
size_t m_out_file_pos{0};
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
ExportLines(EWriteType type, const std::array<GCodeProcessor::TimeMachine, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)>& machines)
|
ExportLines(EWriteType type, const std::array<GCodeProcessor::TimeMachine, static_cast<size_t>(PrintEstimatedStatistics::ETimeMode::Count)>& machines, GCodeFileWriter& writer)
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
: m_statistics(*this)
|
: m_statistics(*this)
|
||||||
, m_write_type(type)
|
, m_write_type(type)
|
||||||
, m_machines(machines){}
|
, m_machines(machines)
|
||||||
|
, m_writer(writer){}
|
||||||
#else
|
#else
|
||||||
: m_write_type(type), m_machines(machines)
|
: m_write_type(type), m_machines(machines), m_writer(writer)
|
||||||
{}
|
{}
|
||||||
#endif // NDEBUG
|
#endif // NDEBUG
|
||||||
|
|
||||||
@@ -890,11 +926,14 @@ public:
|
|||||||
if (line.empty())
|
if (line.empty())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
m_lines.push_back({line, m_times});
|
if (m_write_type == EWriteType::ByTime) {
|
||||||
|
m_lines.push_back({line, m_times});
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
m_statistics.add_line(line.length());
|
m_statistics.add_line(line.length());
|
||||||
#endif // NDEBUG
|
#endif // NDEBUG
|
||||||
m_size += line.length();
|
m_size += line.length();
|
||||||
|
} else
|
||||||
|
m_writer.append(line);
|
||||||
++m_added_lines_counter;
|
++m_added_lines_counter;
|
||||||
if (!ignore_from_move) {
|
if (!ignore_from_move) {
|
||||||
assert(!m_gcode_lines_map.empty());
|
assert(!m_gcode_lines_map.empty());
|
||||||
@@ -960,65 +999,35 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// write to file:
|
// when writing by time, pass the cached lines older than m_times[Normal] - backtrace_time to the writer
|
||||||
// m_write_type == EWriteType::ByTime - all lines older than m_time - backtrace_time
|
void write(float backtrace_time)
|
||||||
// m_write_type == EWriteType::BySize - all lines if current size is greater than 65535 bytes
|
|
||||||
void write(FilePtr& out, float backtrace_time, GCodeProcessorResult& result, const std::string& out_path)
|
|
||||||
{
|
{
|
||||||
if (m_lines.empty())
|
if (m_write_type != EWriteType::ByTime)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
// collect lines to write into a single string
|
while (!m_lines.empty() && m_lines.front().times[Normal] < m_times[Normal] - backtrace_time) {
|
||||||
std::string out_string;
|
const LineData& data = m_lines.front();
|
||||||
if (!m_lines.empty()) {
|
m_writer.append(data.line);
|
||||||
if (m_write_type == EWriteType::ByTime) {
|
m_size -= data.line.length();
|
||||||
while (m_lines.front().times[Normal] < m_times[Normal] - backtrace_time) {
|
m_lines.pop_front();
|
||||||
const LineData& data = m_lines.front();
|
|
||||||
out_string += data.line;
|
|
||||||
m_size -= data.line.length();
|
|
||||||
m_lines.pop_front();
|
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
m_statistics.remove_line();
|
m_statistics.remove_line();
|
||||||
#endif // NDEBUG
|
#endif // NDEBUG
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (m_size > 65535) {
|
|
||||||
while (!m_lines.empty()) {
|
|
||||||
out_string += m_lines.front().line;
|
|
||||||
m_lines.pop_front();
|
|
||||||
}
|
|
||||||
m_size = 0;
|
|
||||||
#ifndef NDEBUG
|
|
||||||
m_statistics.remove_all_lines();
|
|
||||||
#endif // NDEBUG
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
{
|
|
||||||
write_to_file(out, out_string, result, out_path);
|
|
||||||
update_lines_ends_and_out_file_pos(out_string, result.lines_ends, &m_out_file_pos);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// flush the current content of the cache to file
|
// flush the current content of the cache and the writer to file
|
||||||
void flush(FilePtr& out, GCodeProcessorResult& result, const std::string& out_path)
|
void flush()
|
||||||
{
|
{
|
||||||
// collect lines to flush into a single string
|
|
||||||
std::string out_string;
|
|
||||||
while (!m_lines.empty()) {
|
while (!m_lines.empty()) {
|
||||||
out_string += m_lines.front().line;
|
m_writer.append(m_lines.front().line);
|
||||||
m_lines.pop_front();
|
m_lines.pop_front();
|
||||||
}
|
}
|
||||||
m_size = 0;
|
m_size = 0;
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
m_statistics.remove_all_lines();
|
m_statistics.remove_all_lines();
|
||||||
#endif // NDEBUG
|
#endif // NDEBUG
|
||||||
|
m_writer.flush();
|
||||||
{
|
|
||||||
write_to_file(out, out_string, result, out_path);
|
|
||||||
update_lines_ends_and_out_file_pos(out_string, result.lines_ends, &m_out_file_pos);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void synchronize_moves(GCodeProcessorResult& result) const
|
void synchronize_moves(GCodeProcessorResult& result) const
|
||||||
@@ -1051,20 +1060,7 @@ public:
|
|||||||
|
|
||||||
size_t get_size() const { return m_size; }
|
size_t get_size() const { return m_size; }
|
||||||
|
|
||||||
private:
|
void reserve(size_t lines_count) { m_gcode_lines_map.reserve(lines_count); }
|
||||||
void write_to_file(FilePtr& out, const std::string& out_string, GCodeProcessorResult& result, const std::string& out_path)
|
|
||||||
{
|
|
||||||
if (!out_string.empty()) {
|
|
||||||
if (true) {
|
|
||||||
fwrite((const void*) out_string.c_str(), 1, out_string.length(), out.f);
|
|
||||||
if (ferror(out.f)) {
|
|
||||||
out.close();
|
|
||||||
boost::nowide::remove(out_path.c_str());
|
|
||||||
throw Slic3r::RuntimeError("GCode processor post process export failed.\nIs the disk full?");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
void GCodeProcessor::run_post_process()
|
void GCodeProcessor::run_post_process()
|
||||||
@@ -1160,8 +1156,13 @@ void GCodeProcessor::run_post_process()
|
|||||||
last_exported_stop[i] = time_in_minutes(m_time_processor.machines[i].time);
|
last_exported_stop[i] = time_in_minutes(m_time_processor.machines[i].time);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
m_result.lines_ends.clear();
|
||||||
|
// m_result.lines_ends.emplace_back(std::vector<size_t>());
|
||||||
|
GCodeFileWriter writer(out, out_path, m_result.lines_ends, "GCode processor post process export failed.\nIs the disk full?");
|
||||||
ExportLines export_line(m_result.backtrace_enabled ? ExportLines::EWriteType::ByTime : ExportLines::EWriteType::BySize,
|
ExportLines export_line(m_result.backtrace_enabled ? ExportLines::EWriteType::ByTime : ExportLines::EWriteType::BySize,
|
||||||
m_time_processor.machines);
|
m_time_processor.machines, writer);
|
||||||
|
// The line map holds an entry for each line of the file, and the first pass counted them
|
||||||
|
export_line.reserve(m_line_id);
|
||||||
|
|
||||||
// replace placeholder lines with the proper final value
|
// replace placeholder lines with the proper final value
|
||||||
// gcode_line is in/out parameter, to reduce expensive memory allocation
|
// gcode_line is in/out parameter, to reduce expensive memory allocation
|
||||||
@@ -1535,9 +1536,6 @@ void GCodeProcessor::run_post_process()
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
m_result.lines_ends.clear();
|
|
||||||
// m_result.lines_ends.emplace_back(std::vector<size_t>());
|
|
||||||
|
|
||||||
// Orca: freshly collect SKIPPABLE ranges each post-process pass. The ranges are stored on the
|
// Orca: freshly collect SKIPPABLE ranges each post-process pass. The ranges are stored on the
|
||||||
// member (rather than a local) so the injection pass can consume them, hence the clear here to
|
// member (rather than a local) so the injection pass can consume them, hence the clear here to
|
||||||
// avoid stale ranges on re-invocation.
|
// avoid stale ranges on re-invocation.
|
||||||
@@ -1802,7 +1800,7 @@ void GCodeProcessor::run_post_process()
|
|||||||
|
|
||||||
if (!gcode_line.empty())
|
if (!gcode_line.empty())
|
||||||
export_line.append_line(gcode_line);
|
export_line.append_line(gcode_line);
|
||||||
export_line.write(out, 1.1f * max_backtrace_time, m_result, out_path);
|
export_line.write(1.1f * max_backtrace_time);
|
||||||
gcode_line.clear();
|
gcode_line.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1844,7 +1842,7 @@ void GCodeProcessor::run_post_process()
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export_line.flush(out, m_result, out_path);
|
export_line.flush();
|
||||||
|
|
||||||
out.close();
|
out.close();
|
||||||
in.close();
|
in.close();
|
||||||
@@ -1992,31 +1990,13 @@ void GCodeProcessor::run_second_pass_injection()
|
|||||||
// The rewrite may shift byte positions (once the injector inserts lines), so rebuild lines_ends from scratch.
|
// The rewrite may shift byte positions (once the injector inserts lines), so rebuild lines_ends from scratch.
|
||||||
// With an empty map the scanned '\n' offsets reproduce the current lines_ends exactly.
|
// With an empty map the scanned '\n' offsets reproduce the current lines_ends exactly.
|
||||||
m_result.lines_ends.clear();
|
m_result.lines_ends.clear();
|
||||||
size_t out_file_pos = 0;
|
GCodeFileWriter writer(out, out_path, m_result.lines_ends, "GCode processor pre-heat injection pass failed.\nIs the disk full?\n");
|
||||||
|
|
||||||
auto write_out = [&out, &out_path, this, &out_file_pos](std::string& str) {
|
|
||||||
if (str.empty())
|
|
||||||
return;
|
|
||||||
fwrite((const void*) str.c_str(), 1, str.length(), out.f);
|
|
||||||
if (ferror(out.f)) {
|
|
||||||
out.close();
|
|
||||||
boost::nowide::remove(out_path.c_str());
|
|
||||||
throw Slic3r::RuntimeError(std::string("GCode processor pre-heat injection pass failed.\nIs the disk full?\n"));
|
|
||||||
}
|
|
||||||
for (size_t i = 0; i < str.size(); ++i) {
|
|
||||||
if (str[i] == '\n')
|
|
||||||
m_result.lines_ends.emplace_back(out_file_pos + i + 1);
|
|
||||||
}
|
|
||||||
out_file_pos += str.size();
|
|
||||||
str.clear();
|
|
||||||
};
|
|
||||||
|
|
||||||
// Orca: read/split lines with EOL-preserving semantics (keep the original \r and \n bytes, and
|
// Orca: read/split lines with EOL-preserving semantics (keep the original \r and \n bytes, and
|
||||||
// synthesize no trailing newline). This is required for the empty-map identity: normalizing every
|
// synthesize no trailing newline). This is required for the empty-map identity: normalizing every
|
||||||
// line ending to "\n" would not be byte-identical if the finished file used \r\n or lacked a
|
// line ending to "\n" would not be byte-identical if the finished file used \r\n or lacked a
|
||||||
// final newline.
|
// final newline.
|
||||||
std::string gcode_line;
|
std::string gcode_line;
|
||||||
std::string export_buffer;
|
|
||||||
unsigned int line_id = 0;
|
unsigned int line_id = 0;
|
||||||
auto op_it = inserted_operation_lines.begin();
|
auto op_it = inserted_operation_lines.begin();
|
||||||
std::vector<char> buffer(65536 * 10, 0);
|
std::vector<char> buffer(65536 * 10, 0);
|
||||||
@@ -2058,16 +2038,14 @@ void GCodeProcessor::run_second_pass_injection()
|
|||||||
}
|
}
|
||||||
++op_it;
|
++op_it;
|
||||||
}
|
}
|
||||||
export_buffer += gcode_line;
|
writer.append(gcode_line);
|
||||||
gcode_line.clear();
|
gcode_line.clear();
|
||||||
if (export_buffer.length() >= 65536)
|
|
||||||
write_out(export_buffer);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (eof)
|
if (eof)
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
write_out(export_buffer);
|
writer.flush();
|
||||||
|
|
||||||
out.close();
|
out.close();
|
||||||
in.close();
|
in.close();
|
||||||
|
|||||||
@@ -491,6 +491,9 @@ class Print;
|
|||||||
static const std::string VFlush_End_Tag;
|
static const std::string VFlush_End_Tag;
|
||||||
static const std::string External_Purge_Tag;
|
static const std::string External_Purge_Tag;
|
||||||
public:
|
public:
|
||||||
|
// Size of the blocks the post-processing passes write the G-code in
|
||||||
|
static constexpr size_t Output_Block_Size = 65536;
|
||||||
|
|
||||||
// Orca: SKIPPABLE region tags, stored as static strings (the FLUSH idiom above) rather than
|
// Orca: SKIPPABLE region tags, stored as static strings (the FLUSH idiom above) rather than
|
||||||
// a CustomETags/CustomTags array. Public so the emission sites (WipeTower / change_filament
|
// a CustomETags/CustomTags array. Public so the emission sites (WipeTower / change_filament
|
||||||
// path) can reference them single-sourced.
|
// path) can reference them single-sourced.
|
||||||
|
|||||||
@@ -204,8 +204,9 @@ 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;
|
||||||
@@ -215,8 +216,9 @@ 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 = -input_val;
|
value = -1.0 * 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;
|
||||||
@@ -237,10 +239,11 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -586,8 +589,15 @@ 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)
|
||||||
{
|
{
|
||||||
return dispatch_start<func_start_send_gcode_to_sdcard_legacy, func_start_send_gcode_to_sdcard_0203>(
|
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=" << params.try_emmc_print
|
||||||
|
<< ", legacy_mode=" << BBLNetworkPlugin::instance().use_legacy_network()
|
||||||
|
<< ", dev_ip=" << params.dev_ip << ", dev_id=" << params.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)
|
||||||
|
|||||||
@@ -110,6 +110,7 @@ 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);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -289,8 +289,11 @@ 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())
|
||||||
|
return false;
|
||||||
|
|
||||||
if (device_info.dev_ip.empty()) {
|
if (device_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";
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
explicit CrealityPrintAgent(std::string log_dir);
|
explicit CrealityPrintAgent(std::string log_dir);
|
||||||
~CrealityPrintAgent() override = default;
|
~CrealityPrintAgent() override { shutdown(); }
|
||||||
|
|
||||||
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(); }
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -12,6 +12,10 @@
|
|||||||
#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>
|
||||||
@@ -20,6 +24,39 @@ namespace Slic3r { class ICloudServiceAgent; }
|
|||||||
|
|
||||||
namespace Slic3r {
|
namespace Slic3r {
|
||||||
|
|
||||||
|
class Http;
|
||||||
|
|
||||||
|
bool moonraker_is_light_name(const std::string& name);
|
||||||
|
|
||||||
|
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:
|
||||||
@@ -65,12 +102,20 @@ 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;
|
||||||
|
|
||||||
// Pull-mode agent (on-demand filament sync)
|
|
||||||
FilamentSyncMode get_filament_sync_mode() const override { return FilamentSyncMode::pull; }
|
|
||||||
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;
|
||||||
|
CameraStreamMode get_camera_stream_mode() const override;
|
||||||
|
std::string get_camera_url() const 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;
|
||||||
@@ -82,7 +127,9 @@ 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
|
||||||
@@ -100,12 +147,25 @@ 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 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 init_device_info(const PrinterConnectionParams& params);
|
||||||
virtual bool fetch_device_info(const std::string& base_url, const std::string& api_key, MoonrakerDeviceInfo& info, std::string& error) const;
|
virtual bool fetch_device_info(const ConnectionSettings& connection, MoonrakerDeviceInfo& info, std::string& error) const;
|
||||||
|
ConnectionSettings get_connection_settings() 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;
|
||||||
|
|
||||||
// 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);
|
||||||
@@ -118,13 +178,30 @@ 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 std::string& base_url, const std::string& api_key, std::set<std::string>& objects, std::string& error) const;
|
bool fetch_object_list(const ConnectionSettings& connection, std::set<std::string>& objects, 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 query_printer_status(const ConnectionSettings& connection, 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;
|
||||||
@@ -133,10 +210,11 @@ private:
|
|||||||
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);
|
||||||
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, const std::string& base_url, const std::string& api_key);
|
void start_status_stream(const std::string& dev_id, ConnectionSettings connection);
|
||||||
void stop_status_stream();
|
void stop_status_stream();
|
||||||
void run_status_stream(std::string dev_id, std::string base_url, std::string api_key);
|
void run_status_stream(std::string dev_id, ConnectionSettings connection);
|
||||||
void handle_ws_message(const std::string& dev_id, const std::string& payload);
|
void handle_ws_message(std::string dev_id, std::string payload, ConnectionSettings connection);
|
||||||
|
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;
|
||||||
|
|
||||||
@@ -147,22 +225,28 @@ private:
|
|||||||
|
|
||||||
// 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 std::string& base_url, const std::string& api_key,
|
const ConnectionSettings& connection,
|
||||||
OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn);
|
OnUpdateStatusFn update_fn, WasCancelledFn cancel_fn);
|
||||||
|
|
||||||
// JSON-RPC helper
|
// Start a print of a previously uploaded G-code file (path relative to the
|
||||||
bool send_jsonrpc_command(const std::string& base_url, const std::string& api_key,
|
// Moonraker gcodes root).
|
||||||
const nlohmann::json& request, std::string& response) const;
|
bool start_print_file(const ConnectionSettings& connection,
|
||||||
|
const std::string& filename, std::string& error_msg) 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,
|
||||||
const std::string& base_url,
|
ConnectionSettings connection,
|
||||||
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(std::vector<AmsTrayData>& trays, int& max_lane_index);
|
bool fetch_hh_filament_info(const ConnectionSettings& connection, std::vector<AmsTrayData>& trays, int& max_lane_index);
|
||||||
bool fetch_moonraker_filament_data(std::vector<AmsTrayData>& trays, int& max_lane_index);
|
bool fetch_moonraker_filament_data(const ConnectionSettings& connection, 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);
|
||||||
@@ -188,15 +272,38 @@ 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;
|
||||||
|
mutable uint64_t webcam_info_last_lookup_ms = 0;
|
||||||
|
mutable uint64_t webcam_info_generation = 0;
|
||||||
|
unsigned thumbnail_lookup_attempts = 0;
|
||||||
|
|
||||||
|
static constexpr uint64_t WEBCAM_INFO_REFRESH_INTERVAL_MS = 1000;
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
|
// 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
|
||||||
@@ -206,7 +313,13 @@ 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
|
||||||
|
|||||||
@@ -2,18 +2,23 @@
|
|||||||
#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 <map>
|
#include <map>
|
||||||
|
#include <mutex>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
|
#include <thread>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -36,6 +41,18 @@ bool has_visible_base_preset(const PresetCollection& filaments, const std::strin
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RAII decrement for the in-flight fetch count; movable so a failed thread start still releases it.
|
||||||
|
struct InFlightGuard
|
||||||
|
{
|
||||||
|
std::atomic<int>* counter;
|
||||||
|
explicit InFlightGuard(std::atomic<int>& c) noexcept : counter(&c) {}
|
||||||
|
InFlightGuard(InFlightGuard&& other) noexcept : counter(other.counter) { other.counter = nullptr; }
|
||||||
|
InFlightGuard(const InFlightGuard&) = delete;
|
||||||
|
InFlightGuard& operator=(const InFlightGuard&) = delete;
|
||||||
|
InFlightGuard& operator=(InFlightGuard&&) = delete;
|
||||||
|
~InFlightGuard() { if (counter) counter->fetch_sub(1, std::memory_order_relaxed); }
|
||||||
|
};
|
||||||
|
|
||||||
} // anonymous namespace
|
} // anonymous namespace
|
||||||
|
|
||||||
const std::string QidiPrinterAgent_VERSION = "0.0.1";
|
const std::string QidiPrinterAgent_VERSION = "0.0.1";
|
||||||
@@ -49,51 +66,156 @@ AgentInfo QidiPrinterAgent::get_agent_info_static()
|
|||||||
return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"};
|
return AgentInfo{"qidi", "Qidi", QidiPrinterAgent_VERSION, "Qidi printer agent"};
|
||||||
}
|
}
|
||||||
|
|
||||||
bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode /*sync_mode*/)
|
FilamentSyncMode QidiPrinterAgent::get_filament_sync_mode() const
|
||||||
{
|
{
|
||||||
std::string error;
|
if (GUI::wxGetApp().app_config->get_bool("use_printer_agents"))
|
||||||
|
return FilamentSyncMode::subscription;
|
||||||
|
return FilamentSyncMode::pull;
|
||||||
|
}
|
||||||
|
|
||||||
// 1. Fetch device info and infer series_id
|
bool QidiPrinterAgent::fetch_filament_info(std::string dev_id, FilamentSyncMode sync_mode)
|
||||||
std::string series_id;
|
{
|
||||||
{
|
if (sync_mode != get_filament_sync_mode())
|
||||||
MoonrakerDeviceInfo info;
|
|
||||||
if (fetch_device_info(device_info.base_url, device_info.api_key, 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(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;
|
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);
|
||||||
|
model_id = device_info.model_id;
|
||||||
|
model_name = device_info.model_name;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Build the AMS payload
|
// Reserve under the same mutex shutdown() uses, so the flag and the count can't race.
|
||||||
build_ams_payload(box_count, box_count * 4 - 1, trays);
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(fetch_lifecycle_mutex);
|
||||||
|
if (shutting_down.load())
|
||||||
|
return false;
|
||||||
|
filament_fetch_in_flight.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
InFlightGuard guard{filament_fetch_in_flight};
|
||||||
|
std::thread([this, guard = std::move(guard), connection = std::move(connection), model_id, model_name]() mutable {
|
||||||
|
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);
|
||||||
|
}).detach();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url,
|
bool QidiPrinterAgent::apply_box_mapping(const PrintParams& params) const
|
||||||
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;
|
||||||
|
if (!send_gcode(device_info.dev_id, "SAVE_VARIABLE VARIABLE=enable_box VALUE=" + std::to_string(enable))) {
|
||||||
|
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::apply_box_mapping: failed to set enable_box";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
if (params.ams_mapping.empty()) {
|
||||||
|
BOOST_LOG_TRIVIAL(warning) << "QidiPrinterAgent::apply_box_mapping: enable_box set but ams_mapping is empty";
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ams_mapping (v0) is a JSON array indexed by filament/tool; each value is the
|
||||||
|
// physical box slot (-1 = unmapped). Mirror it onto the printer's value_t<tool>
|
||||||
|
// variables: SAVE_VARIABLE VARIABLE=value_t<tool> VALUE='slot<n>'.
|
||||||
|
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
|
||||||
|
const std::string gcode = "SAVE_VARIABLE VARIABLE=value_t" + std::to_string(tool) +
|
||||||
|
" VALUE=\"'slot" + std::to_string(slot) + "'\"";
|
||||||
|
if (!send_gcode(device_info.dev_id, gcode)) {
|
||||||
|
BOOST_LOG_TRIVIAL(error) << "QidiPrinterAgent::apply_box_mapping: failed to set value_t" << tool;
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
if (!apply_box_mapping(params))
|
||||||
|
return BAMBU_NETWORK_ERR_PRINT_WR_UPLOAD_FTP_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(base_url, "/printer/objects/query?save_variables=variables");
|
std::string url = join_url(connection.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";
|
||||||
}
|
}
|
||||||
@@ -103,8 +225,9 @@ bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url,
|
|||||||
std::string http_error;
|
std::string http_error;
|
||||||
|
|
||||||
auto http = Http::get(url);
|
auto http = Http::get(url);
|
||||||
if (!api_key.empty()) {
|
configure_http(http, connection);
|
||||||
http.header("X-Api-Key", api_key);
|
if (!connection.api_key.empty()) {
|
||||||
|
http.header("X-Api-Key", connection.api_key);
|
||||||
}
|
}
|
||||||
http.timeout_connect(5)
|
http.timeout_connect(5)
|
||||||
.timeout_max(10)
|
.timeout_max(10)
|
||||||
@@ -129,20 +252,10 @@ bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url,
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto json = nlohmann::json::parse(response_body, nullptr, false, true);
|
nlohmann::json status;
|
||||||
if (json.is_discarded()) {
|
nlohmann::json variables;
|
||||||
error = "Invalid JSON response";
|
if (!parse_slot_response(response_body, status, variables, error))
|
||||||
return false;
|
return false;
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
box_count = variables.value("box_count", 1);
|
||||||
if (box_count < 0) {
|
if (box_count < 0) {
|
||||||
@@ -217,20 +330,45 @@ bool QidiPrinterAgent::fetch_slot_info(const std::string& base_url,
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool QidiPrinterAgent::fetch_filament_dict(const std::string& base_url,
|
bool QidiPrinterAgent::parse_slot_response(const std::string& response_body,
|
||||||
const std::string& api_key,
|
nlohmann::json& status,
|
||||||
|
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(base_url, "/server/files/config/officiall_filas_list.cfg");
|
std::string url = join_url(connection.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);
|
||||||
if (!api_key.empty()) {
|
configure_http(http, connection);
|
||||||
http.header("X-Api-Key", api_key);
|
if (!connection.api_key.empty()) {
|
||||||
|
http.header("X-Api-Key", connection.api_key);
|
||||||
}
|
}
|
||||||
http.timeout_connect(5)
|
http.timeout_connect(5)
|
||||||
.timeout_max(10)
|
.timeout_max(10)
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
|
|
||||||
#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>
|
||||||
@@ -14,7 +16,7 @@ class QidiPrinterAgent final : public MoonrakerPrinterAgent
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit QidiPrinterAgent(std::string log_dir);
|
explicit QidiPrinterAgent(std::string log_dir);
|
||||||
~QidiPrinterAgent() override = default;
|
~QidiPrinterAgent() override { shutdown(); }
|
||||||
|
|
||||||
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(); }
|
||||||
@@ -22,7 +24,23 @@ 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;
|
||||||
@@ -30,14 +48,13 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Qidi-specific methods
|
// Qidi-specific methods
|
||||||
bool fetch_slot_info(const std::string& base_url,
|
bool fetch_slot_info(const ConnectionSettings& connection,
|
||||||
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 std::string& base_url, const std::string& api_key, QidiFilamentDict& dict, std::string& error) const;
|
bool fetch_filament_dict(const ConnectionSettings& connection, 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);
|
||||||
|
|||||||
@@ -2,11 +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/log/trivial.hpp>
|
#include <boost/log/trivial.hpp>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <mutex>
|
||||||
|
#include <sstream>
|
||||||
|
#include <thread>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include "libslic3r/Preset.hpp"
|
#include "libslic3r/Preset.hpp"
|
||||||
@@ -20,6 +27,25 @@ 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 decrement for the in-flight fetch count; movable so a failed thread start still releases it.
|
||||||
|
struct InFlightGuard
|
||||||
|
{
|
||||||
|
std::atomic<int>* counter;
|
||||||
|
explicit InFlightGuard(std::atomic<int>& c) noexcept : counter(&c) {}
|
||||||
|
InFlightGuard(InFlightGuard&& other) noexcept : counter(other.counter) { other.counter = nullptr; }
|
||||||
|
InFlightGuard(const InFlightGuard&) = delete;
|
||||||
|
InFlightGuard& operator=(const InFlightGuard&) = delete;
|
||||||
|
InFlightGuard& operator=(InFlightGuard&&) = delete;
|
||||||
|
~InFlightGuard() { if (counter) counter->fetch_sub(1, std::memory_order_relaxed); }
|
||||||
|
};
|
||||||
|
|
||||||
// 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>
|
||||||
@@ -76,6 +102,31 @@ 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"};
|
||||||
@@ -111,127 +162,155 @@ 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)
|
||||||
{
|
{
|
||||||
std::string url = join_url(device_info.base_url, "/printer/objects/query?print_task_config&filament_detect");
|
(void) dev_id;
|
||||||
|
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;
|
||||||
|
|
||||||
|
std::string base_url;
|
||||||
|
std::string api_key;
|
||||||
|
{
|
||||||
|
std::lock_guard<std::recursive_mutex> lock(connect_mutex);
|
||||||
|
base_url = device_info.base_url;
|
||||||
|
api_key = device_info.api_key;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto json = nlohmann::json::parse(response_body, nullptr, false, true);
|
// Reserve under the same mutex shutdown() uses, so the flag and the count can't race.
|
||||||
if (json.is_discarded()) {
|
{
|
||||||
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Invalid JSON response";
|
std::lock_guard<std::mutex> lock(fetch_lifecycle_mutex);
|
||||||
return false;
|
if (shutting_down.load())
|
||||||
|
return false;
|
||||||
|
filament_fetch_in_flight.fetch_add(1, std::memory_order_relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Navigate to result.status.print_task_config
|
InFlightGuard guard{filament_fetch_in_flight};
|
||||||
if (!json.contains("result") || !json["result"].contains("status") ||
|
std::thread([this, guard = std::move(guard), base_url, api_key]() {
|
||||||
!json["result"]["status"].contains("print_task_config")) {
|
const std::string url = join_url(base_url, "/printer/objects/query?print_task_config&filament_detect");
|
||||||
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Missing print_task_config in response";
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto& ptc = json["result"]["status"]["print_task_config"];
|
std::string response_body;
|
||||||
|
bool success = false;
|
||||||
|
std::string http_error;
|
||||||
|
|
||||||
// Read parallel arrays from print_task_config
|
auto http = Http::get(url);
|
||||||
auto filament_exist = ptc.value("filament_exist", std::vector<bool>{});
|
if (!api_key.empty()) {
|
||||||
auto filament_type = ptc.value("filament_type", std::vector<std::string>{});
|
http.header("X-Api-Key", api_key);
|
||||||
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>{});
|
http.timeout_connect(5)
|
||||||
auto filament_vendor = ptc.value("filament_vendor", std::vector<std::string>{});
|
.timeout_max(10)
|
||||||
|
.on_complete([&](std::string body, unsigned status) {
|
||||||
const int slot_count = static_cast<int>(filament_exist.size());
|
if (status == 200) {
|
||||||
if (slot_count == 0) {
|
response_body = body;
|
||||||
BOOST_LOG_TRIVIAL(info) << "SnapmakerPrinterAgent::fetch_filament_info: No filament slots reported";
|
success = true;
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read NFC filament_detect data for temperature info (optional)
|
|
||||||
nlohmann::json nfc_info;
|
|
||||||
if (json["result"]["status"].contains("filament_detect") &&
|
|
||||||
json["result"]["status"]["filament_detect"].contains("info")) {
|
|
||||||
nfc_info = json["result"]["status"]["filament_detect"]["info"];
|
|
||||||
}
|
|
||||||
|
|
||||||
static const std::string empty_str;
|
|
||||||
static const std::string default_color = "FFFFFFFF";
|
|
||||||
|
|
||||||
std::vector<AmsTrayData> trays;
|
|
||||||
trays.reserve(slot_count);
|
|
||||||
|
|
||||||
for (int i = 0; i < slot_count; ++i) {
|
|
||||||
AmsTrayData tray;
|
|
||||||
tray.slot_index = i;
|
|
||||||
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 {
|
} else {
|
||||||
tray.tray_info_idx = bundle->filaments.filament_id_by_type(tray.tray_type);
|
http_error = "HTTP error: " + std::to_string(status);
|
||||||
}
|
}
|
||||||
} else {
|
})
|
||||||
tray.tray_info_idx = map_filament_type_to_generic_id(tray.tray_type);
|
.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();
|
||||||
|
|
||||||
// Extract NFC temperature data if available
|
if (!success) {
|
||||||
if (nfc_info.is_array() && i < static_cast<int>(nfc_info.size()) && nfc_info[i].is_object()) {
|
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: HTTP request failed: " << http_error;
|
||||||
auto& nfc_slot = nfc_info[i];
|
return;
|
||||||
std::string vendor = nfc_slot.value("VENDOR", "NONE");
|
|
||||||
if (vendor != "NONE" && !vendor.empty()) {
|
|
||||||
tray.bed_temp = nfc_slot.value("BED_TEMP", 0);
|
|
||||||
tray.nozzle_temp = nfc_slot.value("FIRST_LAYER_TEMP", 0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
trays.emplace_back(std::move(tray));
|
auto json = nlohmann::json::parse(response_body, nullptr, false, true);
|
||||||
}
|
if (json.is_discarded()) {
|
||||||
|
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Invalid JSON response";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Navigate to result.status.print_task_config
|
||||||
|
if (!json.contains("result") || !json["result"].contains("status") || !json["result"]["status"].contains("print_task_config")) {
|
||||||
|
BOOST_LOG_TRIVIAL(warning) << "SnapmakerPrinterAgent::fetch_filament_info: Missing print_task_config in response";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& ptc = json["result"]["status"]["print_task_config"];
|
||||||
|
|
||||||
|
// Read parallel arrays from print_task_config
|
||||||
|
auto filament_exist = ptc.value("filament_exist", std::vector<bool>{});
|
||||||
|
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>{});
|
||||||
|
|
||||||
|
const int slot_count = static_cast<int>(filament_exist.size());
|
||||||
|
if (slot_count == 0) {
|
||||||
|
BOOST_LOG_TRIVIAL(info) << "SnapmakerPrinterAgent::fetch_filament_info: No filament slots reported";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read NFC filament_detect data for temperature info (optional)
|
||||||
|
nlohmann::json nfc_info;
|
||||||
|
if (json["result"]["status"].contains("filament_detect") && json["result"]["status"]["filament_detect"].contains("info")) {
|
||||||
|
nfc_info = json["result"]["status"]["filament_detect"]["info"];
|
||||||
|
}
|
||||||
|
|
||||||
|
static const std::string empty_str;
|
||||||
|
static const std::string default_color = "FFFFFFFF";
|
||||||
|
|
||||||
|
std::vector<AmsTrayData> trays;
|
||||||
|
trays.reserve(slot_count);
|
||||||
|
|
||||||
|
for (int i = 0; i < slot_count; ++i) {
|
||||||
|
AmsTrayData tray;
|
||||||
|
tray.slot_index = i;
|
||||||
|
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 = nfc_slot.value("VENDOR", "NONE");
|
||||||
|
if (vendor != "NONE" && !vendor.empty()) {
|
||||||
|
tray.bed_temp = nfc_slot.value("BED_TEMP", 0);
|
||||||
|
tray.nozzle_temp = nfc_slot.value("FIRST_LAYER_TEMP", 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
trays.emplace_back(std::move(tray));
|
||||||
|
}
|
||||||
|
|
||||||
|
build_ams_payload(1, slot_count - 1, trays);
|
||||||
|
}).detach();
|
||||||
|
|
||||||
build_ams_payload(1, slot_count - 1, trays);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
#include "IPrinterAgent.hpp"
|
#include "IPrinterAgent.hpp"
|
||||||
#include "MoonrakerPrinterAgent.hpp"
|
#include "MoonrakerPrinterAgent.hpp"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstdint>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
namespace Slic3r {
|
namespace Slic3r {
|
||||||
@@ -11,16 +13,25 @@ class SnapmakerPrinterAgent final : public MoonrakerPrinterAgent
|
|||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
explicit SnapmakerPrinterAgent(std::string log_dir);
|
explicit SnapmakerPrinterAgent(std::string log_dir);
|
||||||
~SnapmakerPrinterAgent() override = default;
|
~SnapmakerPrinterAgent() override { shutdown(); }
|
||||||
|
|
||||||
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 { return device_info.base_url + "/server/files/camera/monitor.jpg"; }
|
||||||
|
|
||||||
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
|
||||||
|
|||||||
@@ -1,15 +1,20 @@
|
|||||||
#include <catch2/catch_all.hpp>
|
#include <catch2/catch_all.hpp>
|
||||||
|
|
||||||
|
#include <catch2/catch_message.hpp>
|
||||||
#include <catch2/catch_test_macros.hpp>
|
#include <catch2/catch_test_macros.hpp>
|
||||||
#include <catch2/generators/catch_generators.hpp>
|
#include <catch2/generators/catch_generators.hpp>
|
||||||
#include <catch2/matchers/catch_matchers.hpp>
|
#include <catch2/matchers/catch_matchers.hpp>
|
||||||
#include <catch2/matchers/catch_matchers_floating_point.hpp>
|
#include <catch2/matchers/catch_matchers_floating_point.hpp>
|
||||||
#include "libslic3r/libslic3r.h"
|
#include "libslic3r/libslic3r.h"
|
||||||
|
#include "libslic3r/Config.hpp"
|
||||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||||
|
#include "libslic3r/Model.hpp"
|
||||||
#include "libslic3r/Utils.hpp"
|
#include "libslic3r/Utils.hpp"
|
||||||
|
|
||||||
|
#include "test_helpers.hpp"
|
||||||
#include "test_utils.hpp"
|
#include "test_utils.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <cstddef>
|
#include <cstddef>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include "libslic3r/PrintConfig.hpp"
|
#include "libslic3r/PrintConfig.hpp"
|
||||||
@@ -177,3 +182,42 @@ TEST_CASE("A seam takes the actual speed of the move it follows", "[GCodeProcess
|
|||||||
}
|
}
|
||||||
REQUIRE(seams > 0);
|
REQUIRE(seams > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
TEST_CASE("Line ends of the exported G-code mark every newline in the file", "[GCodeProcessor]")
|
||||||
|
{
|
||||||
|
struct Case
|
||||||
|
{
|
||||||
|
const char* name;
|
||||||
|
bool preheat_backtrace;
|
||||||
|
bool pre_heating;
|
||||||
|
};
|
||||||
|
const auto test_case = GENERATE(values<Case>({
|
||||||
|
{ "written by size", false, false },
|
||||||
|
{ "written by time for the preheat backtrace", true, false },
|
||||||
|
{ "rewritten by the pre-heating pass", false, true },
|
||||||
|
}));
|
||||||
|
INFO(test_case.name);
|
||||||
|
DynamicPrintConfig config = Test::multifilament_config(2, {
|
||||||
|
{ "single_extruder_multi_material", 0 },
|
||||||
|
{ "ooze_prevention", test_case.preheat_backtrace },
|
||||||
|
{ "preheat_time", 30 },
|
||||||
|
{ "enable_pre_heating", test_case.pre_heating },
|
||||||
|
});
|
||||||
|
Print print;
|
||||||
|
Model model;
|
||||||
|
const std::vector<std::vector<ConfigBase::SetDeserializeItem>> overrides{ { { "extruder", 1 } }, { { "extruder", 2 } } };
|
||||||
|
Test::init_print({ Test::cube(20), Test::cube(20) }, print, model, config, &overrides);
|
||||||
|
GCodeProcessorResult result;
|
||||||
|
const std::string gcode = Test::gcode(print, &result);
|
||||||
|
REQUIRE((gcode.find("preheat T") != std::string::npos) == test_case.preheat_backtrace);
|
||||||
|
REQUIRE((gcode.find(GCodeProcessor::Machine_Start_GCode_End_Tag) != std::string::npos) == test_case.pre_heating);
|
||||||
|
REQUIRE(gcode.size() > GCodeProcessor::Output_Block_Size);
|
||||||
|
|
||||||
|
std::vector<size_t> newline_ends;
|
||||||
|
for (size_t i = gcode.find('\n'); i != std::string::npos; i = gcode.find('\n', i + 1))
|
||||||
|
newline_ends.push_back(i + 1);
|
||||||
|
REQUIRE(result.lines_ends.size() == newline_ends.size());
|
||||||
|
const auto difference = std::mismatch(result.lines_ends.begin(), result.lines_ends.end(), newline_ends.begin());
|
||||||
|
INFO("first difference at line " << difference.first - result.lines_ends.begin() + 1);
|
||||||
|
CHECK(difference.first == result.lines_ends.end());
|
||||||
|
}
|
||||||
|
|||||||
@@ -14,6 +14,7 @@
|
|||||||
#include <initializer_list>
|
#include <initializer_list>
|
||||||
#include "libslic3r/Point.hpp"
|
#include "libslic3r/Point.hpp"
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <ios>
|
||||||
#include <iterator>
|
#include <iterator>
|
||||||
#include <set>
|
#include <set>
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -330,13 +331,13 @@ void init_and_process_print(std::initializer_list<TriangleMesh> meshes, Slic3r::
|
|||||||
print.process();
|
print.process();
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string gcode(Print & print)
|
std::string gcode(Print & print, GCodeProcessorResult* result)
|
||||||
{
|
{
|
||||||
ScopedTemporaryFile temp(".gcode");
|
ScopedTemporaryFile temp(".gcode");
|
||||||
print.set_status_silent();
|
print.set_status_silent();
|
||||||
print.process();
|
print.process();
|
||||||
print.export_gcode(temp.string(), nullptr, nullptr);
|
print.export_gcode(temp.string(), result, nullptr);
|
||||||
std::ifstream t(temp.string());
|
std::ifstream t(temp.string(), std::ios::binary);
|
||||||
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
|
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
|
||||||
return str;
|
return str;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,9 @@
|
|||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace Slic3r { namespace Test {
|
namespace Slic3r {
|
||||||
|
struct GCodeProcessorResult;
|
||||||
|
namespace Test {
|
||||||
|
|
||||||
constexpr double MM_PER_MIN = 60.0;
|
constexpr double MM_PER_MIN = 60.0;
|
||||||
|
|
||||||
@@ -92,8 +94,8 @@ void init_and_process_print(std::initializer_list<TriangleMesh> meshes, Slic3r::
|
|||||||
void init_and_process_print(std::initializer_list<TestMesh> meshes, Slic3r::Print &print, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items);
|
void init_and_process_print(std::initializer_list<TestMesh> meshes, Slic3r::Print &print, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items);
|
||||||
void init_and_process_print(std::initializer_list<TriangleMesh> meshes, Slic3r::Print &print, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items);
|
void init_and_process_print(std::initializer_list<TriangleMesh> meshes, Slic3r::Print &print, std::initializer_list<Slic3r::ConfigBase::SetDeserializeItem> config_items);
|
||||||
|
|
||||||
// Process `print` and return its exported G-code.
|
// Process `print` and return its exported G-code, filling `result` when one is given.
|
||||||
std::string gcode(Print& print);
|
std::string gcode(Print& print, GCodeProcessorResult* result = nullptr);
|
||||||
|
|
||||||
// Build, slice, and return the G-code for `meshes` under the given config.
|
// Build, slice, and return the G-code for `meshes` under the given config.
|
||||||
std::string slice(std::initializer_list<TestMesh> meshes, const DynamicPrintConfig &config);
|
std::string slice(std::initializer_list<TestMesh> meshes, const DynamicPrintConfig &config);
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ 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
|
||||||
|
|||||||
@@ -1,18 +1,29 @@
|
|||||||
#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; }
|
||||||
@@ -20,6 +31,259 @@ namespace Slic3r { class IPrinterAgent; }
|
|||||||
using namespace Slic3r;
|
using namespace Slic3r;
|
||||||
namespace py = pybind11;
|
namespace py = pybind11;
|
||||||
|
|
||||||
|
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"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===========================================================================
|
||||||
|
// 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)) {}
|
||||||
|
|
||||||
|
std::atomic<bool> invoked{false};
|
||||||
|
std::promise<void> release_gate;
|
||||||
|
std::promise<void> done_promise;
|
||||||
|
|
||||||
|
bool fetch_filament_info(std::string /*dev_id*/, FilamentSyncMode /*sync_mode*/ = FilamentSyncMode::pull) override
|
||||||
|
{
|
||||||
|
std::thread([this]() {
|
||||||
|
invoked.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.get_future().wait();
|
||||||
|
done_promise.set_value();
|
||||||
|
}).detach();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
auto agent = std::make_shared<RecordingAgent>(std::string{});
|
||||||
|
auto done_future = agent->done_promise.get_future();
|
||||||
|
|
||||||
|
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};
|
||||||
|
|
||||||
|
// Joins on scope exit so a throwing REQUIRE does not std::terminate.
|
||||||
|
class ScopedJoiner
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
explicit ScopedJoiner(std::thread& t) : m_thread(t) {}
|
||||||
|
~ScopedJoiner() { if (m_thread.joinable()) m_thread.join(); }
|
||||||
|
ScopedJoiner(const ScopedJoiner&) = delete;
|
||||||
|
ScopedJoiner& operator=(const ScopedJoiner&) = delete;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::thread& m_thread;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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>>()};
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
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)] {
|
||||||
|
struct InFlightGuard
|
||||||
|
{
|
||||||
|
std::atomic<int>& counter;
|
||||||
|
~InFlightGuard() { counter.fetch_sub(1, std::memory_order_relaxed); }
|
||||||
|
} guard{filament_fetch_in_flight};
|
||||||
|
|
||||||
|
g_deferred_fetch_running.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
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;
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
});
|
||||||
|
ScopedJoiner join_destroyer{destroyer};
|
||||||
|
|
||||||
|
// Let teardown pass its wait; the worker has not reserved yet.
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(300));
|
||||||
|
allow_fetch->set_value();
|
||||||
|
|
||||||
|
// Get the fetch actually in flight (parked on allow_finish).
|
||||||
|
for (int i = 0; i < 200 && g_deferred_fetch_running.load() == 0; ++i)
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||||
|
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
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
#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");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user