Start a Creality print from the path the printer lists the upload at (#17633)

Upload and Print picked the start command's folder from the model that /info reports, and every
unlisted model got /mnt/UDISK. A Nebula Pad reports the printer it is fitted to, such as
"Ender-3 V2 Neo", and keeps its G-code under /usr/data, so its firmware ignored the start.

Before the start, the host now asks the printer for its G-code file list (reqGcodeFile), as
Creality Print does, and starts the upload from the path listed for it. K1-family firmware answers
retGcodeFileInfo and K2-family firmware retGcodeFileInfo2. A list without the upload is asked for
again until files_reply passes. When the printer doesn't list the upload, the model table decides
as before, and it now includes "Ender-3 V2 Neo".

(cherry picked from commit 4a45621b57)
This commit is contained in:
Arthur Porto authored and raistlin7447 committed 2026-11-21 09:34:38 -06:00
1 parent 413218414e
commit 2c01dd1cf5
3 files changed
+324 -36

No files matched your search

+177 -29
View File
@@ -27,6 +27,8 @@
#include <boost/nowide/convert.hpp>
#include <curl/curl.h>
#include <optional>
#include <thread>
#include <utility>
#include <vector>
#include <wx/progdlg.h>
@@ -162,7 +164,11 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn,
auto http = Http::post(url); // std::move(url));
set_auth(http);
if (!supports_multi_color_print())
// Multi-color models get no folder with the upload, so they keep it right under printer_data/gcodes.
const bool multi_color = supports_multi_color_print();
const auto remote_path = multi_color || upload_parent_path.empty() ? safe_upload_filename :
(upload_parent_path / safe_upload_filename).generic_string();
if (!multi_color)
http.form_add("path", upload_parent_path.string());
http.form_add_file("file", upload_data.source_path.string(), safe_upload_filename)
@@ -171,7 +177,7 @@ bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn,
if (upload_data.post_action == PrintHostPostUploadAction::StartPrint) {
wxString errormsg;
if (!start_print(errormsg, safe_upload_filename, upload_data.extended_info)) {
if (!start_print(errormsg, remote_path, upload_data.extended_info)) {
error_fn(std::move(errormsg));
res = false;
}
@@ -278,24 +284,15 @@ static int reported_cfs_connect(const std::string& msg)
return cfs_connect == 1 ? 1 : -1;
}
// Sends the CFS slot query and returns the reply, or nothing when none arrives in time.
// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer.
// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7
// reports no CFS connected for its CFS Lite and still sends the slots.
static std::string ws_query_slots(net::io_context& ioc,
websocket::stream<beast::tcp_stream>& ws,
std::chrono::milliseconds slots_reply,
std::chrono::milliseconds cfs_reply,
std::chrono::milliseconds no_cfs_reply,
bool* no_cfs)
// Reads the printer's messages until one holds key and returns it, or returns nothing once deadline passes or on_other, which gets
// every other message, returns false. The deadline also ends the read when the printer keeps sending heartbeats or status updates.
template<class OnOther>
static std::string ws_await_reply(net::io_context& ioc,
websocket::stream<beast::tcp_stream>& ws,
const std::chrono::steady_clock::time_point& deadline,
const char* key,
OnOther&& on_other)
{
const auto sent = std::chrono::steady_clock::now();
auto deadline = sent + slots_reply;
bool reported_no_cfs = false;
beast::get_lowest_layer(ws).expires_at(deadline);
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}});
// The deadline also ends the read when the printer keeps sending heartbeats or status updates.
while (std::chrono::steady_clock::now() < deadline) {
beast::flat_buffer buf;
const beast::error_code ec = ws_read(ioc, ws, buf);
@@ -310,8 +307,32 @@ static std::string ws_query_slots(net::io_context& ioc,
ws_write(ioc, ws, "ok");
continue;
}
if (msg.find("boxsInfo") != std::string::npos)
if (msg.find(key) != std::string::npos)
return msg;
if (!on_other(msg))
break;
}
return {};
}
// Sends the CFS slot query and returns the reply, or nothing when none arrives in time.
// The query gets slots_reply, or the later of slots_reply and cfs_reply once a status reports a CFS connected, since such a printer does answer.
// A status reporting no CFS connected cuts the wait to no_cfs_reply from then, and sets *no_cfs if no reply follows: a SPARKX i7
// reports no CFS connected for its CFS Lite and still sends the slots.
static std::string ws_query_slots(net::io_context& ioc,
websocket::stream<beast::tcp_stream>& ws,
std::chrono::milliseconds slots_reply,
std::chrono::milliseconds cfs_reply,
std::chrono::milliseconds no_cfs_reply,
bool* no_cfs)
{
const auto sent = std::chrono::steady_clock::now();
auto deadline = sent + slots_reply;
beast::get_lowest_layer(ws).expires_at(deadline);
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"boxsInfo", 1}}}});
bool reported_no_cfs = false;
const std::string reply = ws_await_reply(ioc, ws, deadline, "boxsInfo", [&](const std::string& msg) {
const int cfs_connect = reported_cfs_connect(msg);
if (cfs_connect == 0 && !reported_no_cfs) {
reported_no_cfs = true;
@@ -323,15 +344,94 @@ static std::string ws_query_slots(net::io_context& ioc,
deadline = sent + std::max(slots_reply, cfs_reply);
beast::get_lowest_layer(ws).expires_at(deadline);
}
}
return true;
});
if (!reply.empty())
return reply;
if (reported_no_cfs) {
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer reports no CFS connected";
if (no_cfs)
*no_cfs = true;
return {};
} else
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response";
return reply;
}
// The full path a reply to reqGcodeFile lists remote_path at, an empty string when it does not list it, or nothing when the reply
// is no list this code reads. K2-family firmware answers retGcodeFileInfo2, a list of files with their path. K1-family firmware
// answers retGcodeFileInfo, whose fileInfo holds "folder:name:size:..." entries separated by ';'.
static std::optional<std::string> listed_gcode_path(const std::string& reply_text, const std::string& remote_path)
{
const json reply = json::parse(reply_text, nullptr, false);
if (!reply.is_object())
return std::nullopt;
const std::string under_gcodes = "/printer_data/gcodes/" + remote_path;
if (const auto files = reply.find("retGcodeFileInfo2"); files != reply.end() && files->is_array()) {
for (const json& file : *files)
if (file.is_object() && file.contains("path") && file.at("path").is_string() &&
boost::algorithm::ends_with(file.at("path").get<std::string>(), under_gcodes))
return file.at("path").get<std::string>();
return std::string();
}
const auto info = reply.find("retGcodeFileInfo");
if (info == reply.end() || !info->is_object() || !info->contains("fileInfo") || !info->at("fileInfo").is_string())
return std::nullopt;
// Finds the name between its folder and its size, so a name holding ';' or ':' is found too.
const std::string file_info = info->at("fileInfo").get<std::string>();
const std::string name = remote_path.substr(remote_path.rfind('/') + 1);
const std::string field = ':' + name + ':';
for (size_t at = file_info.find(field); at != std::string::npos; at = file_info.find(field, at + 1)) {
const size_t entry = file_info.rfind(';', at);
const size_t begin = entry == std::string::npos ? 0 : entry + 1;
const std::string path = file_info.substr(begin, at - begin) + '/' + name;
if (boost::algorithm::ends_with(path, under_gcodes))
return path;
}
return std::string();
}
namespace {
// What the printer's G-code file list says about an upload.
struct GcodeListing
{
enum class Result { NoReply, Unreadable, NotListed, Listed } result = Result::NoReply;
std::string path; // The full path the upload is listed at
};
} // namespace
// Asks for the G-code file list until it lists remote_path or files_reply passes. A printer can answer before it has indexed a
// file just uploaded, so a list without the upload is asked for again after files_retry.
static GcodeListing ws_find_listed_gcode(net::io_context& ioc,
websocket::stream<beast::tcp_stream>& ws,
std::chrono::milliseconds files_reply,
std::chrono::milliseconds files_retry,
const std::string& remote_path)
{
const auto deadline = std::chrono::steady_clock::now() + files_reply;
GcodeListing listing;
for (;;) {
beast::get_lowest_layer(ws).expires_at(deadline);
ws_send(ioc, ws, json{{"method", "get"}, {"params", {{"reqGcodeFile", 1}}}});
const std::string reply = ws_await_reply(ioc, ws, deadline, "retGcodeFileInfo", [](const std::string&) { return true; });
if (reply.empty())
return listing;
const std::optional<std::string> path = listed_gcode_path(reply, remote_path);
if (!path) {
listing.result = GcodeListing::Result::Unreadable;
return listing;
}
if (!path->empty()) {
listing.result = GcodeListing::Result::Listed;
listing.path = *path;
return listing;
}
listing.result = GcodeListing::Result::NotListed;
if (std::chrono::steady_clock::now() + files_retry >= deadline)
return listing;
std::this_thread::sleep_for(files_retry);
}
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for a 'boxsInfo' response";
return {};
}
// The K1 SE closes its side after a reply and K1-family printers after a start command, so a close error is not a failure.
@@ -341,7 +441,8 @@ static void ws_close(net::io_context& ioc, websocket::stream<beast::tcp_stream>&
run_until_done(ioc, [&](auto&& handler) { ws.async_close(websocket::close_code::normal, handler); });
}
// Add a model by its /info value once its firmware is known to keep gcodes under /usr/data; every other model uses /mnt/UDISK.
// The folder for a printer that lists no G-code file. Add a model by its /info value once its firmware is known to keep gcodes
// under /usr/data; every other model uses /mnt/UDISK.
static bool stores_gcode_in_usr_data(const std::string& model)
{
static const std::unordered_set<std::string> usr_data_models = {
@@ -351,6 +452,7 @@ static bool stores_gcode_in_usr_data(const std::string& model)
"F004", // Ender-5 Max
"F005", // Ender-3 V3 KE
"F016", // K2 SE
"Ender-3 V2 Neo", // Nebula Pad on an Ender-3 V2 Neo
"K1",
"K1 Max",
"K1 Max_CFS-C",
@@ -440,6 +542,45 @@ std::string CrealityPrint::query_boxes_info(bool* no_cfs) const
}
}
// Uses a connection of its own, since the K1 SE closes its side after a reply. A failed connection is not caught: the start would
// fail the same way, and trying again would double the wait.
std::string CrealityPrint::query_listed_gcode(const std::string& remote_path) const
{
net::io_context ioc;
websocket::stream<beast::tcp_stream> ws{ioc};
ws_connect(ioc, ws, m_host, ws_settings.port, ws_settings.connect);
GcodeListing listing;
try {
listing = ws_find_listed_gcode(ioc, ws, ws_settings.files_reply, ws_settings.files_retry, remote_path);
} catch (std::exception const& e) {
BOOST_LOG_TRIVIAL(error) << "CrealityPrint: Failed to query the G-code file list: " << e.what();
return {};
}
switch (listing.result) {
case GcodeListing::Result::Listed:
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: The printer lists " << remote_path << " at " << listing.path;
break;
case GcodeListing::Result::NotListed:
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list does not include " << remote_path;
break;
case GcodeListing::Result::Unreadable:
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: The printer's G-code file list has no format this host reads";
break;
case GcodeListing::Result::NoReply:
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: Timed out waiting for the G-code file list";
break;
}
// A printer that sent no list may not answer a close either, so its connection is dropped without one.
if (listing.result == GcodeListing::Result::NoReply) {
beast::error_code ec;
beast::get_lowest_layer(ws).socket().close(ec);
} else
ws_close(ioc, ws, ws_settings.close);
return listing.path;
}
CrealityPrinterInfo CrealityPrint::read_printer_info() const
{
CrealityPrinterInfo info;
@@ -528,14 +669,21 @@ std::vector<std::string> CrealityPrint::start_print_commands(bool
return commands;
}
bool CrealityPrint::start_print(wxString &msg, const std::string &filename, const std::map<std::string, std::string>& extended_info) const
bool CrealityPrint::start_print(wxString &msg, const std::string &remote_path, const std::map<std::string, std::string>& extended_info) const
{
try {
// Runs before the WebSocket opens and its reply deadline starts, since it can query the
// printer over HTTP. It also fills m_model.
const bool multi_color = supports_multi_color_print();
const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK";
const std::string gcode_path = data_root + "/printer_data/gcodes/" + filename;
const bool multi_color = supports_multi_color_print();
// Starts the file at the path the printer lists it at, as Creality Print does, since the
// folder depends on the printer's board and not on its model. The model decides only when
// the printer does not list the upload.
std::string gcode_path = query_listed_gcode(remote_path);
if (gcode_path.empty()) {
const std::string data_root = stores_gcode_in_usr_data(m_model) ? "/usr/data" : "/mnt/UDISK";
gcode_path = data_root + "/printer_data/gcodes/" + remote_path.substr(remote_path.rfind('/') + 1);
BOOST_LOG_TRIVIAL(info) << "CrealityPrint: Using " << data_root << " for model " << m_model;
}
net::io_context ioc;
websocket::stream<beast::tcp_stream> ws{ioc};
+6 -1
View File
@@ -70,6 +70,8 @@ protected:
std::chrono::milliseconds reply{std::chrono::seconds(10)}; // Commands and the replies read after them
std::chrono::milliseconds slots_reply{std::chrono::seconds(5)}; // The CFS slot query, extended to reply once a status reports a CFS connected
std::chrono::milliseconds no_cfs_reply{std::chrono::seconds(2)}; // The CFS slot query once a status reports no CFS connected
std::chrono::milliseconds files_reply{std::chrono::seconds(3)}; // The G-code file list query before a start, asked again within it
std::chrono::milliseconds files_retry{std::chrono::milliseconds(500)}; // The pause before asking again for a list without the upload
std::chrono::milliseconds close{std::chrono::seconds(3)}; // Closing handshake
} ws_settings;
@@ -83,7 +85,10 @@ private:
mutable std::string m_model;
std::string make_url(const std::string& path) const;
bool start_print(wxString& msg, const std::string& filename, const std::map<std::string, std::string>& extended_info) const;
// remote_path is where the upload went under printer_data/gcodes.
bool start_print(wxString& msg, const std::string& remote_path, const std::map<std::string, std::string>& extended_info) const;
// The full path the printer lists remote_path at, or nothing when it does not list it. Throws when the printer cannot be reached.
std::string query_listed_gcode(const std::string& remote_path) const;
std::string safe_filename(const std::string& filename) const;
void query_model() const;
// Reads /info and caches the model. When msg is not null, it gets a translated error, or on Windows the resolved address.
+141 -6
View File
@@ -2,6 +2,7 @@
#include <catch2/catch_test_macros.hpp>
#include <catch2/generators/catch_generators.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
@@ -73,11 +74,13 @@ struct Message
std::string payload;
};
// Serves the printer's HTTP API and its websocket on one port.
// Serves the printer's HTTP API and its websocket on one port. With file_lists, each G-code file list query gets the next one,
// and the last one once they run out.
class FakeCrealityPrinter
{
public:
FakeCrealityPrinter(Behavior behavior, std::string model) : m_behavior(behavior), m_model(std::move(model))
FakeCrealityPrinter(Behavior behavior, std::string model, std::vector<std::string> file_lists = {})
: m_behavior(behavior), m_model(std::move(model)), m_file_lists(std::move(file_lists))
{
m_accept_thread = std::thread([this] { accept_loop(); });
}
@@ -110,6 +113,12 @@ public:
return m_http_requests;
}
int websocket_requests()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_websocket_requests;
}
// Hangs up every connection that is waiting.
void release()
{
@@ -144,6 +153,10 @@ private:
serve_http(socket, request);
return;
}
{
std::lock_guard<std::mutex> lock(m_mutex);
++m_websocket_requests;
}
if (m_behavior == Behavior::SilentBeforeHandshake) {
wait_for_release();
return;
@@ -171,6 +184,15 @@ private:
m_messages.push_back({ws.got_text(), payload});
}
const std::string slots = R"({"boxsInfo":{"materialBoxs":[]}})";
if (!m_file_lists.empty() && payload.find("reqGcodeFile") != std::string::npos) {
std::string file_list;
{
std::lock_guard<std::mutex> lock(m_mutex);
file_list = m_file_lists[std::min(m_file_list_replies++, m_file_lists.size() - 1)];
}
ws.write(net::buffer(file_list), ec);
continue;
}
if (first && m_behavior == Behavior::ReportsNoCfs) {
ws.write(net::buffer(std::string(R"({"cfsConnect":0,"nozzleTemp":"25.000000"})")), ec);
wait_for_release();
@@ -236,6 +258,7 @@ private:
const Behavior m_behavior;
const std::string m_model;
const std::vector<std::string> m_file_lists;
net::io_context m_accept_ioc;
tcp::acceptor m_acceptor{m_accept_ioc, {net::ip::make_address("127.0.0.1"), 0}};
std::atomic<bool> m_stopping{false};
@@ -245,6 +268,8 @@ private:
std::condition_variable m_changed;
std::vector<Message> m_messages;
int m_http_requests = 0;
int m_websocket_requests = 0;
std::size_t m_file_list_replies = 0;
bool m_released = false;
};
@@ -276,6 +301,7 @@ std::unique_ptr<TestHost> make_host(const FakeCrealityPrinter& printer, std::chr
host->ws_settings.reply = deadline;
host->ws_settings.slots_reply = deadline;
host->ws_settings.no_cfs_reply = deadline;
host->ws_settings.files_reply = deadline;
host->ws_settings.close = deadline;
return host;
}
@@ -294,18 +320,39 @@ template<class Call> bool finishes_within(FakeCrealityPrinter& printer, std::chr
return in_time;
}
bool upload_and_print(const CrealityPrint& host, wxString& error, const std::map<std::string, std::string>& extended_info = {})
bool upload_and_print(const CrealityPrint& host,
wxString& error,
const std::map<std::string, std::string>& extended_info = {},
const std::string& upload_path = "test.gcode")
{
const ScopedTemporaryFile source(".gcode");
std::ofstream(source.string()) << "G28\n";
PrintHostUpload upload;
upload.source_path = source.path();
upload.upload_path = "test.gcode";
upload.upload_path = upload_path;
upload.post_action = PrintHostPostUploadAction::StartPrint;
upload.extended_info = extended_info;
return host.upload(upload, [](Http::Progress, bool&) {}, [&](wxString message) { error = message; }, [](wxString, wxString) {});
}
bool is_file_list_query(const Message& message) { return message.payload.find("reqGcodeFile") != std::string::npos; }
int file_list_queries(FakeCrealityPrinter& printer)
{
const std::vector<Message> messages = printer.messages();
return static_cast<int>(std::count_if(messages.begin(), messages.end(), is_file_list_query));
}
// The start commands, without the G-code file list query and the heartbeat acknowledgement sent on its connection.
std::vector<Message> start_messages(FakeCrealityPrinter& printer)
{
std::vector<Message> messages = printer.messages();
messages.erase(std::remove_if(messages.begin(), messages.end(),
[](const Message& message) { return is_file_list_query(message) || message.payload == "ok"; }),
messages.end());
return messages;
}
} // namespace
TEST_CASE("Querying the CFS slots gives a silent printer no more than its deadlines", "[CrealityPrint]")
@@ -510,11 +557,14 @@ TEST_CASE("Starting a print gives a silent printer no more than its deadlines",
CHECK(result == started);
CHECK(error.empty() == started);
CHECK(error.StartsWith("Connection timed out") == !started);
// A printer that never completes the handshake for the G-code file list query gets no second connection for the start.
CHECK(printer.websocket_requests() == (started ? 2 : 1));
}
TEST_CASE("Starting a print sends each command with the G-code path in a text frame", "[CrealityPrint]")
{
// F008 is a multi-color model and F018 a plain one. K1C, F005 (Ender-3 V3 KE) and F016 (K2 SE) keep their G-code under /usr/data.
// The printer never answers the G-code file list query, so the model decides the folder. F008 is a multi-color model and F018
// a plain one. K1C, F005 (Ender-3 V3 KE), F016 (K2 SE) and a Nebula Pad on an Ender-3 V2 Neo keep their G-code under /usr/data.
// Only a mapping onto CFS slots starts a multi-color print; a printer that listed no slots starts plainly.
const std::map<std::string, std::string> cfs_mapping = {{"enableSelfTest", "0"}, {"colorMatch_0", "T1A\tPLA\t#FF0000\t1\t0"}};
const auto [model, extended_info, commands, gcode] = GENERATE_REF(table<std::string, std::map<std::string, std::string>, std::vector<std::string>, std::string>({
@@ -522,6 +572,7 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr
{"F008", {}, {"opGcodeFile"}, "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"F018", {}, {"opGcodeFile"}, "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"F005", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"},
{"Ender-3 V2 Neo", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"},
{"F016", cfs_mapping, {"colorMatch", "multiColorPrint"}, "/usr/data/printer_data/gcodes/test.gcode"},
{"K1C", cfs_mapping, {"colorMatch", "multiColorPrint"}, "/usr/data/printer_data/gcodes/test.gcode"},
{"K1C", {}, {"opGcodeFile"}, "printprt:/usr/data/printer_data/gcodes/test.gcode"},
@@ -530,11 +581,12 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr
FakeCrealityPrinter printer(Behavior::Answers, model);
const auto host = make_host(printer, 5s);
host->ws_settings.files_reply = 200ms;
wxString error;
CHECK(upload_and_print(*host, error, extended_info));
CHECK(error.empty());
const std::vector<Message> messages = printer.messages();
const std::vector<Message> messages = start_messages(printer);
REQUIRE(messages.size() == commands.size());
for (std::size_t i = 0; i < messages.size(); ++i) {
CAPTURE(i);
@@ -545,6 +597,89 @@ TEST_CASE("Starting a print sends each command with the G-code path in a text fr
}
}
TEST_CASE("Starting a print uses the path the printer lists the upload at", "[CrealityPrint]")
{
// K1-family firmware lists "folder:name:size:..." entries, escaping its slashes, and K2-family firmware files with their path.
// The listed path decides over the model, which would give F018 and the unlisted F099 /mnt/UDISK and K1C /usr/data. Only the
// upload counts: another file, a list without files, or a list in a format this host does not read leave the folder to the
// model. A name holding ';' and a file in a subfolder are still found. A name that is not UTF-8 makes the printer's text frame
// invalid, so the whole list is lost and the model decides, but the print still starts.
const std::string k1_upload = R"({"retGcodeFileInfo":{"totalNum":1,"fileInfo":"\/usr\/data\/printer_data\/gcodes:test.gcode:63301:0.240000:1794188820:109:\/tmp\/test.png;"}})";
const std::string k1_other = R"({"retGcodeFileInfo":{"totalNum":1,"fileInfo":"/usr/data/printer_data/gcodes:other.gcode:63301:0.240000:1794188820:109:/tmp/other.png;"}})";
const std::string k1_semicolon = R"({"retGcodeFileInfo":{"totalNum":2,"fileInfo":"/usr/data/printer_data/gcodes:other.gcode:63301:0.240000:1794188820:109:/tmp/other.png;)"
R"(/usr/data/printer_data/gcodes:a;b.gcode:63301:0.240000:1794188820:109:/tmp/a;b.png;"}})";
const std::string k1_subfolder = R"({"retGcodeFileInfo":{"totalNum":2,"fileInfo":"/usr/data/printer_data/gcodes:test.gcode:63301:0.240000:1794188820:109:/tmp/test.png;)"
R"(/usr/data/printer_data/gcodes/parts:test.gcode:63301:0.240000:1794188820:109:/tmp/test.png;"}})";
const std::string k2_upload = R"({"retGcodeFileInfo2":[{"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})";
const std::string k2_both = R"({"retGcodeFileInfo2":[{"name":"other.gcode","path":"/usr/data/printer_data/gcodes/other.gcode","type":8},)"
R"({"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})";
const std::string k2_not_utf8 = R"({"retGcodeFileInfo2":[{"name":"x.gcode","path":"/mnt/UDISK/printer_data/gcodes/)" "\xff" R"(.gcode","type":8},)"
R"({"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})";
const std::string no_files = R"({"retGcodeFileInfo2":[]})";
const std::string no_folders = R"({"retGcodeFileInfo3":{"fileInfo":"test.gcode:63301:1794188820;"}})";
const auto [model, upload_path, file_list, gcode] = GENERATE_REF(table<std::string, std::string, std::string, std::string>({
{"F099", "test.gcode", k1_upload, "/usr/data/printer_data/gcodes/test.gcode"},
{"F018", "test.gcode", k1_other, "/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"F018", "a;b.gcode", k1_semicolon, "/usr/data/printer_data/gcodes/a;b.gcode"},
{"F018", "parts/test.gcode", k1_subfolder, "/usr/data/printer_data/gcodes/parts/test.gcode"},
{"K1C", "test.gcode", k2_upload, "/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"K1C", "test.gcode", k2_both, "/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"K1C", "test.gcode", k2_not_utf8, "/usr/data/printer_data/gcodes/test.gcode"},
{"F005", "test.gcode", no_files, "/usr/data/printer_data/gcodes/test.gcode"},
{"F018", "test.gcode", no_files, "/mnt/UDISK/printer_data/gcodes/test.gcode"},
{"F018", "test.gcode", no_folders, "/mnt/UDISK/printer_data/gcodes/test.gcode"},
}));
CAPTURE(model, upload_path, file_list);
FakeCrealityPrinter printer(Behavior::Answers, model, {file_list});
const auto host = make_host(printer, 5s);
host->ws_settings.files_reply = 300ms;
host->ws_settings.files_retry = 50ms;
wxString error;
CHECK(upload_and_print(*host, error, {}, upload_path));
CHECK(error.empty());
const std::vector<Message> messages = printer.messages();
REQUIRE_FALSE(messages.empty());
CHECK(is_file_list_query(messages[0]));
CHECK(messages[0].text);
const std::vector<Message> start = start_messages(printer);
REQUIRE(start.size() == 1);
const nlohmann::json params = nlohmann::json::parse(start[0].payload).at("params");
CHECK(params.at("opGcodeFile") == "printprt:" + gcode);
}
TEST_CASE("Starting a print asks again for a file list that does not list the upload yet", "[CrealityPrint]")
{
// The first list comes before the printer has indexed the upload. K1C's model alone would give /usr/data.
const std::string no_files = R"({"retGcodeFileInfo2":[]})";
const std::string k2_upload = R"({"retGcodeFileInfo2":[{"name":"test.gcode","path":"/mnt/UDISK/printer_data/gcodes/test.gcode","type":8}]})";
FakeCrealityPrinter printer(Behavior::Answers, "K1C", {no_files, k2_upload});
const auto host = make_host(printer, 5s);
host->ws_settings.files_retry = 50ms;
wxString error;
CHECK(upload_and_print(*host, error));
CHECK(error.empty());
CHECK(file_list_queries(printer) == 2);
const std::vector<Message> start = start_messages(printer);
REQUIRE(start.size() == 1);
CHECK(nlohmann::json::parse(start[0].payload).at("params").at("opGcodeFile") == "printprt:/mnt/UDISK/printer_data/gcodes/test.gcode");
}
TEST_CASE("Starting a print asks once for a file list in a format this host does not read", "[CrealityPrint]")
{
const std::string no_folders = R"({"retGcodeFileInfo3":{"fileInfo":"test.gcode:63301:1794188820;"}})";
FakeCrealityPrinter printer(Behavior::Answers, "F018", {no_folders});
const auto host = make_host(printer, 5s);
host->ws_settings.files_retry = 50ms;
wxString error;
CHECK(upload_and_print(*host, error));
CHECK(error.empty());
CHECK(file_list_queries(printer) == 1);
}
namespace {
const std::string gcode_path = "/usr/data/printer_data/gcodes/part.gcode";