Files
OrcaSlicer/src/slic3r/Utils/CrealityPrint.cpp
Igor Mammedov c746c48649 CrealityPrint: add ws_send_and_read() helper
Add a reusable websocket helper that sends a JSON command and loops
reads until finding a response containing the expected key. This
handles the printer's unsolicited status messages that arrive on
connect before the actual response. Returns empty string on timeout
instead of throwing.

Signed-off-by: Igor Mammedov <niallain@gmail.com>
2026-05-18 09:41:32 +02:00

295 lines
9.7 KiB
C++

#include "CrealityPrint.hpp"
#include <algorithm>
#include <sstream>
#include <exception>
#include <boost/format.hpp>
#include <boost/foreach.hpp>
#include <boost/log/trivial.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/nowide/convert.hpp>
#include <curl/curl.h>
#include <wx/progdlg.h>
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/format.hpp"
#include "Http.hpp"
#include "libslic3r/AppConfig.hpp"
#include "Bonjour.hpp"
#include "slic3r/GUI/BonjourDialog.hpp"
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using std::to_string;
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
namespace fs = boost::filesystem;
namespace pt = boost::property_tree;
namespace Slic3r {
CrealityPrint::CrealityPrint(DynamicPrintConfig* config) :
m_host(config->opt_string("print_host")),
m_web_ui(config->opt_string("print_host_webui")),
m_cafile(config->opt_string("printhost_cafile")),
m_port(config->opt_string("printhost_port")),
m_apikey(config->opt_string("printhost_apikey")),
m_ssl_revoke_best_effort(config->opt_bool("printhost_ssl_ignore_revoke"))
{}
const char* CrealityPrint::get_name() const { return "Creality Print"; }
std::string CrealityPrint::get_host() const {
return m_host;
}
void CrealityPrint::set_auth(Http& http) const
{
http.header("Authorization", "Bearer " + m_apikey);
if (!m_cafile.empty()) {
http.ca_file(m_cafile);
}
}
wxString CrealityPrint::get_test_ok_msg() const { return _(L("Connected to CrealityPrint successfully!")); }
wxString CrealityPrint::get_test_failed_msg(wxString& msg) const
{
return GUI::format_wxstr("%s: %s", _L("Could not connect to CrealityPrint"), msg.Truncate(256));
}
bool CrealityPrint::test(wxString& msg) const
{
bool res = true;
const char* name = get_name();
auto url = make_url("info");
BOOST_LOG_TRIVIAL(info) << boost::format("%1%: Get version at: %2%") % name % url;
// Here we do not have to add custom "Host" header - the url contains host filled by user and libCurl will set the header by itself.
auto http = Http::get(std::move(url));
set_auth(http);
http.timeout_max(5)
.on_error([&](std::string body, std::string error, unsigned status) {
BOOST_LOG_TRIVIAL(error) << boost::format("%1%: Error getting version: %2%, HTTP %3%, body: `%4%`") % name % error % status %
body;
res = false;
msg = format_error(body, error, status);
})
.on_complete([&, this](std::string body, unsigned) {
BOOST_LOG_TRIVIAL(debug) << boost::format("%1%: Got version: %2%") % name % body;
try {
auto info = json::parse(body);
if (info.contains("model")) {
m_model = info["model"].get<std::string>();
BOOST_LOG_TRIVIAL(info) << boost::format("%1%: Detected model: %2%") % name % m_model;
}
} catch (const json::exception& e) {
BOOST_LOG_TRIVIAL(warning) << boost::format("%1%: Failed to parse /info response: %2%") % name % e.what();
}
})
#ifdef WIN32
.ssl_revoke_best_effort(m_ssl_revoke_best_effort)
.on_ip_resolve([&](std::string address) {
// Workaround for Windows 10/11 mDNS resolve issue, where two mDNS resolves in succession fail.
// Remember resolved address to be reused at successive REST API call.
msg = GUI::from_u8(address);
})
#endif // WIN32
.perform_sync();
return res;
}
PrintHostPostUploadActions CrealityPrint::get_post_upload_actions() const {
return PrintHostPostUploadAction::StartPrint;
}
bool CrealityPrint::upload(PrintHostUpload upload_data, ProgressFn prorgess_fn, ErrorFn error_fn, InfoFn info_fn) const
{
const char* name = get_name();
const auto upload_filename = upload_data.upload_path.filename();
const auto upload_parent_path = upload_data.upload_path.parent_path();
wxString test_msg;
if (!test(test_msg)) {
error_fn(std::move(test_msg));
return false;
}
bool res = true;
auto url = make_url("upload/" + safe_filename(upload_filename.string()));
auto http = Http::post(url); // std::move(url));
set_auth(http);
http.form_add("path", upload_parent_path.string())
.form_add_file("file", upload_data.source_path.string(), upload_filename.string())
.on_complete([&](std::string body, unsigned status) {
BOOST_LOG_TRIVIAL(debug) << boost::format("%1%: File uploaded: HTTP %2%: %3%") % name % status % body;
if (upload_data.post_action == PrintHostPostUploadAction::StartPrint) {
wxString errormsg;
if (!start_print(errormsg, safe_filename(upload_filename.string()))) {
error_fn(std::move(errormsg));
res = false;
}
}
})
.on_error([&](std::string body, std::string error, unsigned status) {
BOOST_LOG_TRIVIAL(error) << boost::format("%1%: Error uploading file to %2%: %3%, HTTP %4%, body: `%5%`") % name % url % error %
status % body;
error_fn(format_error(body, error, status));
res = false;
})
.on_progress([&](Http::Progress progress, bool& cancel) {
prorgess_fn(std::move(progress), cancel);
if (cancel) {
// Upload was canceled
BOOST_LOG_TRIVIAL(info) << name << ": Upload canceled";
res = false;
}
})
#ifdef WIN32
.ssl_revoke_best_effort(m_ssl_revoke_best_effort)
#endif
.perform_sync();
return res;
}
std::string CrealityPrint::make_url(const std::string &path) const
{
if (m_host.find("http://") == 0 || m_host.find("https://") == 0) {
if (m_host.back() == '/') {
return (boost::format("%1%%2%") % m_host % path).str();
} else {
return (boost::format("%1%/%2%") % m_host % path).str();
}
} else {
return (boost::format("http://%1%/%2%") % m_host % path).str();
}
}
std::string CrealityPrint::safe_filename(const std::string &filename) const
{
std::string safe_filename = filename;
std::replace(safe_filename.begin(), safe_filename.end(), ' ', '_');
return safe_filename;
}
static void ws_connect(net::io_context& ioc, websocket::stream<beast::tcp_stream>& ws,
const std::string& host_url, const std::string& port)
{
std::string host = Http::get_host_from_url(host_url);
tcp::resolver resolver{ioc};
beast::get_lowest_layer(ws).expires_after(std::chrono::seconds(5));
auto const results = resolver.resolve(host, port);
beast::get_lowest_layer(ws).connect(results);
host += ':' + std::to_string(beast::get_lowest_layer(ws).socket().remote_endpoint().port());
ws.set_option(websocket::stream_base::decorator(
[](websocket::request_type& req) {
req.set(http::field::user_agent,
std::string(BOOST_BEAST_VERSION_STRING) + " websocket-client-coro");
}));
ws.handshake(host, "/");
#ifdef _WIN32
DWORD recv_timeout = 3000;
#else
struct timeval recv_timeout = {3, 0};
#endif
setsockopt(beast::get_lowest_layer(ws).socket().native_handle(),
SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&recv_timeout), sizeof(recv_timeout));
}
static std::string ws_send_and_read(websocket::stream<beast::tcp_stream>& ws, const json& cmd, const std::string& expected_key, int max_reads = 20)
{
ws.write(net::buffer(to_string(cmd)));
for (int i = 0; i < max_reads; i++) {
beast::flat_buffer buf;
beast::error_code ec;
ws.read(buf, ec);
if (ec == net::error::would_block)
break;
if (ec)
throw beast::system_error{ec};
std::string msg = beast::buffers_to_string(buf.data());
if (msg.find(expected_key) != std::string::npos)
return msg;
}
BOOST_LOG_TRIVIAL(warning) << "CrealityPrint: No '" << expected_key << "' response after " << max_reads << " messages";
return {};
}
void CrealityPrint::query_model() const
{
if (!m_model.empty())
return;
wxString msg;
test(msg);
}
bool CrealityPrint::supports_multi_color_print() const
{
query_model();
// K2-platform printers with CFS support
return m_model == "F008" // K2 Plus
|| m_model == "F012" // K2 Pro
|| m_model == "F021"; // K2
}
bool CrealityPrint::start_print(wxString &msg, const std::string &filename) const
{
try {
net::io_context ioc;
websocket::stream<beast::tcp_stream> ws{ioc};
ws_connect(ioc, ws, m_host, "9999");
json j2 = {
{ "method", "set" },
{
"params", {
{ "opGcodeFile", "printprt:/usr/data/printer_data/gcodes/" + filename }
}
}
};
ws.write(net::buffer(to_string(j2)));
beast::flat_buffer buffer;
ws.read(buffer);
return true;
} catch(std::exception const& e) {
BOOST_LOG_TRIVIAL(error) << "CrealityPrint: Error starting print: " << e.what();
msg = wxString::FromUTF8(e.what());
return false;
}
}
}