-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathSendToPrinter.cpp
More file actions
1741 lines (1456 loc) · 66.7 KB
/
SendToPrinter.cpp
File metadata and controls
1741 lines (1456 loc) · 66.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "SendToPrinter.hpp"
#include "slic3r/GUI/I18N.hpp"
#include "slic3r/GUI/wxExtensions.hpp"
#include "slic3r/GUI/GUI_App.hpp"
#include "slic3r/GUI/MainFrame.hpp"
#include "libslic3r_version.h"
#include <regex>
#include <string>
#include <wx/sizer.h>
#include <wx/string.h>
#include <wx/toolbar.h>
#include <wx/textdlg.h>
#include <locale>
#include <codecvt>
#include <slic3r/GUI/Widgets/WebView.hpp>
#include <wx/webview.h>
#include "slic3r/GUI/print_manage/RemotePrinterManager.hpp"
#include <boost/beast/core/detail/base64.hpp>
#include <wx/stdpaths.h>
#include "slic3r/GUI/print_manage/utils/cxmdns.h"
#include "slic3r/GUI/print_manage/Utils.hpp"
#include "wx/event.h"
#include "slic3r/GUI/Plater.hpp"
#include "slic3r/GUI/PartPlate.hpp"
#include "slic3r/GUI/AnalyticsDataUploadManager.hpp"
#include "libslic3r/Print.hpp"
#include <wx/variant.h>
#include <wx/datstrm.h>
#include "../data/DataCenter.hpp"
#include "../AppMgr.hpp"
#include "../AppUtils.hpp"
#include "slic3r/GUI/Notebook.hpp"
#include "cereal/external/base64.hpp"
#include "libslic3r/Time.hpp"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#if defined(__linux__) || defined(__LINUX__)
#include "video/WebRTCDecoder.h"
#endif
#include "libslic3r/common_header/common_header.h"
namespace Slic3r {
namespace GUI {
namespace pt = boost::property_tree;
CxSentToPrinterDialog::CxSentToPrinterDialog(Plater *plater,
SendType sendtype,std::string mapString)
: DPIDialog(wxGetApp().mainframe,
wxID_ANY,
_L("Send to Lan Printer"),
wxDefaultPosition,
wxDefaultSize,
wxCAPTION | wxCLOSE_BOX | wxRESIZE_BORDER), m_sendtype(sendtype),m_mapString(mapString)
, m_plater(plater)
{
#ifdef __WINDOWS__
SetDoubleBuffered(true);
#endif //__WINDOWS__
wxGetApp().UpdateDlgDarkUI(this);
wxSize minSize = wxSize(FromDIP(1170), FromDIP(500)); // 设置最小尺寸
wxSize initialSize = wxSize(FromDIP(1170), FromDIP(650));
SetMinSize(minSize);
SetSize(initialSize);
// 将窗体移动到屏幕顶部
Bind(wxEVT_SHOW, [this](wxShowEvent& event) {
if (event.IsShown()) {
wxPoint position = GetPosition();
if (position.y < 0)
{
wxSize newSize = wxSize(FromDIP(1170), FromDIP(650) + position.y);
SetSize(newSize);
SetPosition(wxPoint(position.x, 0));
}
}
event.Skip();
});
//SetBackgroundColour(m_colour_def_color);
// icon
std::string icon_path = (boost::format("%1%/images/%2%.ico") % resources_dir() % Slic3r::CxBuildInfo::getIconName()).str();
SetIcon(wxIcon(encode_path(icon_path.c_str()), wxBITMAP_TYPE_ICO));
wxBoxSizer* topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->SetMinSize(FromDIP(1170), FromDIP(600));
// Create the webview
m_browser = WebView::CreateWebView(this, "");
if (m_browser == nullptr) {
wxLogError("Could not init m_browser");
return;
}
bind_events();
SetSizer(topsizer);
topsizer->Add(m_browser, 1, wxEXPAND | wxALL, 0);
std::string version = std::string(CREALITYPRINT_VERSION);
std::string os = wxGetOsDescription().ToStdString();
int port = wxGetApp().get_server_port();
//#define _DEBUG1
#ifdef _DEBUG1
wxString url = wxString::Format("http://localhost:5174/?version=%s&port=%d&sendtype=%d&map=%s&os=%s", version, port,(int)m_sendtype,m_mapString, os);
this->load_url(url, wxString());
m_browser->EnableAccessToDevTools();
#else
// wxString url = wxString::Format("file://%s/web/sendToPrinterPage/index.html", from_u8(resources_dir()));
// this->load_url(wxString(url), wxString());
wxString url = wxString::Format("%s/web/sendToPrinterPage/index.html?version=%s&port=%d&sendtype=%d&os=%s", from_u8(resources_dir()),version, port,(int)m_sendtype, os);
url.Replace(wxT("\\"), wxT("/"));
url.Replace(wxT("#"), wxT("%23"));
wxURI uri(url);
wxString encodedUrl = uri.BuildURI();
encodedUrl = wxT("file://")+encodedUrl;
//encodedUrl = "http://localhost:5173/";
this->load_url(encodedUrl, wxString());
m_browser->EnableAccessToDevTools();
#endif
if (m_plater)
{
update_send_page_content();
}
wxGetApp().mainframe->get_printer_mgr_view()->RequestDeviceListFromDB();
if (wxGetApp().mainframe && wxGetApp().mainframe->get_printer_mgr_view()) {
wxGetApp().mainframe->get_printer_mgr_view()->RegisterHandler("receive_color_match_info",
[this](const nlohmann::json& json_data) {
this->handle_receive_color_match_info(json_data);
});
}
CenterOnParent();
DM::AppMgr::Ins().Register(m_browser);
}
CxSentToPrinterDialog::~CxSentToPrinterDialog()
{
DM::AppMgr::Ins().UnRegister(m_browser);
restore_extruder_colors();
UnregisterHandler("register_complete");
UnregisterHandler("send_gcode");
UnregisterHandler("send_3mf");
UnregisterHandler("cancel_send");
UnregisterHandler("request_color_match_info");
UnregisterHandler("send_start_print_cmd");
UnregisterHandler("request_update_plate_thumbnail");
UnregisterHandler("forward_device_detail");
UnregisterHandler("get_lang");
UnregisterHandler("get_devices");
UnregisterHandler("get_user");
UnregisterHandler("is_dark_theme");
UnregisterHandler("get_threeMF");
UnregisterHandler("get_machine_list");
UnregisterHandler("get_webrtc_local_param");
}
void CxSentToPrinterDialog::OnCloseWindow(wxCloseEvent& event)
{
// need to reopen the detail-page Video when close the send page
wxGetApp().mainframe->get_printer_mgr_view()->request_reopen_detail_video();
if(m_uploadingIp!=wxEmptyString)
RemotePrint::RemotePrinterManager::getInstance().cancelUpload(m_uploadingIp.ToStdString());
while (m_uploadingIp!=wxEmptyString)
{
wxMilliSleep(100);
}
event.Skip();
}
void CxSentToPrinterDialog::bind_events()
{
Bind(wxEVT_CLOSE_WINDOW, &CxSentToPrinterDialog::OnCloseWindow, this);
if(m_browser)
{
m_browser->Bind(wxEVT_WEBVIEW_ERROR, &CxSentToPrinterDialog::OnError, this);
m_browser->Bind(wxEVT_WEBVIEW_LOADED, &CxSentToPrinterDialog::OnLoaded, this);
Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, &CxSentToPrinterDialog::OnScriptMessage, this, m_browser->GetId());
}
RegisterHandler("register_complete", [this](const nlohmann::json& json_data) {
this->handle_register_complete(json_data);
});
RegisterHandler("send_gcode", [this](const nlohmann::json& json_data) {
this->handle_send_gcode(json_data);
});
RegisterHandler("send_3mf", [this](const nlohmann::json& json_data) {
this->handle_send_3mf(json_data);
});
RegisterHandler("cancel_send", [this](const nlohmann::json& json_data) {
this->handle_cancel_send(json_data);
});
RegisterHandler("request_color_match_info", [this](const nlohmann::json& json_data) {
this->handle_request_color_match_info(json_data);
});
RegisterHandler("send_start_print_cmd", [this](const nlohmann::json& json_data) {
this->handle_send_start_print_cmd(json_data);
});
RegisterHandler("start_heartbeat_cmd", [this](const nlohmann::json& json_data) {
this->handle_start_heartbeat_cmd(json_data);
});
RegisterHandler("stop_heartbeat_cmd", [this](const nlohmann::json& json_data) {
this->handle_stop_heartbeat_cmd(json_data);
});
RegisterHandler("set_error_cmd", [this](const nlohmann::json& json_data) { this->handle_set_error_cmd(json_data); });
RegisterHandler("request_update_plate_thumbnail", [this](const nlohmann::json& json_data) {
this->handle_request_update_plate_thumbnail(json_data);
});
RegisterHandler("get_lang", [this](const nlohmann::json& json_data) {
wxString lan = wxGetApp().app_config->get("language");
nlohmann::json commandJson;
commandJson["command"] = "get_lang";
commandJson["data"] = lan.ToStdString();
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump()));
run_script(strJS.ToStdString());
});
RegisterHandler("get_devices", [this](const nlohmann::json& json_data) {
nlohmann::json commandJson;
commandJson["command"] = "get_devices";
commandJson["data"] = DM::DataCenter::Ins().GetData();
std::string commandStr = commandJson.dump(-1,' ',true);
// wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandStr));
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", commandStr);
run_script(strJS.ToUTF8().data());
});
RegisterHandler("get_user", [this](const nlohmann::json& json_data) {
auto user = wxGetApp().get_user();
std::string country_code = wxGetApp().app_config->get("region");
nlohmann::json top_level_json = {
{"bLogin", user.bLogin ? 1 : 0},
{"token", user.token},
{"userId", user.userId},
{"region", country_code},
};
nlohmann::json commandJson = {
{"command", "get_user"},
{"data", top_level_json.dump()}
};
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump()));
run_script(strJS.ToStdString());
});
RegisterHandler("is_dark_theme", [this](const nlohmann::json& json_data) {
wxString lan = wxGetApp().current_language_code_safe();
nlohmann::json commandJson;
commandJson["command"] = "is_dark_theme";
commandJson["data"] = wxGetApp().dark_mode();
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump()));
run_script(strJS.ToStdString());
});
RegisterHandler("get_threeMF", [this](const nlohmann::json& json_data) {
wxString project_name = Slic3r::GUI::wxGetApp().plater()->get_project_name();
boost::property_tree::wptree req;
req.put(L"command", L"get_threeMF");
boost::property_tree::wptree item;
item.put(L"project_name", project_name);
req.put_child(L"data", item);
std::wostringstream oss;
pt::write_json(oss, req, false);
WebView::RunScript(m_browser, wxString::Format("window.handleStudioCmd(%s)", oss.str()));
});
RegisterHandler("get_machine_list", [this](const nlohmann::json& json_data) {
load_machine_preset_data();
});
RegisterHandler("get_webrtc_local_param", [this](const nlohmann::json& json_data) {
this->handle_get_webrtc_local_param(json_data);
});
}
void CxSentToPrinterDialog::RegisterHandler(const std::string& command, std::function<void(const nlohmann::json&)> handler)
{
m_commandHandlers[command] = handler;
}
void CxSentToPrinterDialog::UnregisterHandler(const std::string& command)
{
m_commandHandlers.erase(command);
}
void CxSentToPrinterDialog::OnScriptMessage(wxWebViewEvent& evt)
{
try {
std::string strInput = evt.GetString().ToStdString();
BOOST_LOG_TRIVIAL(trace) << "DeviceDialog::OnScriptMessage;OnRecv:" << strInput.c_str();
json j = json::parse(strInput);
std::string strCmd = j["command"];
BOOST_LOG_TRIVIAL(trace) << "DeviceDialog::OnScriptMessage;Command:" << strCmd;
if(strCmd == "forward_device_detail"){
wxPostEvent(this, wxCloseEvent(wxEVT_CLOSE_WINDOW));
}else if(strCmd == "switch_webrtc_source")
{
#if defined(__linux__) || defined(__LINUX__)
std::string ip = j["ip"];
std::string video_url = (boost::format("http://%1%:8000/call/webrtc_local") % ip).str();
WebRTCDecoder::GetInstance()->startPlay(video_url);
#endif
} else if (strCmd == "common_openurl") {
wxLaunchDefaultBrowser(j["url"]);
wxPostEvent(this, wxCloseEvent(wxEVT_CLOSE_WINDOW));
}
if (DM::AppMgr::Ins().Invoke(m_browser, evt.GetString().ToUTF8().data()))
{
return;
}
if (m_commandHandlers.find(strCmd) != m_commandHandlers.end()) {
m_commandHandlers[strCmd](j);
} else {
BOOST_LOG_TRIVIAL(trace) << "CxSentToPrinterDialog::OnScriptMessage;Unknown Command:" << strCmd;
}
} catch (std::exception &e) {
// wxMessageBox(e.what(), "json Exception", MB_OK);
BOOST_LOG_TRIVIAL(trace) << "DeviceDialog::OnScriptMessage;Error:" << e.what();
}
}
/**
* Handle the "request_color_match_info" command from the sendPage browser,
* and then send the request to the printerMgrView
*/
void CxSentToPrinterDialog::handle_request_color_match_info(const nlohmann::json& json_data)
{
m_request_color_match_plateIndex = json_data["plateIndex"];
wxString ipAddress = json_data["ipAddress"];
wxGetApp().mainframe->get_printer_mgr_view()->ExecuteScriptCommand(build_match_color_cmd_info(m_request_color_match_plateIndex, ipAddress.ToStdString()));
}
/**
* Handle the "send_start_print_cmd" command from the sendPage browser,
* and then send the request to the printerMgrView
*/
void CxSentToPrinterDialog::handle_send_start_print_cmd(const nlohmann::json& json_data)
{
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "send_print_cmd";
commandJson["data"] = json_data["data"].dump(-1, ' ', true);
wxGetApp().mainframe->get_printer_mgr_view()->ExecuteScriptCommand(RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
}
void CxSentToPrinterDialog::handle_set_error_cmd(const nlohmann::json& json_data)
{
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "set_error_cmd";
commandJson["data"] = json_data["data"].dump();
wxGetApp().mainframe->get_printer_mgr_view()->ExecuteScriptCommand(RemotePrint::Utils::url_encode(commandJson.dump()));
}
void CxSentToPrinterDialog::post_notify_event(const std::vector<int>& plate_extruders, const std::vector<std::string>& extruder_match_colors, bool bUpdateSelf)
{
wxVariantList str_variantList;
for (const auto& str : extruder_match_colors) {
str_variantList.Append(new wxVariant(str));
}
wxVariant str_variant(str_variantList);
wxVariantList int_variantList;
for (const auto& i : plate_extruders) {
int_variantList.Append(new wxVariant(i));
}
wxVariant int_variant(int_variantList);
wxVariantList variantList;
variantList.Append(&str_variant);
variantList.Append(&int_variant);
wxCommandEvent notifyEvent(EVT_NOTIFY_PLATE_THUMBNAIL_UPDATE);
notifyEvent.SetClientData(new wxVariant(variantList));
//wxPostEvent(wxGetApp().plater(), notifyEvent);
wxGetApp().plater()->update_plate_thumbnail(notifyEvent);//Optimize this code in the future
if(bUpdateSelf)
update_plate_preview_img_on_send_page();
}
// void CxSentToPrinterDialog::handle_request_update_plate_thumbnail(const nlohmann::json& json_data)
// {
// std::vector<int> plate_extruders;
// std::vector<std::string> extruder_match_colors;
// m_request_color_match_plateIndex = json_data["plateIndex"];
// int extruderId = json_data["extruderId"];
// plate_extruders.emplace_back(extruderId);
// wxString matchColor = json_data["matchColor"];
// extruder_match_colors.emplace_back(matchColor.ToStdString());
// post_notify_event(plate_extruders, extruder_match_colors);
// }
void CxSentToPrinterDialog::handle_request_update_plate_thumbnail(const nlohmann::json& json_data)
{
std::vector<int> plate_extruders;
std::vector<std::string> extruder_match_colors;
if (m_plater->model().objects.size() == 0)
return;
m_request_color_match_plateIndex = json_data["plateIndex"];
// 遍历 matchInfo 数组,解析 extruderId 和 matchColor
for (const auto& matchInfo : json_data["matchInfo"])
{
int extruderId = matchInfo["extruderId"];
std::string matchColor = matchInfo["matchColor"];
plate_extruders.emplace_back(extruderId);
extruder_match_colors.emplace_back(matchColor);
}
post_notify_event(plate_extruders, extruder_match_colors);
}
void CxSentToPrinterDialog::handle_get_webrtc_local_param(const nlohmann::json& json_data){
std::string url = json_data["url"].get<std::string>();
std::string sdp = json_data["sdp"].get<std::string>();
Slic3r::Http http = Slic3r::Http::post(url);
std::string localip = "";
try {
// 提取域名部分
std::string domain = DM::AppUtils::extractDomain(url);
// 创建一个 Boost.Asio 的 io_context 对象
boost::asio::io_context io_context;
// 创建一个 UDP 套接字
boost::asio::ip::udp::socket socket(io_context);
// 连接到一个公共的 UDP 地址和端口(Google 的公共 DNS 服务器)
socket.connect(boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string(domain), 80));
// 获取本地端点信息
boost::asio::ip::udp::endpoint local_endpoint = socket.local_endpoint();
// 关闭套接字
socket.close();
// 返回本地 IP 地址的字符串表示
localip = local_endpoint.address().to_string();
}
catch (const std::exception& e) {
// 若出现异常,输出错误信息并返回空字符串
std::cerr << "Error: " << e.what() << std::endl;
}
if (!localip.empty())
{
std::string mdns_addr = "";
std::vector<std::string> tokens;
boost::split(tokens, sdp, boost::is_any_of("\n"));
for (const auto& token : tokens) {
if (token.find("a=candidate") != std::string::npos) {
std::vector<std::string> sub_tokens;
boost::split(sub_tokens, token, boost::is_any_of(" "));
mdns_addr = sub_tokens[4];
break;
//sdp = sdp.replace("a=candidate", "a=candidate" + " " + "raddr=" + localip);
}
}
if (!mdns_addr.empty())
{
boost::algorithm::replace_first(sdp, mdns_addr, localip);
}
//sdp = sdp.replace("
}
nlohmann::json j;
j["type"] = "offer";
j["sdp"] = sdp;
std::string d = j.dump();
std::string e = cereal::base64::encode((unsigned char const*)d.c_str(), d.length());
http.header("Content-Type", "application/json")
.set_post_body(e)
.on_complete([&](std::string body, unsigned status) {
if (status != 200) {
return;
}
nlohmann::json data;
data["body"] = body;
data["ret"] = true;
nlohmann::json commandJson;
commandJson["command"] = "get_webrtc_local_param";
commandJson["data"] = data;
// AppUtils::PostMsg(browse, wxString::Format("window.handleStudioCmd('%s');", commandJson.dump(-1, ' ', true)).ToStdString());
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", commandJson.dump(-1, ' ', true));
run_script(strJS.ToStdString());
})
.on_error([&](std::string body, std::string error, unsigned status) {
nlohmann::json data;
data["body"] = body;
data["ret"] = false;
nlohmann::json commandJson;
commandJson["command"] = "get_webrtc_local_param";
commandJson["data"] = data;
// AppUtils::PostMsg(browse,
// wxString::Format("window.handleStudioCmd('%s');", commandJson.dump(-1, ' ', true)).ToStdString());
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", commandJson.dump(-1, ' ', true));
run_script(strJS.ToStdString());
})
.perform_sync();
}
std::string CxSentToPrinterDialog::build_match_color_cmd_info(int plateIndex, const std::string& ipAddress)
{
PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_plate(plateIndex);
if(!plate)
return "";
if(m_backup_extruder_colors.size() <= 0) {
return "";
}
// get filament types
std::vector<std::string> filament_presets = wxGetApp().preset_bundle->filament_presets;
std::vector<std::string> filament_types;
if(m_plater->only_gcode_mode()) {
GCodeProcessorResult* current_result = m_plater->get_partplate_list().get_current_slice_result();
if(current_result) {
for (auto f_type : current_result->creality_extruder_types) {
filament_types.emplace_back(f_type);
}
}
}
else {
for (const auto& preset_name : filament_presets) {
std::string filament_type;
Slic3r::Preset* preset = wxGetApp().preset_bundle->filaments.find_preset(preset_name);
if (preset) {
preset->get_filament_type(filament_type);
filament_types.emplace_back(filament_type);
}
}
}
nlohmann::json plate_extruder_colors_json = nlohmann::json::array();
std::vector<int> plate_extruders = plate->get_used_extruders();
if(m_plater->only_gcode_mode()) {
plate_extruders = m_plater->get_gcode_extruders_in_only_gcode_mode();
}
if (plate_extruders.size() > 0) {
for (const auto& extruder : plate_extruders) {
if(m_backup_extruder_colors.size() > (extruder-1)) {
nlohmann::json extruder_info = {
{"extruder_id", extruder},
{"extruder_color", m_backup_extruder_colors[extruder - 1]},
{"filament_type", filament_types[extruder - 1]}
};
plate_extruder_colors_json.push_back(extruder_info);
}
}
}
// Create top-level JSON object
nlohmann::json top_level_json = {
{"printer_ip", ipAddress},
{"plate_extruder_colors", plate_extruder_colors_json}
};
// Create command JSON object
nlohmann::json commandJson = {
{"command", "req_match_color_info"},
{"data", top_level_json.dump()}
};
// Encode the command string
return RemotePrint::Utils::url_encode(commandJson.dump());
}
void CxSentToPrinterDialog::notify_update_plate_thumbnail_data(const nlohmann::json& json_data)
{
if (m_plater->model().objects.size() == 0)
return;
const auto& dataInfo = json_data["data"];
std::vector<int> plate_extruders;
std::vector<std::string> extruder_match_colors;
for (const auto& matchInfo : dataInfo) {
plate_extruders.emplace_back(matchInfo["extruderId"]);
extruder_match_colors.emplace_back(matchInfo["matchColor"]);
}
post_notify_event(plate_extruders, extruder_match_colors);
}
void CxSentToPrinterDialog::update_plate_preview_img_on_send_page()
{
std::string str_val = get_updated_plate_preview_img(m_request_color_match_plateIndex);
if(str_val.empty())
return;
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", str_val);
run_script(strJS.ToStdString());
}
/**
* Processes the received color match information from the printerMgrView
* and prepares it to be sent to the send page.
*/
void CxSentToPrinterDialog::handle_receive_color_match_info(const nlohmann::json& json_data)
{
notify_update_plate_thumbnail_data(json_data);
boost::property_tree::wptree req;
req.put(L"command", L"update_color_match_info");
req.put(L"data", from_u8(json_data["data"].dump()));
std::wostringstream oss;
pt::write_json(oss, req, false);
BOOST_LOG_TRIVIAL(warning) << oss.str();
WebView::RunScript(m_browser, wxString::Format("window.handleStudioCmd(%s)", oss.str()));
}
void CxSentToPrinterDialog::handle_send_3mf(const nlohmann::json& json_data)
{
if(!m_plater)
return;
int plateIndex = json_data["printPlateIndex"]; // which plate to print
wxString ipAddress = json_data["ipAddress"];
std::string upload3mfName = json_data["upload3mfName"];
std::string tmp_3mf_path = "";
if (m_plater->only_gcode_mode())
{
tmp_3mf_path = m_plater->get_last_loaded_3mf().string();
}
else
{
boost::filesystem::path temp_path(m_plater->model().get_backup_path("Metadata"));
temp_path /= (boost::format(".%1%.%2%_upload.3mf") % get_current_pid() % plateIndex).str();
tmp_3mf_path = temp_path.string();
int result = m_plater->export_3mf(tmp_3mf_path, SaveStrategy::UploadToPrinter);
if (result < 0) {
return;
}
}
if (tmp_3mf_path.empty())
return;
{
// upload analytics data here
auto device = DM::DataCenter::Ins().get_printer_data(ipAddress.ToStdString());
check_upload_analytics_data(device.mac);
}
m_uploadingIp = ipAddress;
RemotePrint::RemotePrinterManager::getInstance().pushUploadTasks(
ipAddress.ToStdString(), upload3mfName, tmp_3mf_path,
[this](std::string ip, float progress,double speed) {
nlohmann::json top_level_json;
top_level_json["printer_ip"] = ip;
top_level_json["progress"] = progress;
top_level_json["speed"] = speed;
std::string json_str = top_level_json.dump();
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "display_upload_progress";
commandJson["data"] = RemotePrint::Utils::url_encode(json_str);
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
}
catch (...)
{
}
});
},
[this](std::string ip, int statusCode) {
nlohmann::json top_level_json;
top_level_json["printer_ip"] = ip;
top_level_json["status_code"] = statusCode;
std::string json_str = top_level_json.dump();
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "notify_upload_status";
commandJson["data"] = RemotePrint::Utils::url_encode(json_str);
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
}
catch (...)
{
}
});
m_uploadingIp = wxEmptyString;
}, [this,tmp_3mf_path](std::string ip, std::string body) {
int statusCode = 1;
std::string status_msg = "";
json jBody = json::parse(body);
if (jBody.contains("code") && jBody["code"].is_number_integer()) {
statusCode = jBody["code"];
}
if(jBody.contains("message") && jBody["message"].is_string()) {
status_msg = jBody["message"];
}
nlohmann::json commandJson;
commandJson["command"] = "notify_send_complete";
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS,tmp_3mf_path, statusCode, status_msg]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
if(wxGetApp().is_privacy_checked()) {
json js;
js["type_code"] = "slice813";
js["client_id"] = wxGetApp().get_client_id();
js["file_format"] = "3mf";
std::uintmax_t size_bytes = 0;
size_bytes = boost::filesystem::file_size(tmp_3mf_path);
double size_mb = size_bytes / (1024.0 * 1024.0); // MB
std::ostringstream oss;
oss << std::fixed << std::setprecision(2) << size_mb;
js["file_size"] = oss.str();
js["status_code"] = statusCode;
js["message"] = status_msg;
js["operation_date"] = Slic3r::Utils::utc_timestamp(Slic3r::Utils::get_current_time_utc());
js["app_version"] = GUI_App::format_display_version().c_str();
wxGetApp().track_event("send_file_complete", js.dump());
}
}
catch (...)
{
}
});
m_uploadingIp = wxEmptyString;
});
}
void CxSentToPrinterDialog::handle_cancel_send(const nlohmann::json& json_data) {
int plateIndex = json_data["plateIndex"];
wxString ipAddress = json_data["ipAddress"];
RemotePrint::RemotePrinterManager::getInstance().cancelUpload(ipAddress.ToStdString());
}
void CxSentToPrinterDialog::handle_start_heartbeat_cmd(const nlohmann::json& json_data) {
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "start_heartbeat_cmd";
commandJson["data"] = json_data["data"].dump(-1, ' ', true);
wxGetApp().mainframe->get_printer_mgr_view()->ExecuteScriptCommand(RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
}
void CxSentToPrinterDialog::handle_stop_heartbeat_cmd(const nlohmann::json& json_data) {
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "stop_heartbeat_cmd";
commandJson["data"] = json_data["data"].dump(-1, ' ', true);
wxGetApp().mainframe->get_printer_mgr_view()->ExecuteScriptCommand(RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
}
void CxSentToPrinterDialog::handle_register_complete(const nlohmann::json& json_data)
{
if (m_plater) {
update_send_page_content();
}
}
void CxSentToPrinterDialog::handle_send_gcode(const nlohmann::json& json_data)
{
int plateIndex = json_data["plateIndex"];
wxString ipAddress = json_data["ipAddress"];
std::string uploadName = json_data["uploadName"]; // convert from wxString to std::string would cause exception
bool oldPrinter = json_data["oldPrinter"];
int moonrakerPort = json_data["moonrakerPort"];
if (oldPrinter)
{
std::string strIpAddr = ipAddress.ToStdString();
RemotePrint::RemotePrinterManager::getInstance().setOldPrinterMap(strIpAddr);
}
if (moonrakerPort > 0)
{
std::string strIpAddr = ipAddress.ToStdString();
if (strIpAddr.find('(') != std::string::npos)
{
RemotePrint::RemotePrinterManager::getInstance().setKlipperPrinterMap(strIpAddr, moonrakerPort);
}
}
PartPlate* plate = wxGetApp().plater()->get_partplate_list().get_plate(plateIndex);
if (plate) {
{
// upload analytics data here
auto device = DM::DataCenter::Ins().get_printer_data(ipAddress.ToStdString());
AnalyticsDataUploadManager::getInstance().triggerUploadTasks(AnalyticsUploadTiming::ON_CLICK_START_PRINT_CMD,
{AnalyticsDataEventType::ANALYTICS_GLOBAL_PRINT_PARAMS,
AnalyticsDataEventType::ANALYTICS_OBJECT_PRINT_PARAMS}, plateIndex,device.mac);
}
std::string gcodeFilePath;
if (m_plater->only_gcode_mode()) {
GCodeProcessorResult* plate_gcode_result = plate->get_slice_result();
if (plate_gcode_result)
{
gcodeFilePath = plate_gcode_result->filename;
}
if (gcodeFilePath.empty())
return;
}
else{
gcodeFilePath = _L(plate->get_tmp_gcode_path()).ToUTF8();
}
m_uploadingIp = ipAddress;
RemotePrint::RemotePrinterManager::getInstance().pushUploadTasks(
ipAddress.ToStdString(), uploadName, gcodeFilePath,
[this](std::string ip, float progress,double speed) {
nlohmann::json top_level_json;
top_level_json["printer_ip"] = ip;
top_level_json["progress"] = progress;
top_level_json["speed"] = round(speed);
std::string json_str = top_level_json.dump();
// create command to send to the webview
nlohmann::json commandJson;
commandJson["command"] = "display_upload_progress";
commandJson["data"] = RemotePrint::Utils::url_encode(json_str);
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
}
catch (...)
{
}
});
},
[this](std::string ip, int statusCode) {
nlohmann::json top_level_json;
top_level_json["status_code"] = statusCode;
std::string json_str = top_level_json.dump();
nlohmann::json commandJson;
commandJson["command"] = "notify_upload_status";
commandJson["data"] = RemotePrint::Utils::url_encode(json_str);
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
}
catch (...)
{
}
});
m_uploadingIp = wxEmptyString;
},
[this, gcodeFilePath](std::string ip, std::string body){
int deviceType = 0;//local device
int statusCode = 1;
std::string status_msg = "";
json jBody = json::parse(body);
if (jBody.contains("code") && jBody["code"].is_number_integer()) {
statusCode = jBody["code"];
}
if(jBody.contains("message") && jBody["message"].is_string()) {
status_msg = jBody["message"];
}
nlohmann::json top_level_json;
top_level_json["status_code"] = statusCode;
top_level_json["id"] = "";
top_level_json["name"] = "";
top_level_json["type"] = "";
top_level_json["filekey"] = "";
if(jBody.contains("result") && jBody["result"].contains("list") &&jBody["result"]["list"].size()>=0){
deviceType = 1;//CX device
if(jBody["result"]["list"][0].contains("id"))top_level_json["id"]=jBody["result"]["list"][0]["id"];
if(jBody["result"]["list"][0].contains("name"))top_level_json["name"]=jBody["result"]["list"][0]["name"];
if(jBody["result"]["list"][0].contains("type"))top_level_json["type"]=jBody["result"]["list"][0]["type"];
if(jBody["result"]["list"][0].contains("filekey"))top_level_json["filekey"]=jBody["result"]["list"][0]["filekey"];
}
std::string json_str;
if(1 == deviceType)
{ json_str = top_level_json.dump(-1, ' ', true);}
nlohmann::json commandJson;
commandJson["command"] = "notify_send_complete";
commandJson["data"] = RemotePrint::Utils::url_encode(json_str);
wxString strJS = wxString::Format("window.handleStudioCmd('%s');", RemotePrint::Utils::url_encode(commandJson.dump(-1, ' ', true)));
wxTheApp->CallAfter([this, strJS, statusCode, status_msg, gcodeFilePath]() {
try
{
if (!m_browser->IsBusy()) {
run_script(strJS.ToStdString());
}
if(wxGetApp().is_privacy_checked()) {
json js;
js["type_code"] = "slice813";
js["client_id"] = wxGetApp().get_client_id();
js["file_format"] = "gcode";