-
Notifications
You must be signed in to change notification settings - Fork 6
/
NewFrame.cpp
1876 lines (1745 loc) · 66.1 KB
/
NewFrame.cpp
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 "NewFrame.h"
#include <wx/intl.h>
#include <wx/tokenzr.h>
#include <wx/file.h>
#include <wx/process.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include <wx/fileconf.h>
#include <wx/dir.h>
#include <wx/filefn.h>
#include <wx/process.h>
#include <wx/artprov.h>
#include <wx/arrstr.h>
#ifndef __WINDOWS__
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#endif
#include <stdlib.h>
#include <exception>
#include "MyThread.h"
#include "ping.h"
#include "settings.h"
#include "SettingsDialog.h"
#define RECV_BUFFER_LENGTH 1290
wxDatagramSocket *sock;
wxIPV4address *addrPeer;
uint8_t receivedBuf[RECV_BUFFER_LENGTH];
wxUint32 numRead = -1;
bool isRunning = false;
DisplayProcess* m_running;
DEFINE_EVENT_TYPE(wxEVT_READTHREAD)
MyThread::MyThread(wxEvtHandler* pParent) : wxThread(wxTHREAD_DETACHED), m_pParent(pParent)
{
//pass parameters into the thread
//addrLocal1
//m_param = param;
//sock.SetRefData(s);
}
void* MyThread::Entry()
{
try
{
wxCommandEvent evt(wxEVT_READTHREAD, GetId());
//can be used to set some identifier for the data
memset(&receivedBuf[0], 0, sizeof(receivedBuf));
isRunning = true;
//if (sock->IsConnected())
//{
if (sock->IsOk())
{
sock->SetTimeout((long)(replyTimeout / 1000)+1);
sock->RecvFrom(*addrPeer, receivedBuf, RECV_BUFFER_LENGTH);
numRead = sock->LastCount();
}
//}
evt.SetInt(0);
isRunning = false;
//whatever data your thread calculated, to be returned to GUI
//evt.SetClientData((void*)temp);
wxPostEvent(m_pParent, evt);
return 0;
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
isRunning = true;
return 0;
}
}
MyThread *sockThread;
class GcodeCommandClass
{
private:
wxString cmd;
wxString params;
public:
GcodeCommandClass(wxString Command = "", wxString Parameters = "")
{
cmd = Command;
params = Parameters;
}
wxString getCommand()
{
return cmd;
}
wxString getParameter()
{
return params;
}
void setCommand(wxString Command)
{
cmd = Command;
}
void setParameter(wxString Parameters)
{
params = Parameters;
}
wxString getGcodeCmd(wxString Delimater = " ")
{
return cmd + Delimater + params;
}
bool isCmd(wxString Command)
{
if (cmd.CmpNoCase(Command) == 0)
return true;
return false;
}
};
GcodeCommandClass gcodeCmd;
bool DisplayProcess::HasInput() // The following methods are adapted from the exec sample. This one manages the stream redirection
{
m_parent->isPingRunning=true;
char c;
bool hasInput = false;
// The original used wxTextInputStream to read a line at a time. Fine, except when there was no \n, whereupon the thing would hang
// Instead, read the stream (which may occasionally contain non-ascii bytes e.g. from g++) into a memorybuffer, then to a wxString
while (IsInputAvailable()) // If there's std input
{
wxMemoryBuffer buf;
do
{
c = GetInputStream()->GetC(); // Get a char from the input
if (GetInputStream()->Eof())
break; // Check we've not just overrun
buf.AppendByte(c);
if (c==wxT('\n'))
break; // If \n, break to print the line
}
while (IsInputAvailable()); // Unless \n, loop to get another char
wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen()); // Convert the line to utf8
m_parent->processInput(line); // Either there's a full line in 'line', or we've run out of input. Either way, print it
hasInput = true;
}
while (IsErrorAvailable())
{
wxMemoryBuffer buf;
do
{
c = GetErrorStream()->GetC();
if (GetErrorStream()->Eof())
break;
buf.AppendByte(c);
if (c==wxT('\n'))
break;
}
while (IsErrorAvailable());
wxString line((const char*)buf.GetData(), wxConvUTF8, buf.GetDataLen());
m_parent->processInput(line);
hasInput = true;
}
return hasInput;
}
void DisplayProcess::OnTerminate(int pid, int status) // When the subprocess has finished, show the rest of the output, then an exit message
{
while (HasInput());
wxString exitmessage;
if (!status)
exitmessage = _("Success\n");
else
exitmessage = _("Process failed\n");
m_parent->exitstatus = status; // Tell the dlg what the exit status was, in case caller is interested
m_parent->isPingRunning=false;
m_parent->ProcessPollTimer.Stop();
m_running = NULL;
m_parent->getPrintStatus();
delete this;
}
// --------------------------------------------------------------------------
// resources
// --------------------------------------------------------------------------
// the application icon
//#ifndef wxHAS_IMAGES_IN_RESOURCES
//#include "../sample.xpm"
//#endif
//(*IdInit(NewFrame)
const long NewFrame::ID_STATICBOX1 = wxNewId();
const long NewFrame::ID_STATICTEXT1 = wxNewId();
const long NewFrame::ID_BUTTON1 = wxNewId();
const long NewFrame::ID_STATICTEXT2 = wxNewId();
const long NewFrame::ID_STATICBOX2 = wxNewId();
const long NewFrame::ID_BUTTON2 = wxNewId();
const long NewFrame::ID_BUTTON3 = wxNewId();
const long NewFrame::ID_BUTTON4 = wxNewId();
const long NewFrame::ID_GAUGE1 = wxNewId();
const long NewFrame::ID_STATICTEXT3 = wxNewId();
const long NewFrame::ID_STATICBOX3 = wxNewId();
const long NewFrame::ID_BUTTON5 = wxNewId();
const long NewFrame::ID_BUTTON6 = wxNewId();
const long NewFrame::ID_BUTTON7 = wxNewId();
const long NewFrame::ID_BUTTON8 = wxNewId();
const long NewFrame::ID_GAUGE2 = wxNewId();
const long NewFrame::ID_LISTCTRL1 = wxNewId();
const long NewFrame::ID_BUTTON9 = wxNewId();
const long NewFrame::ID_BITMAPBUTTON1 = wxNewId();
const long NewFrame::ID_COMBOBOX1 = wxNewId();
const long NewFrame::ID_PANEL1 = wxNewId();
const long NewFrame::ID_TIMER1 = wxNewId();
const long NewFrame::ID_STATUSBAR1 = wxNewId();
const long NewFrame::ID_TIMER2 = wxNewId();
const long NewFrame::ID_TIMER3 = wxNewId();
//*)
// --------------------------------------------------------------------------
// constants
// --------------------------------------------------------------------------
// IDs for the controls and the menu commands
// --------------------------------------------------------------------------
// event tables and other macros for wxWidgets
// --------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(NewFrame, wxFrame)
//(*EventTable(NewFrame)
//*)
EVT_COMMAND(wxID_ANY, wxEVT_READTHREAD, NewFrame::OnMyThread)
wxEND_EVENT_TABLE()
wxIMPLEMENT_APP(MyApp);
// ==========================================================================
// implementation
// ==========================================================================
// --------------------------------------------------------------------------
// the application class
// --------------------------------------------------------------------------
bool MyApp::OnInit()
{
if (!wxApp::OnInit())
return false;
// Create the main application window
NewFrame *frame = new NewFrame((wxFrame *)NULL, wxID_ANY, _("Photon Network Controller"), wxDefaultPosition, wxSize(300, 200));
#if defined(__WINDOWS__)
frame->SetIcon(wxICON(aaaa));
#elif defined(__WXGTK__)
char path[PATH_MAX ];
char dest[PATH_MAX];
memset(dest,0,sizeof(dest));
pid_t pid = getpid();
sprintf(path, "/proc/%d/exe", pid);
ssize_t PathLen = readlink( path, dest, PATH_MAX );
if(PathLen!=-1)
frame->SetIcon(wxIcon(wxString::Format(wxT("%s.xpm"), dest)));
#endif // defined
// Show it
frame->Show(true);
// success
return true;
}
// --------------------------------------------------------------------------
// main frame
// --------------------------------------------------------------------------
// frame constructor
NewFrame::NewFrame(wxFrame* parent, wxWindowID id, wxString title, const wxPoint& pos, const wxSize& size)
{
// HICON hIcon;
// hIcon = LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(2));
// SetClassLong(hWnd, GCL_HICON, (LONG) hIcon); // The new icon
// PostMessage (hWnd, WM_SETICON, ICON_BIG, (LPARAM) hIcon);
//(*Initialize(NewFrame)
Create(parent, wxID_ANY, _("Photon Network Controller"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE|wxMINIMIZE_BOX, _T("wxID_ANY"));
SetClientSize(wxSize(334,491));
Panel1 = new wxPanel(this, ID_PANEL1, wxPoint(224,320), wxSize(334,488), wxTAB_TRAVERSAL, _T("ID_PANEL1"));
StaticBox1 = new wxStaticBox(Panel1, ID_STATICBOX1, _("Connection Settings"), wxPoint(8,8), wxSize(320,80), 0, _T("ID_STATICBOX1"));
StaticText1 = new wxStaticText(Panel1, ID_STATICTEXT1, _("IP Address"), wxPoint(16,28), wxDefaultSize, 0, _T("ID_STATICTEXT1"));
btnConnect = new wxButton(Panel1, ID_BUTTON1, _("Connect"), wxPoint(235,54), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON1"));
lblStatus = new wxStaticText(Panel1, ID_STATICTEXT2, _("Not Connected"), wxPoint(16,60), wxDefaultSize, 0, _T("ID_STATICTEXT2"));
StaticBox2 = new wxStaticBox(Panel1, ID_STATICBOX2, _("Print Status"), wxPoint(8,96), wxSize(320,112), 0, _T("ID_STATICBOX2"));
btnStart = new wxButton(Panel1, ID_BUTTON2, _("Start"), wxPoint(16,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON2"));
btnPause = new wxButton(Panel1, ID_BUTTON3, _("Pause"), wxPoint(127,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON3"));
btnStop = new wxButton(Panel1, ID_BUTTON4, _("Stop"), wxPoint(235,118), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON4"));
PrintProgress = new wxGauge(Panel1, ID_GAUGE1, 1000, wxPoint(16,170), wxSize(304,24), 0, wxDefaultValidator, _T("ID_GAUGE1"));
lblPercentDone = new wxStaticText(Panel1, ID_STATICTEXT3, _("Percent Done"), wxPoint(16,152), wxDefaultSize, 0, _T("ID_STATICTEXT3"));
StaticBox3 = new wxStaticBox(Panel1, ID_STATICBOX3, _("Files"), wxPoint(8,216), wxSize(320,251), 0, _T("ID_STATICBOX3"));
btnDelete = new wxButton(Panel1, ID_BUTTON5, _("Delete"), wxPoint(16,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON5"));
btnRefresh = new wxButton(Panel1, ID_BUTTON6, _("Refresh"), wxPoint(125,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON6"));
btnUpload = new wxButton(Panel1, ID_BUTTON7, _("Upload"), wxPoint(235,392), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON7"));
btnDownload = new wxButton(Panel1, ID_BUTTON8, _("Download"), wxPoint(235,432), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON8"));
progressFile = new wxGauge(Panel1, ID_GAUGE2, 100, wxPoint(16,433), wxSize(212,24), 0, wxDefaultValidator, _T("ID_GAUGE2"));
ListCtrl1 = new wxListCtrl(Panel1, ID_LISTCTRL1, wxPoint(16,232), wxSize(304,152), wxLC_REPORT|wxLC_SINGLE_SEL|wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_LISTCTRL1"));
btnSettings = new wxButton(Panel1, ID_BUTTON9, _("Settings"), wxPoint(127,54), wxSize(85,26), 0, wxDefaultValidator, _T("ID_BUTTON9"));
btnSearchPrinter = new wxBitmapButton(Panel1, ID_BITMAPBUTTON1, wxArtProvider::GetBitmap(wxART_MAKE_ART_ID_FROM_STR(_T("wxART_FIND")),wxART_BUTTON), wxPoint(296,23), wxSize(25,25), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_BITMAPBUTTON1"));
btnSearchPrinter->SetMinSize(wxSize(25,25));
btnSearchPrinter->SetToolTip(_("Search for printer"));
comboIP = new wxComboBox(Panel1, ID_COMBOBOX1, wxEmptyString, wxPoint(127,24), wxSize(160,26), 0, 0, 0, wxDefaultValidator, _T("ID_COMBOBOX1"));
PollTimer.SetOwner(this, ID_TIMER1);
StatusBar1 = new wxStatusBar(this, ID_STATUSBAR1, 0, _T("ID_STATUSBAR1"));
int __wxStatusBarWidths_1[1] = { -10 };
int __wxStatusBarStyles_1[1] = { wxSB_NORMAL };
StatusBar1->SetFieldsCount(1,__wxStatusBarWidths_1);
StatusBar1->SetStatusStyles(1,__wxStatusBarStyles_1);
SetStatusBar(StatusBar1);
WatchDogTimer.SetOwner(this, ID_TIMER2);
ProcessPollTimer.SetOwner(this, ID_TIMER3);
Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnConnectClick);
Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnStartClick);
Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnPauseClick);
Connect(ID_BUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnStopClick);
Connect(ID_BUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnDeleteClick);
Connect(ID_BUTTON6,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnRefreshClick);
Connect(ID_BUTTON7,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnUploadClick);
Connect(ID_BUTTON8,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnDownloadClick);
Connect(ID_BUTTON9,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnSettingsClick);
Connect(ID_BITMAPBUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&NewFrame::OnbtnSearchPrinterClick);
Connect(ID_TIMER1,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnPollTimerTrigger);
Connect(ID_TIMER2,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnWatchDogTimerTrigger);
Connect(ID_TIMER3,wxEVT_TIMER,(wxObjectEventFunction)&NewFrame::OnProcessPollTimerTrigger);
//*)
//#if defined(__WXGTK__)
//SetClientSize(wxSize(334, 470));
//#else
SetClientSize(wxSize(334,470));
#ifdef __WINDOWS__
comboIP->SetPosition(wxPoint(127, 24));
#else
comboIP->SetPosition(wxPoint(127, 23));
#endif
setStatusMessages(_("Not Connected"), "", "");
readSettings();
}
wxArrayString GetNetworkAddresses()
{
wxArrayString array;
#ifndef __WINDOWS__
// host name is a valid entry
array.Add(wxGetFullHostName());
// now get all the IP addresses
bool result = false;
struct hostent* currentHost = NULL;
char hostName[_POSIX_HOST_NAME_MAX];
int hostResult = gethostname(hostName, sizeof (hostName) - 1);
// null terminate
hostName[sizeof(hostName) / sizeof(char) - 1] = '\0';
if (hostResult == 0)
{
currentHost = gethostbyname(hostName);
if (NULL != currentHost)
{
result = true;
}
}
if (result)
{
for (int i = 0 ; currentHost->h_addr_list[i] != NULL ; ++i)
{
char *inoutString = inet_ntoa(*(struct in_addr*)(currentHost->h_addr_list[i]));
// add the IP address
array.Add(wxString((char*) &inoutString[0], wxConvLocal));
}
}
#else
// win32
int i = 0;
WSAData wsaData;
struct hostent *phe = NULL;
if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
{
goto end;
}
char ac[80];
if (gethostname(ac, sizeof(ac)) == SOCKET_ERROR)
{
goto end;
}
phe = gethostbyname(ac);
if (phe == 0)
{
goto end;
}
for (i = 0 ; phe->h_addr_list[i] != 0 ; ++i)
{
struct in_addr addr;
memcpy(&addr, phe->h_addr_list[i], sizeof(struct in_addr));
char *address = inet_ntoa(addr);
// add the IP address
array.Add(wxString((char*) &address[0], wxConvLocal));
}
end:
WSACleanup();
#endif
// if all above fail, then fallback to wxWidgets
//if (array.GetCount() == 0)
//{
// array.Add(this->GetCurrentIPAddress());
//}
return array;
}
wxString convertSize(size_t size)
{
const char *SIZES[] = { _("Bytes"), _("KB"), _("MB"), _("GB") };
unsigned int div = 0;
size_t rem = 0;
while (size >= 1024 && div < (sizeof SIZES / sizeof *SIZES))
{
rem = (size % 1024);
div++;
size /= 1024;
}
double size_d = (float)size + (float)rem / 1024.0;
wxString result;
unsigned int FileSize = round(size_d);
result.Printf("%d %s", FileSize, SIZES[div]);
return result;
}
double getValue(wxString str, wxString prefix, double default_val, wxString ahead)
{
try
{
int startIndex = 0;
if (ahead != "")
{
startIndex = str.Find(ahead);
if (startIndex != -1)
{
startIndex += ahead.Length();
}
}
int index = str.substr(startIndex).Find(prefix);
if (index != wxNOT_FOUND)
{
index += prefix.Length();
int length = 0;
//char* chArray = str.ToCharArray();
char* chArray = (char*)malloc(sizeof(char)*(str.Length()));
strcpy(chArray, (const char*)str.mb_str(wxConvUTF8));
for (unsigned int i = index; i < str.Length(); i++)
{
char ch = chArray[i];
if (((ch < '0') || (ch > '9')) && ((ch != '.') && (ch != '-')))
{
break;
}
length++;
}
if (length > 0)
{
double value;
if (!str.substr(index, length).ToDouble(&value))
return -1;
else
return value;
}
return default_val;
}
return default_val;
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
return default_val;
}
}
wxString getStringValue(wxString str, wxString prefix, wxString default_val, wxString ahead)
{
try
{
int startIndex = 0;
if (ahead != "")
{
startIndex = str.Find(ahead);
if (startIndex != -1)
{
startIndex += ahead.Length();
}
}
int index = str.substr(startIndex).Find(prefix);
if (index != wxNOT_FOUND)
{
index += prefix.Length();
wxString tempstr = str.substr(index);
int len = tempstr.Find(' ');
if (len == wxNOT_FOUND)
return tempstr.Trim();
else
return tempstr.substr(0, len).Trim();
}
return default_val;
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
return default_val;
}
}
double getValue(wxString str, wxString prefix, double default_val)
{
return getValue(str, prefix, default_val, "");
}
NewFrame::~NewFrame()
{
//(*Destroy(NewFrame)
//*)
}
void NewFrame::processInput(wxString input)
{
if (input.IsEmpty())
return;
if(pingFailed) //if you have determined that the ping has already failed then just skip rest of the function
return;
wxString line = input.Trim();
#if defined(__WINDOWS__)
if(line.Contains(wxString("timed out")) || line.Contains(wxString("host unreachable")))
{
//printf("Ping Failed");
saveLog(LOG_INFORMATION,_("Ping Failed."));
pingFailed=true;
}
#else
if(line.Find(wxString("packet loss"))!=wxNOT_FOUND)
{
wxString loss = line.BeforeLast('%').AfterLast(',');
double value;
if(loss.ToDouble(&value))
{
if(value!=0)
{
saveLog(LOG_INFORMATION,_("Ping Failed."));
pingFailed=true;
}
}
}
#endif
}
bool NewFrame::connectToPrinter(wxString hostname)
{
if(pingPrinter(hostname,(int)pingTimeOut))
{
wxIPV4address addrLocal;
addrLocal.Hostname();
sock = new wxDatagramSocket(addrLocal);
//wxDatagramSocket sock(addrLocal);
if (!sock->IsOk())
{
wxMessageBox(_("Failed to create UDP socket."), _("Error"), wxICON_ERROR);
saveLog(LOG_INFORMATION,_("Failed to create UDP socket."));
return false;
}
//wxIPV4address addrPeer;
//if (addrPeer != NULL)
//{
// free(addrPeer);
// addrPeer = NULL;
//}
addrPeer = new wxIPV4address;
addrPeer->Hostname(hostname);
addrPeer->Service(port);
isconnected = false;
startList = false;
endList = false;
fileCount = 0;
photonFile = NULL;
photonFileName = wxEmptyString;
photonFilePath = wxEmptyString;
beforeByte = 0;
frameNum = 0;
numDownloadRetries = 0;
downloadStarted = false;
downloadFileLength = -1;
downloadFileCurrentLength = -1;
btnStart->Enable();
PollTimer.Stop();
WatchDogTimer.Stop();
saveLog(LOG_INFORMATION,_("Connected to printer running at IP ")+hostname);
return true;
}
else
{
wxMessageBox(_("The address cannot be reached."), _("Error"), wxICON_ERROR);
saveLog(LOG_INFORMATION,_("The address ") + hostname + _(" cannot be reached."));
return false;
}
}
void NewFrame::disconnectFromPrinter()
{
try
{
if (isRunning)
{
sockThread->Kill();
//free(sockThread);
sockThread = NULL;
isRunning = false;
}
if(sock->IsOk())
sock->Close();
//if (addrPeer != NULL)
//{
// free(addrPeer);
// addrPeer = NULL;
//}
isconnected = false;
startList = false;
endList = false;
fileCount = 0;
photonFile = NULL;
photonFileName = wxEmptyString;
photonFilePath = wxEmptyString;
beforeByte = 0;
frameNum = 0;
numDownloadRetries = 0;
downloadStarted = false;
downloadFileLength = -1;
downloadFileCurrentLength = -1;
PollTimer.Stop();
WatchDogTimer.Stop();
setStatusMessages(_("Not Connected"), "", "");
btnConnect->SetLabel(_("Connect"));
lblStatus->SetLabel(_("Not Connected"));
lblPercentDone->SetLabel(_("Percent Done"));
clearListControl();
progressFile->SetValue(0);
PrintProgress->SetValue(0);
btnStart->Disable();
saveLog(LOG_INFORMATION,_("Printer Disconnected"));
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
}
}
void NewFrame::setStatusMessages(wxString message1, wxString message2, wxString message3)
{
if (message1 != "prev")
msges[0] = message1;
if (message2 != "prev")
msges[1] = message2;
if (message3 != "prev")
msges[2] = message3;
SetStatusText(msges[0] + " " + msges[1] + " " + msges[2], 0);
saveLog(LOG_INFORMATION,msges[0] + " " + msges[1] + " " + msges[2]);
}
void NewFrame::sendCmdToPrinter(wxString cmd)
{
try
{
memset(&receivedBuf[0], 0, sizeof(receivedBuf));
wxUint32 sendSize = cmd.Length();
char* tempBuffer = (char*)malloc(sizeof(char)*(2 + sendSize));
strcpy(tempBuffer, (const char*)cmd.mb_str(wxConvUTF8)); // buf will now contain the command
tempBuffer[sendSize] = '\0';
tempBuffer[sendSize + 1] = '\0';
saveLog(LOG_INFORMATION,wxString::Format(wxT("Send to printer \"%s\""), tempBuffer));
WatchDogTimer.Start(replyTimeout, true);
if (sock->SendTo(*addrPeer, tempBuffer, sendSize).LastCount() != sendSize)
{
wxMessageBox(_("Failed to send data"), _("Error"), wxICON_ERROR);
saveLog(LOG_ERROR,_("Failed to send data"));
return;
}
free(tempBuffer);
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
wxMessageBox(_("Failed to send data"), _("Error"), wxICON_ERROR);
saveLog(LOG_ERROR,_("Failed to send data"));
}
}
void NewFrame::sendCmdToPrinter(uint8_t* cmd, unsigned int sendSize)
{
try
{
memset(&receivedBuf[0], 0, sizeof(receivedBuf));
WatchDogTimer.Start(replyTimeout, true);
if (sock->SendTo(*addrPeer, cmd, sendSize).LastCount() != sendSize)
{
wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR);
saveLog(LOG_ERROR,_("Failed to send data"));
return;
}
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR);
saveLog(LOG_ERROR,_("Failed to send data"));
}
}
void NewFrame::broadcastOverUDP(wxString broadCastHost,uint8_t* cmd, unsigned int sendSize)
{
try
{
wxIPV4address m_LocalAddress;
m_LocalAddress.AnyAddress();
m_LocalAddress.Service(3001); // port on which we listen
// Create the socket
m_Listen_Socket = new wxDatagramSocket(m_LocalAddress, wxSOCKET_REUSEADDR);
if (m_Listen_Socket->Error())
{
wxLogError(_("Could not open Datagram Socket"));
saveLog(LOG_ERROR,_("Could not open Datagram Socket"));
return;
}
else
{
///////////////////////////////////////////////////////////////////////////
// To send to a broadcast address, you must enable SO_BROADCAST socket
// option, in plain C this is:
// int enabled = 1;
// setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &enabled, sizeof(enabled));
// where sockfd is the socket descriptor (See http://linux.die.net/man/2/setsockopt)
// See also boxcarmiba Wed Aug 02, 2006
// at https://forums.wxwidgets.org/viewtopic.php?t=9410
static int enabled = 1;
m_Listen_Socket->SetOption(SOL_SOCKET, SO_BROADCAST, &enabled, sizeof(enabled));
///////////////////////////////////////////////////////////////////////////
// Specify a broadcast IP, in this case "Limited Broadcast" on the local network:
free(m_BroadCastAddress);
m_BroadCastAddress = NULL;
m_BroadCastAddress = new wxIPV4address;
m_BroadCastAddress->Hostname(broadCastHost);
m_BroadCastAddress->Service(3000);
// Use same socket created for listening for sending:
m_Listen_Socket->SendTo(*m_BroadCastAddress, cmd, sendSize);
if (m_Listen_Socket->Error())
{
//wxLogMessage(_T("SendTo Error: %d"), m_Listen_Socket->LastError());
saveLog(LOG_ERROR,wxString::Format(wxT("SendTo Error: %d"), m_Listen_Socket->LastError()));
}
saveLog(LOG_INFORMATION,wxString::Format(wxT("Send broadcast message to %s"), broadCastHost));
}
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
wxMessageBox(_("failed to send data"), _("Error"), wxICON_ERROR);
saveLog(LOG_ERROR,_("Failed to send data"));
}
}
wxArrayString NewFrame::getBlockingBroadcastReply(wxString broadcastHostname)
{
wxArrayString ipArray;
try
{
wxIPV4address Peer;
wxString host;
unsigned int itemIndex = 0;
wxString beforeString = comboIP->GetValue();
do
{
memset(&receivedBuf[0], 0, sizeof(receivedBuf));
m_Listen_Socket->SetTimeout(2);
m_Listen_Socket->Read(&receivedBuf, sizeof(receivedBuf));
m_Listen_Socket->GetPeer(Peer);
host = Peer.IPAddress();
if (host != "255.255.255.255" && host!= broadcastHostname)
{
wxString name = getStringValue(receivedBuf, "NAME:", "00_NO_NAME_00", "");
if (name != "00_NO_NAME_00")
{
ipArray.Add(host);
saveLog(LOG_INFORMATION,wxString::Format(wxT("Received reply from IP %s"), host));
//comboIP->Insert(host, itemIndex);
//comboIP->SetValue(host);
itemIndex++;
}
}
} while (m_Listen_Socket->IsData());
m_Listen_Socket->Close();
free(m_Listen_Socket);
m_Listen_Socket = NULL;
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
}
return ipArray;
}
void NewFrame::getAsyncReply()
{
try
{
//free(sockThread);
//sockThread = NULL;
sockThread = new MyThread(this);
sockThread->Create();
sockThread->Run();
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
}
}
void NewFrame::getBlockingReply()
{
try
{
memset(&receivedBuf[0], 0, sizeof(receivedBuf));
sock->SetTimeout((long)(replyTimeout / 1000));
numRead = sock->RecvFrom(*addrPeer, receivedBuf, sizeof(receivedBuf)).LastCount();
saveLog(LOG_INFORMATION,_("Received data from Printer. Blocking receive"));
WatchDogTimer.Stop();
}
catch (std::exception &e)
{
saveLog(LOG_EXCEPTION,wxString(e.what()));
}
}
void NewFrame::clearListControl()
{
ListCtrl1->ClearAll();
ListCtrl1->DeleteAllColumns();
//The two lines below is only needed for GCC under windows. It works fine without this in all other OSes
ListCtrl1->~wxListCtrl();
ListCtrl1 = new wxListCtrl(Panel1, ID_LISTCTRL1, wxPoint(16, 232), wxSize(304, 152), wxLC_REPORT | wxLC_SINGLE_SEL | wxSUNKEN_BORDER, wxDefaultValidator, _T("ID_LISTCTRL1"));
//Under Windows GCC the list fails to redraw after deleting items in it. The above workaround is the easiest way to fix that issue
//comment them out for better performance under other platforms
}
void NewFrame::handleResponse()
{
WatchDogTimer.Stop();
saveLog(LOG_INFORMATION,_("Received data from Printer. Async receive"));
if (gcodeCmd.isCmd("M4002")) //Gcode to read version info from printer
{
wxString tempStr = receivedBuf;
if (tempStr.Length() <= 0)
return;
lblStatus->SetLabel(_("Connected"));
btnConnect->SetLabel(_("Disconnect"));
isconnected = true;
setStatusMessages(tempStr.substr(3).Trim(), "", "");
isConnected = true;
while (sock->IsData()) //get rid of extra messages from the sockets buffer as it will confuse the program
getBlockingReply();
updatefileList();
PollTimer.Start(300); //Get printer status if possible
saveLog(LOG_INFORMATION,_("Received version information from printer. Reply for M4002"));
}
else if (gcodeCmd.isCmd("M20")) //Gcode to read the filelist
{
wxString receivedText = receivedBuf;
receivedText.Trim();
if (!receivedText.Contains("Begin file list"))
{
if (!startList) //if the file listing has not started then read again
{
getAsyncReply();
}
else
{
if (!receivedText.Contains("End file list")) //File listing has not ended
{
wxStringTokenizer temp(receivedText, " ");
wxString temp1 = "";
while (temp.HasMoreTokens())
{
wxString token = temp.GetNextToken();
temp1 = temp1 + token + " ";
if (temp.CountTokens() == 1)
break;
}
wxString token = temp.GetNextToken();
long value;
if (token.ToLong(&value))
{
if (value > 0)
{
ListCtrl1->InsertItem(fileCount, wxString((char)(fileCount + 49)));
ListCtrl1->SetItem(fileCount, 1, temp1);
ListCtrl1->SetItem(fileCount, 2, convertSize(value));
fileCount++;
}
}
else
{
ListCtrl1->InsertItem(fileCount, wxString((char)(fileCount + 49)));
ListCtrl1->SetItem(fileCount, 1, temp1);
ListCtrl1->SetItem(fileCount, 2, _("Unknown"));
fileCount++;
}
getAsyncReply();
}
else
{
startList = false; //File list ended don't read any more lines
endList = true;
saveLog(LOG_INFORMATION,_("Received File list from printer. Reply for M20"));
}
}
}
else
{
startList = true; //File Listing just Started
endList = false;
clearListControl();
ListCtrl1->AppendColumn(_("Num"), wxLIST_FORMAT_LEFT, 50);
ListCtrl1->AppendColumn(_("File Name"), wxLIST_FORMAT_LEFT, 175);
ListCtrl1->AppendColumn(_("Size"), wxLIST_FORMAT_LEFT, 75);
fileCount = 0;
getAsyncReply();
}
if (endList) //Received end of file list in the last command so now clean up rest of the receive buffer
{
getBlockingReply();
}
//else if (endList>=1)
//{
//get rid of extra messages from the sockets buffer as it will confuse the program
//}
}
else if (gcodeCmd.isCmd("M6030")) //Gcode to Start Printing
{
ispaused = false;
isPrinting = true;
btnPause->Enable();
btnStart->Disable();
btnStop->Enable();
gcodeCmd.setCommand("M27");
gcodeCmd.setParameter("");
beforeByte = 0;
frameNum = 0;