Added possibility for upload to Duet

Further changes:
- Added new configuration option Host Type
- Added abstract base class for future printer hosts
- Moved location of upload dialog (also made it a little bit more configureable)
- added possibility to send file via postfield instead a new frame
This commit is contained in:
Martin Loidl 2018-07-08 14:32:48 +02:00 committed by Vojtech Kral
parent 3433e8e374
commit dd1fd66a47
29 changed files with 699 additions and 128 deletions

View file

@ -0,0 +1,281 @@
#include "Duet.hpp"
#include "PrintHostSendDialog.hpp"
#include <algorithm>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <boost/log/trivial.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <wx/frame.h>
#include <wx/event.h>
#include <wx/progdlg.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "libslic3r/PrintConfig.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/MsgDialog.hpp"
#include "Http.hpp"
namespace fs = boost::filesystem;
namespace pt = boost::property_tree;
namespace Slic3r {
Duet::Duet(DynamicPrintConfig *config) :
host(config->opt_string("print_host")),
password(config->opt_string("printhost_apikey"))
{}
bool Duet::test(wxString &msg) const
{
bool connected = connect(msg);
if (connected) {
disconnect();
}
return connected;
}
wxString Duet::get_test_ok_msg () const
{
return wxString::Format("%s", _(L("Connection to Duet works correctly.")));
}
wxString Duet::get_test_failed_msg (wxString &msg) const
{
return wxString::Format("%s: %s",
_(L("Could not connect to Duet")), msg);
}
bool Duet::send_gcode(const std::string &filename) const
{
enum { PROGRESS_RANGE = 1000 };
const auto errortitle = _(L("Error while uploading to the Duet"));
fs::path filepath(filename);
PrintHostSendDialog send_dialog(filepath.filename(), true);
if (send_dialog.ShowModal() != wxID_OK) { return false; }
const bool print = send_dialog.print();
const auto upload_filepath = send_dialog.filename();
const auto upload_filename = upload_filepath.filename();
const auto upload_parent_path = upload_filepath.parent_path();
wxProgressDialog progress_dialog(
_(L("Duet upload")),
_(L("Sending G-code file to Duet...")),
PROGRESS_RANGE, nullptr, wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT);
progress_dialog.Pulse();
wxString connect_msg;
if (!connect(connect_msg)) {
auto errormsg = wxString::Format("%s: %s", errortitle, connect_msg);
GUI::show_error(&progress_dialog, std::move(errormsg));
return false;
}
bool res = true;
auto upload_cmd = get_upload_url(upload_filepath.string());
BOOST_LOG_TRIVIAL(info) << boost::format("Duet: Uploading file %1%, filename: %2%, path: %3%, print: %4%, command: %5%")
% filepath.string()
% upload_filename.string()
% upload_parent_path.string()
% print
% upload_cmd;
auto http = Http::post(std::move(upload_cmd));
http.postfield_add_file(filename)
.on_complete([&](std::string body, unsigned status) {
BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: File uploaded: HTTP %1%: %2%") % status % body;
progress_dialog.Update(PROGRESS_RANGE);
int err_code = get_err_code_from_body(body);
switch (err_code) {
case 0:
break;
default:
auto msg = format_error(body, L("Unknown error occured"), 0);
GUI::show_error(&progress_dialog, std::move(msg));
res = false;
break;
}
if (err_code == 0 && print) {
wxString errormsg;
res = start_print(errormsg, upload_filepath.string());
if (!res) {
GUI::show_error(&progress_dialog, std::move(errormsg));
}
}
})
.on_error([&](std::string body, std::string error, unsigned status) {
BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error uploading file: %1%, HTTP %2%, body: `%3%`") % error % status % body;
auto errormsg = wxString::Format("%s: %s", errortitle, format_error(body, error, status));
GUI::show_error(&progress_dialog, std::move(errormsg));
res = false;
})
.on_progress([&](Http::Progress progress, bool &cancel) {
if (cancel) {
// Upload was canceled
res = false;
} else if (progress.ultotal > 0) {
int value = PROGRESS_RANGE * progress.ulnow / progress.ultotal;
cancel = !progress_dialog.Update(std::min(value, PROGRESS_RANGE - 1)); // Cap the value to prevent premature dialog closing
} else {
cancel = !progress_dialog.Pulse();
}
})
.perform_sync();
disconnect();
return res;
}
bool Duet::have_auto_discovery() const
{
return false;
}
bool Duet::can_test() const
{
return true;
}
bool Duet::connect(wxString &msg) const
{
bool res = false;
auto url = get_connect_url();
auto http = Http::get(std::move(url));
http.on_error([&](std::string body, std::string error, unsigned status) {
BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error connecting: %1%, HTTP %2%, body: `%3%`") % error % status % body;
msg = format_error(body, error, status);
})
.on_complete([&](std::string body, unsigned) {
BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body;
int err_code = get_err_code_from_body(body);
switch (err_code) {
case 0:
res = true;
break;
case 1:
msg = format_error(body, L("Wrong password"), 0);
break;
case 2:
msg = format_error(body, L("Could not get resources to create a new connection"), 0);
break;
default:
msg = format_error(body, L("Unknown error occured"), 0);
break;
}
})
.perform_sync();
return res;
}
void Duet::disconnect() const
{
auto url = (boost::format("%1%rr_disconnect")
% get_base_url()).str();
auto http = Http::get(std::move(url));
http.on_error([&](std::string body, std::string error, unsigned status) {
// we don't care about it, if disconnect is not working Duet will disconnect automatically after some time
BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error disconnecting: %1%, HTTP %2%, body: `%3%`") % error % status % body;
})
.perform_sync();
}
std::string Duet::get_upload_url(const std::string &filename) const
{
return (boost::format("%1%rr_upload?name=0:/gcodes/%2%&%3%")
% get_base_url()
% filename
% timestamp_str()).str();
}
std::string Duet::get_connect_url() const
{
return (boost::format("%1%rr_connect?password=%2%&%3%")
% get_base_url()
% (password.empty() ? "reprap" : password)
% timestamp_str()).str();
}
std::string Duet::get_base_url() const
{
if (host.find("http://") == 0 || host.find("https://") == 0) {
if (host.back() == '/') {
return host;
} else {
return (boost::format("%1%/") % host).str();
}
} else {
return (boost::format("http://%1%/") % host).str();
}
}
std::string Duet::timestamp_str() const
{
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::stringstream ss;
ss << "time=" << std::put_time(&tm, "%Y-%d-%mT%H:%M:%S");
return ss.str();
}
wxString Duet::format_error(const std::string &body, const std::string &error, unsigned status)
{
if (status != 0) {
auto wxbody = wxString::FromUTF8(body.data());
return wxString::Format("HTTP %u: %s", status, wxbody);
} else {
return wxString::FromUTF8(error.data());
}
}
bool Duet::start_print(wxString &msg, const std::string &filename) const {
bool res = false;
auto url = (boost::format("%1%rr_gcode?gcode=M32%%20\"%2%\"")
% get_base_url()
% filename).str();
auto http = Http::get(std::move(url));
http.on_error([&](std::string body, std::string error, unsigned status) {
BOOST_LOG_TRIVIAL(error) << boost::format("Duet: Error starting print: %1%, HTTP %2%, body: `%3%`") % error % status % body;
msg = format_error(body, error, status);
})
.on_complete([&](std::string body, unsigned) {
BOOST_LOG_TRIVIAL(debug) << boost::format("Duet: Got: %1%") % body;
res = true;
})
.perform_sync();
return res;
}
int Duet::get_err_code_from_body(const std::string &body) const
{
pt::ptree root;
std::istringstream iss (body); // wrap returned json to istringstream
pt::read_json(iss, root);
return root.get<int>("err", 0);
}
}

View file

@ -0,0 +1,46 @@
#ifndef slic3r_Duet_hpp_
#define slic3r_Duet_hpp_
#include <string>
#include <wx/string.h>
#include "PrintHost.hpp"
namespace Slic3r {
class DynamicPrintConfig;
class Http;
class Duet : public PrintHost
{
public:
Duet(DynamicPrintConfig *config);
bool test(wxString &curl_msg) const;
wxString get_test_ok_msg () const;
wxString get_test_failed_msg (wxString &msg) const;
// Send gcode file to duet, filename is expected to be in UTF-8
bool send_gcode(const std::string &filename) const;
bool have_auto_discovery() const;
bool can_test() const;
private:
std::string host;
std::string password;
std::string get_upload_url(const std::string &filename) const;
std::string get_connect_url() const;
std::string get_base_url() const;
std::string timestamp_str() const;
bool connect(wxString &msg) const;
void disconnect() const;
bool start_print(wxString &msg, const std::string &filename) const;
int get_err_code_from_body(const std::string &body) const;
static wxString format_error(const std::string &body, const std::string &error, unsigned status);
};
}
#endif

View file

@ -4,6 +4,7 @@
#include <functional>
#include <thread>
#include <deque>
#include <sstream>
#include <boost/filesystem/fstream.hpp>
#include <boost/format.hpp>
@ -42,6 +43,7 @@ struct Http::priv
// Used for storing file streams added as multipart form parts
// Using a deque here because unlike vector it doesn't ivalidate pointers on insertion
std::deque<fs::ifstream> form_files;
std::string postfields;
size_t limit;
bool cancel;
@ -60,6 +62,7 @@ struct Http::priv
static size_t form_file_read_cb(char *buffer, size_t size, size_t nitems, void *userp);
void form_add_file(const char *name, const fs::path &path, const char* filename);
void postfield_add_file(const fs::path &path);
std::string curl_error(CURLcode curlcode);
std::string body_size_error();
@ -187,6 +190,16 @@ void Http::priv::form_add_file(const char *name, const fs::path &path, const cha
}
}
void Http::priv::postfield_add_file(const fs::path &path)
{
std::ifstream f (path.string());
std::string file_content { std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>() };
if (!postfields.empty()) {
postfields += "&";
}
postfields += file_content;
}
std::string Http::priv::curl_error(CURLcode curlcode)
{
return (boost::format("%1% (%2%)")
@ -229,6 +242,11 @@ void Http::priv::http_perform()
::curl_easy_setopt(curl, CURLOPT_HTTPPOST, form);
}
if (!postfields.empty()) {
::curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postfields.c_str());
::curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, postfields.size());
}
CURLcode res = ::curl_easy_perform(curl);
if (res != CURLE_OK) {
@ -338,6 +356,12 @@ Http& Http::form_add_file(const std::string &name, const fs::path &path, const s
return *this;
}
Http& Http::postfield_add_file(const fs::path &path)
{
if (p) { p->postfield_add_file(path);}
return *this;
}
Http& Http::on_complete(CompleteFn fn)
{
if (p) { p->completefn = std::move(fn); }

View file

@ -73,6 +73,9 @@ public:
// Same as above except also override the file's filename with a custom one
Http& form_add_file(const std::string &name, const boost::filesystem::path &path, const std::string &filename);
// Add the file as POSTFIELD to the request, this can be used for hosts which do not support multipart requests
Http& postfield_add_file(const boost::filesystem::path &path);
// Callback called on HTTP request complete
Http& on_complete(CompleteFn fn);
// Callback called on an error occuring at any stage of the requests: Url parsing, DNS lookup,

View file

@ -1,21 +1,11 @@
#include "OctoPrint.hpp"
#include "PrintHostSendDialog.hpp"
#include <algorithm>
#include <boost/filesystem/path.hpp>
#include <boost/format.hpp>
#include <boost/log/trivial.hpp>
#include <wx/frame.h>
#include <wx/event.h>
#include <wx/progdlg.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "libslic3r/PrintConfig.hpp"
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/MsgDialog.hpp"
#include "Http.hpp"
namespace fs = boost::filesystem;
@ -23,47 +13,10 @@ namespace fs = boost::filesystem;
namespace Slic3r {
struct SendDialog : public GUI::MsgDialog
{
wxTextCtrl *txt_filename;
wxCheckBox *box_print;
SendDialog(const fs::path &path) :
MsgDialog(nullptr, _(L("Send G-Code to printer")), _(L("Upload to OctoPrint with the following filename:")), wxID_NONE),
txt_filename(new wxTextCtrl(this, wxID_ANY, path.filename().wstring())),
box_print(new wxCheckBox(this, wxID_ANY, _(L("Start printing after upload"))))
{
auto *label_dir_hint = new wxStaticText(this, wxID_ANY, _(L("Use forward slashes ( / ) as a directory separator if needed.")));
label_dir_hint->Wrap(CONTENT_WIDTH);
content_sizer->Add(txt_filename, 0, wxEXPAND);
content_sizer->Add(label_dir_hint);
content_sizer->AddSpacer(VERT_SPACING);
content_sizer->Add(box_print, 0, wxBOTTOM, 2*VERT_SPACING);
btn_sizer->Add(CreateStdDialogButtonSizer(wxOK | wxCANCEL));
txt_filename->SetFocus();
wxString stem(path.stem().wstring());
txt_filename->SetSelection(0, stem.Length());
Fit();
}
fs::path filename() const {
return fs::path(txt_filename->GetValue().wx_str());
}
bool print() const { return box_print->GetValue(); }
};
OctoPrint::OctoPrint(DynamicPrintConfig *config) :
host(config->opt_string("octoprint_host")),
apikey(config->opt_string("octoprint_apikey")),
cafile(config->opt_string("octoprint_cafile"))
host(config->opt_string("print_host")),
apikey(config->opt_string("printhost_apikey")),
cafile(config->opt_string("printhost_cafile"))
{}
bool OctoPrint::test(wxString &msg) const
@ -91,6 +44,17 @@ bool OctoPrint::test(wxString &msg) const
return res;
}
wxString OctoPrint::get_test_ok_msg () const
{
return wxString::Format("%s", _(L("Connection to OctoPrint works correctly.")));
}
wxString OctoPrint::get_test_failed_msg (wxString &msg) const
{
return wxString::Format("%s: %s\n\n%s",
_(L("Could not connect to OctoPrint")), msg, _(L("Note: OctoPrint version at least 1.1.0 is required.")));
}
bool OctoPrint::send_gcode(const std::string &filename) const
{
enum { PROGRESS_RANGE = 1000 };
@ -98,7 +62,7 @@ bool OctoPrint::send_gcode(const std::string &filename) const
const auto errortitle = _(L("Error while uploading to the OctoPrint server"));
fs::path filepath(filename);
SendDialog send_dialog(filepath.filename());
PrintHostSendDialog send_dialog(filepath.filename(), true);
if (send_dialog.ShowModal() != wxID_OK) { return false; }
const bool print = send_dialog.print();
@ -161,6 +125,16 @@ bool OctoPrint::send_gcode(const std::string &filename) const
return res;
}
bool OctoPrint::have_auto_discovery() const
{
return true;
}
bool OctoPrint::can_test() const
{
return true;
}
void OctoPrint::set_auth(Http &http) const
{
http.header("X-Api-Key", apikey);

View file

@ -4,6 +4,8 @@
#include <string>
#include <wx/string.h>
#include "PrintHost.hpp"
namespace Slic3r {
@ -11,14 +13,18 @@ namespace Slic3r {
class DynamicPrintConfig;
class Http;
class OctoPrint
class OctoPrint : public PrintHost
{
public:
OctoPrint(DynamicPrintConfig *config);
bool test(wxString &curl_msg) const;
wxString get_test_ok_msg () const;
wxString get_test_failed_msg (wxString &msg) const;
// Send gcode file to octoprint, filename is expected to be in UTF-8
bool send_gcode(const std::string &filename) const;
bool have_auto_discovery() const;
bool can_test() const;
private:
std::string host;
std::string apikey;

View file

@ -0,0 +1,31 @@
#ifndef slic3r_PrintHost_hpp_
#define slic3r_PrintHost_hpp_
#include <string>
#include <wx/string.h>
namespace Slic3r {
class DynamicPrintConfig;
class PrintHost
{
public:
virtual bool test(wxString &curl_msg) const = 0;
virtual wxString get_test_ok_msg () const = 0;
virtual wxString get_test_failed_msg (wxString &msg) const = 0;
// Send gcode file to print host, filename is expected to be in UTF-8
virtual bool send_gcode(const std::string &filename) const = 0;
virtual bool have_auto_discovery() const = 0;
virtual bool can_test() const = 0;
};
}
#endif

View file

@ -0,0 +1,21 @@
#include "PrintHostFactory.hpp"
#include "OctoPrint.hpp"
#include "Duet.hpp"
#include "libslic3r/PrintConfig.hpp"
namespace Slic3r {
PrintHost * PrintHostFactory::get_print_host(DynamicPrintConfig *config)
{
PrintHostType kind = config->option<ConfigOptionEnum<PrintHostType>>("host_type")->value;
if (kind == htOctoPrint) {
return new OctoPrint(config);
} else if (kind == htDuet) {
return new Duet(config);
}
return NULL;
}
}

View file

@ -0,0 +1,24 @@
#ifndef slic3r_PrintHostFactory_hpp_
#define slic3r_PrintHostFactory_hpp_
#include <string>
#include <wx/string.h>
namespace Slic3r {
class DynamicPrintConfig;
class PrintHost;
class PrintHostFactory
{
public:
PrintHostFactory() {};
~PrintHostFactory() {};
static PrintHost * get_print_host(DynamicPrintConfig *config);
};
}
#endif

View file

@ -0,0 +1,54 @@
#include "PrintHostSendDialog.hpp"
#include <wx/frame.h>
#include <wx/event.h>
#include <wx/progdlg.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/MsgDialog.hpp"
namespace fs = boost::filesystem;
namespace Slic3r {
PrintHostSendDialog::PrintHostSendDialog(const fs::path &path, bool can_start_print) :
MsgDialog(nullptr, _(L("Send G-Code to printer host")), _(L("Upload to Printer Host with the following filename:")), wxID_NONE),
txt_filename(new wxTextCtrl(this, wxID_ANY, path.filename().wstring())),
box_print(new wxCheckBox(this, wxID_ANY, _(L("Start printing after upload")))),
can_start_print(can_start_print)
{
auto *label_dir_hint = new wxStaticText(this, wxID_ANY, _(L("Use forward slashes ( / ) as a directory separator if needed.")));
label_dir_hint->Wrap(CONTENT_WIDTH);
content_sizer->Add(txt_filename, 0, wxEXPAND);
content_sizer->Add(label_dir_hint);
content_sizer->AddSpacer(VERT_SPACING);
content_sizer->Add(box_print, 0, wxBOTTOM, 2*VERT_SPACING);
btn_sizer->Add(CreateStdDialogButtonSizer(wxOK | wxCANCEL));
txt_filename->SetFocus();
wxString stem(path.stem().wstring());
txt_filename->SetSelection(0, stem.Length());
if (!can_start_print) {
box_print->Disable();
}
Fit();
}
fs::path PrintHostSendDialog::filename() const
{
return fs::path(txt_filename->GetValue().wx_str());
}
bool PrintHostSendDialog::print() const
{
return box_print->GetValue(); }
}

View file

@ -0,0 +1,40 @@
#ifndef slic3r_PrintHostSendDialog_hpp_
#define slic3r_PrintHostSendDialog_hpp_
#include <string>
#include <boost/filesystem/path.hpp>
#include <wx/string.h>
#include <wx/frame.h>
#include <wx/event.h>
#include <wx/progdlg.h>
#include <wx/sizer.h>
#include <wx/stattext.h>
#include <wx/textctrl.h>
#include <wx/checkbox.h>
#include "slic3r/GUI/GUI.hpp"
#include "slic3r/GUI/MsgDialog.hpp"
namespace Slic3r {
class PrintHostSendDialog : public GUI::MsgDialog
{
private:
wxTextCtrl *txt_filename;
wxCheckBox *box_print;
bool can_start_print;
public:
PrintHostSendDialog(const boost::filesystem::path &path, bool can_start_print);
boost::filesystem::path filename() const;
bool print() const;
};
}
#endif