-
Notifications
You must be signed in to change notification settings - Fork 19
/
UwxScripting.cpp
1083 lines (991 loc) · 39 KB
/
UwxScripting.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
/******************************************************************************
** Copyright (C) 2016-2023 Laird Connectivity
**
** Project: UwTerminalX
**
** Module: UwxScripting.cpp
**
** Notes:
**
** License: This program is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License as
** published by the Free Software Foundation, version 3.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see http://www.gnu.org/licenses/
**
** SPDX-License-Identifier: GPL-3.0
**
*******************************************************************************/
/******************************************************************************/
// Include Files
/******************************************************************************/
#include "UwxScripting.h"
#include "ui_UwxScripting.h"
/******************************************************************************/
// Local Functions or Private Members
/******************************************************************************/
UwxScripting::UwxScripting(QWidget *parent) : QDialog(parent), ui(new Ui::UwxScripting)
{
//On form creation
ui->setupUi(this);
//Set the textbox font
QFont fntTmpFnt = QFontDatabase::systemFont(QFontDatabase::FixedFont);
fntTmpFnt.setFixedPitch(true);
fntTmpFnt.setPointSize(9);
QFontMetrics tmTmpFM(fntTmpFnt);
ui->edit_Script->setFont(fntTmpFnt);
ui->edit_Script->setTabStopDistance(tmTmpFM.horizontalAdvance(" ")*6);
//Create highlighter object
mhlHighlighter = new LrdHighlighter(ui->edit_Script->document());
//Setup pause timer
mtmrPauseTimer.setSingleShot(true);
connect(&mtmrPauseTimer, SIGNAL(timeout()), this, SLOT(AdvanceLine()));
//Setup status bar update timer
mtmrUpdateTimer.setSingleShot(false);
connect(&mtmrUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateStatusBar()));
//Script is not currently running or waiting for a data match
mbIsRunning = false;
mbWaitingForReceive = false;
//Set the icons and tooltip of the buttons
ui->btn_Load->setText("");
ui->btn_Load->setIcon(this->style()->standardIcon(QStyle::SP_DialogOpenButton));
ui->btn_Save->setText("");
ui->btn_Save->setIcon(this->style()->standardIcon(QStyle::SP_DialogSaveButton));
ui->btn_Compile->setText("");
ui->btn_Compile->setIcon(this->style()->standardIcon(QStyle::SP_MessageBoxWarning));
ui->btn_Run->setText("");
ui->btn_Run->setIcon(this->style()->standardIcon(QStyle::SP_MediaPlay));
ui->btn_Pause->setText("");
ui->btn_Pause->setIcon(this->style()->standardIcon(QStyle::SP_MediaPause));
ui->btn_Stop->setText("");
ui->btn_Stop->setIcon(this->style()->standardIcon(QStyle::SP_MessageBoxCritical));
ui->btn_Clear->setText("");
ui->btn_Clear->setIcon(this->style()->standardIcon(QStyle::SP_DialogDiscardButton));
ui->btn_Help->setText("");
ui->btn_Help->setIcon(this->style()->standardIcon(QStyle::SP_MessageBoxQuestion));
ui->btn_Options->setMinimumHeight(ui->btn_Compile->height()-2);
ui->btn_Options->setMaximumHeight(ui->btn_Compile->height()-2);
//Serial port is not yet open
mbSerialStatus = false;
//Create status bar
msbStatusBar = new QStatusBar;
ui->StatusBarLayout->addWidget(msbStatusBar);
msbStatusBar->showMessage("[Status]");
//Remove question mark button from window title
this->setWindowFlags((Qt::Window | Qt::WindowCloseButtonHint));
//Create option menu items
gpOptionsMenu = new QMenu(this);
gpOptionsMenu->addAction("Change Font")->setData(MenuActionChangeFont);
gpSOptionsMenu1 = gpOptionsMenu->addMenu("Export to");
gpSOptionsMenu1->addAction("String Player")->setData(MenuActionExportStringPlayer);
//Connect signals
connect(gpOptionsMenu, SIGNAL(triggered(QAction*)), this, SLOT(MenuSelected(QAction*)));
//Create shotcut objects
qaKeyShortcuts[0] = new QShortcut(QKeySequence::Save, this);
qaKeyShortcuts[1] = new QShortcut(QKeySequence::Open, this);
qaKeyShortcuts[2] = new QShortcut(QKeySequence::HelpContents, this);
qaKeyShortcuts[3] = new QShortcut(QKeySequence::New, this);
qaKeyShortcuts[4] = new QShortcut(QKeySequence::Refresh, this);
//Connect shortcuts
connect(qaKeyShortcuts[0], SIGNAL(activated()), this, SLOT(on_btn_Save_clicked()));
connect(qaKeyShortcuts[1], SIGNAL(activated()), this, SLOT(on_btn_Load_clicked()));
connect(qaKeyShortcuts[2], SIGNAL(activated()), this, SLOT(on_btn_Help_clicked()));
connect(qaKeyShortcuts[3], SIGNAL(activated()), this, SLOT(on_btn_Clear_clicked()));
connect(qaKeyShortcuts[4], SIGNAL(activated()), this, SLOT(on_btn_Run_clicked()));
}
//=============================================================================
//=============================================================================
UwxScripting::~UwxScripting(
)
{
//On dialogue deletion
disconnect(&mtmrPauseTimer, SIGNAL(timeout()), this, SLOT(AdvanceLine()));
disconnect(gpOptionsMenu, SIGNAL(triggered(QAction*)), this, SLOT(MenuSelected(QAction*)));
disconnect(qaKeyShortcuts[0], SIGNAL(activated()), this, SLOT(on_btn_Save_clicked()));
disconnect(qaKeyShortcuts[1], SIGNAL(activated()), this, SLOT(on_btn_Load_clicked()));
disconnect(qaKeyShortcuts[2], SIGNAL(activated()), this, SLOT(on_btn_Help_clicked()));
disconnect(qaKeyShortcuts[3], SIGNAL(activated()), this, SLOT(on_btn_Clear_clicked()));
disconnect(qaKeyShortcuts[4], SIGNAL(activated()), this, SLOT(on_btn_Run_clicked()));
//Clean up
delete qaKeyShortcuts[4];
delete qaKeyShortcuts[3];
delete qaKeyShortcuts[2];
delete qaKeyShortcuts[1];
delete qaKeyShortcuts[0];
delete mhlHighlighter;
delete msbStatusBar;
delete gpSOptionsMenu1;
delete gpOptionsMenu;
delete ui;
}
//=============================================================================
//=============================================================================
void
UwxScripting::SetPopupHandle(
PopupMessage *pmNewHandle
)
{
//Sets the Popup Message handle
mFormAuto = pmNewHandle;
}
//=============================================================================
//=============================================================================
void
UwxScripting::ChangeFont(
)
{
//Change font
bool bTmpBool;
QFont fntTmpFnt = QFontDialog::getFont(&bTmpBool, ui->edit_Script->font(), this);
if (bTmpBool == true)
{
//Set font and re-adjust tab spacing
QFontMetrics tmTmpFM(fntTmpFnt);
ui->edit_Script->setFont(fntTmpFnt);
ui->edit_Script->setTabStopDistance(tmTmpFM.horizontalAdvance(" ")*6);
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Load_clicked(
)
{
//Load buffer from file
QString strLoadFile = QFileDialog::getOpenFileName(this, tr("Open File"), strLastScriptFile, "Text files (*.txt)");
if (!strLoadFile.isNull() && !strLoadFile.isEmpty())
{
//File was selected
LoadScriptFile(&strLoadFile);
emit UpdateScriptLastDirectory(&strLoadFile);
strLastScriptFile = strLoadFile;
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Save_clicked(
)
{
//Save buffer contents
QString strSaveFile = QFileDialog::getSaveFileName(this, tr("Save File"), "", "Text files (*.txt)");
if (strSaveFile.length() > 1)
{
//File was selected
QFile fileSave(strSaveFile);
if (fileSave.open(QFile::WriteOnly | QFile::Text))
{
//File opened for writing
if (fileSave.size() > ui->edit_Script->toPlainText().length())
{
//Truncate file
fileSave.resize(ui->edit_Script->toPlainText().length());
}
//Output the data to the file
QTextStream tsDataStream(&fileSave);
tsDataStream << ui->edit_Script->toPlainText();
fileSave.close();
}
else
{
//Failed to open file
QString strMessage = tr("Error during scripting file save: Access to selected file is denied: ").append(strSaveFile);
mFormAuto->SetMessage(&strMessage);
mFormAuto->show();
}
}
}
//=============================================================================
//=============================================================================
bool
UwxScripting::on_btn_Compile_clicked(
)
{
//Compile script
ui->edit_Script->ClearBadLines();
mintCLine = -1;
ui->edit_Script->SetExecutionLine(mintCLine);
unsigned int i = 0;
bool bFailed = false;
if (ui->edit_Script->document()->lineCount() > 0)
{
//At least one line of data
QTextBlock tbCurrentBlock = ui->edit_Script->document()->firstBlock();
while (tbCurrentBlock.isValid())
{
int iLineLength = tbCurrentBlock.text().length();
if (iLineLength == 1)
{
//Fail
ui->edit_Script->AddBadLine(i);
bFailed = true;
}
else if (iLineLength > 1)
{
//Check the command
if (tbCurrentBlock.text().at(0) == ScriptingWaitTime)
{
//Check if the time value is valid or not
bool bConverted = false;
int intConv = tbCurrentBlock.text().right(tbCurrentBlock.text().length()-1).toInt(&bConverted);
if (bConverted == false)
{
//Invalid number
ui->edit_Script->AddBadLine(i);
bFailed = true;
}
else if (intConv <= 0)
{
//Time value is 0 or negative
ui->edit_Script->AddBadLine(i);
bFailed = true;
}
}
else if (!(tbCurrentBlock.text().at(0) == ScriptingDataOut) && !(tbCurrentBlock.text().at(0) == ScriptingDataIn) && !(tbCurrentBlock.text().at(0) == ScriptingWaitTime) && !(tbCurrentBlock.text().left(2) == ScriptingComment) && QString(tbCurrentBlock.text()).replace("\t", "").replace(" ", "").length() > 0)
{
//Text present that isn't space/tab or a valid command
ui->edit_Script->AddBadLine(i);
bFailed = true;
}
}
//Progrss to next block
tbCurrentBlock = tbCurrentBlock.next();
++i;
}
}
//Show status bar message
msbStatusBar->showMessage((bFailed == false ? "Script compile successful: no errors." : "Script compile failed due to syntax errors."));
//Repaint with line colours
ui->edit_Script->repaint();
//Return fail code
return bFailed;
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Run_clicked(
)
{
//Run script
if (mbSerialStatus == true && on_btn_Compile_clicked() == false)
{
//Compile successful, check if main form is busy
mnRepeats = 0;
mnScriptLines = ui->edit_Script->blockCount();
msbStatusBar->showMessage("Script execution request pending...");
emit ScriptStartRequest();
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::SerialPortStatus(
bool bPortStatus
)
{
//Serial port has been opened or closed
mbSerialStatus = bPortStatus;
if (bPortStatus == false)
{
if (mbIsRunning == true)
{
//Stop running script and display error
on_btn_Stop_clicked();
msbStatusBar->showMessage("Script stopped due to serial port disconnecting.");
}
//Disable run button
ui->btn_Run->setEnabled(false);
}
else
{
//Enable run button
ui->btn_Run->setEnabled(true);
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::SerialPortError(
QSerialPort::SerialPortError SPE
)
{
//Serial port has an error
if (SPE != QSerialPort::NoError)
{
if (mbIsRunning == true)
{
//Stop running script and display error
on_btn_Stop_clicked();
msbStatusBar->showMessage("Script stopped due to serial port error.");
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::SerialPortData(
const QByteArray *Data
)
{
//Serial port data received
if (mbIsRunning == true)
{
//Append data
mbaRecvData.append(*Data);
if (mbWaitingForReceive == true)
{
//Check if there is a match for this line
AdvanceLine();
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Stop_clicked(
)
{
//Stop execution
if (mbIsRunning == true)
{
//Stop execution and timer
mbIsRunning = false;
if (mtmrPauseTimer.isActive())
{
mtmrPauseTimer.stop();
}
//Stop update timer update if running
if (mtmrUpdateTimer.isActive())
{
mtmrUpdateTimer.stop();
}
//Clear buffers
mbaRecvData.clear();
mbaMatchData.clear();
mbWaitingForReceive = false;
//Disable read only mode of editor
SetButtonStatus(true);
if (gtmrRecTimer.isValid())
{
//Invalidate receive timer
gtmrRecTimer.invalidate();
}
//Update status bar
QString strRepeatText;
if (mnRepeats > 0)
{
//Create text for repeat information
strRepeatText = QString(" with ").append(QString::number(mnRepeats)).append(" repeat").append(mnRepeats == 1 ? "" : "s").append(", ~");
double fElapsed = (double)gtmrScriptTimer.elapsed()/1000.0;
if (fElapsed == 0.0)
{
//Avoid division by zero
fElapsed = 1.0;
}
strRepeatText.append(QString::number(fElapsed/(double)mnRepeats, 'f', 1)).append(" seconds/loop");
}
//Show script stopped message
msbStatusBar->showMessage(QString("Script stopped after ~").append(QString::number(((double)gtmrScriptTimer.elapsed()/1000.0), 'f', 1)).append(" seconds").append(strRepeatText));
gtmrScriptTimer.invalidate();
ui->edit_Script->SetExecutionLineStatus(true);
//Return window title
setWindowTitle("Scripting");
//Notify main form that script is no longer executing
emit ScriptFinished();
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::ExportToStringPlayer(
)
{
//Export to stringplayer
if (on_btn_Compile_clicked() == false)
{
//Compile successful
QString strSaveFile = QFileDialog::getSaveFileName(this, tr("Save File"), "", "StringPlayer Files (*.sub)");
if (strSaveFile.length() > 1)
{
//File was selected
QFile fileExport(strSaveFile);
if (fileExport.open(QFile::WriteOnly | QFile::Text))
{
//File opened for writing. Output the data to the file
QTextStream tsDataStream(&fileExport);
//Output header
tsDataStream << "//Exported from UwTerminalX v" << mstrUwTerminalXVersion << " Scripting on " << QDate::currentDate().toString("dd/MM/yyyy") << " @ " << QTime::currentTime().toString("hh:mm") << "\r\n\r\nSET vPort \"0\" //Change to the port number to send/receive data on\r\nDECLARE vWaitTime\r\nSET vWaitTime \"5000\" //Change to the desired maximum wait time for each receive event in ms\r\n\r\n";
//Go through each block in the editor
QTextBlock tbCurrentBlock = ui->edit_Script->document()->firstBlock();
while (tbCurrentBlock.isValid())
{
if (tbCurrentBlock.text().left(2) == ScriptingComment)
{
//Comment
tsDataStream << tbCurrentBlock.text() << "\r\n";
}
else if (tbCurrentBlock.text().at(0) == ScriptingDataOut)
{
//Send out
tsDataStream << "SENDCMD [vPort] \"" << tbCurrentBlock.text().right(tbCurrentBlock.text().length()-1) << "\"\r\n";
}
else if (tbCurrentBlock.text().at(0) == ScriptingDataIn)
{
//Receive
tsDataStream << "WAITRESPEX [vWaitTime] [vPort] \"" << tbCurrentBlock.text().right(tbCurrentBlock.text().length()-1) << "\"\r\n";
}
else if (tbCurrentBlock.text().at(0) == ScriptingWaitTime)
{
//Wait for
tsDataStream << "DELAY \"" << tbCurrentBlock.text().right(tbCurrentBlock.text().length()-1) << "\"\r\n";
}
else if (tbCurrentBlock.text().length() == 0)
{
//Newline
tsDataStream << "\r\n";
}
else if (QString(tbCurrentBlock.text()).replace("\t", "").replace(" ", "").length() > 0)
{
//Text present that isn't space/tab, just assume a newline
tsDataStream << "\r\n";
}
//Progress to next block
tbCurrentBlock = tbCurrentBlock.next();
}
fileExport.close();
//Show message
msbStatusBar->showMessage("StringPlayer export successful!");
}
else
{
//Failed to open file
QString strMessage = tr("Error during Scripting StringPlayer file export: Access to selected file is denied: ").append(strSaveFile);
mFormAuto->SetMessage(&strMessage);
mFormAuto->show();
}
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::AdvanceLine(
)
{
//Executes the next script line
if (mtmrUpdateTimer.isActive() && ucLastAct != ScriptingActionDataIn)
{
//Stop pause update timer
mtmrUpdateTimer.stop();
}
while (mtbExecutionBlock.isValid())
{
//Execution block exists
ui->edit_Script->SetExecutionLine(mintCLine);
if (mbIsRunning == false)
{
//Cancelled
return;
}
else if (ui->btn_Pause->isChecked())
{
//Execution is paused
return;
}
if (mtbExecutionBlock.text().length() > 0)
{
//Some data is present
if (mtbExecutionBlock.text().at(0) == ScriptingDataOut)
{
//Clear receive buffer and send data out
mbaRecvData.clear();
QByteArray baTmpDat(mtbExecutionBlock.text().right(mtbExecutionBlock.text().length()-1).toUtf8());
UwxEscape::EscapeCharacters(&baTmpDat);
//Set the number of bytes remaining to be written to the length of the string (only used if the WaitForWrite checkout is enabled)
mbBytesWriteRemain = QString(baTmpDat).length();
//Pass the data back to the main form
emit SendData(baTmpDat, false, true);
ucLastAct = ScriptingActionDataOut;
if (ui->check_WaitForWrite->isChecked() == true)
{
//Wait for data to leave the buffer
UpdateStatusBar();
return;
}
}
else if (mtbExecutionBlock.text().at(0) == ScriptingDataIn)
{
//Receive
mbaMatchData = mtbExecutionBlock.text().right(mtbExecutionBlock.text().length()-1).toUtf8();
UwxEscape::EscapeCharacters(&mbaMatchData);
ucLastAct = ScriptingActionDataIn;
if (!gtmrRecTimer.isValid())
{
//Start timer
gtmrRecTimer.start();
mtmrUpdateTimer.start(500);
}
if (CheckRecvMatchBuffers() == false)
{
//Waiting on a match
if (mbaRecvData.length() > ui->spin_MaxRecBufSize->value())
{
//Buffer is too big, clear and fail the script
QString strMsg = QString("Script failed (expected data not found after ").append(ui->spin_MaxRecBufSize->text()).append(" bytes (").append(QString::number(mbaRecvData.length())).append(" bytes in buffer) after ");
ui->edit_Script->SetExecutionLineStatus(true);
on_btn_Stop_clicked();
strMsg.append(msbStatusBar->currentMessage().right(msbStatusBar->currentMessage().length()-21));
msbStatusBar->showMessage(strMsg);
return;
}
mbWaitingForReceive = true;
UpdateStatusBar();
return;
}
if (gtmrRecTimer.isValid())
{
//Stop timer and invalidate it
gtmrRecTimer.invalidate();
mtmrUpdateTimer.stop();
}
}
else if (mtbExecutionBlock.text().at(0) == ScriptingWaitTime)
{
//Wait for a specified period of time
mtmrPauseTimer.start(mtbExecutionBlock.text().right(mtbExecutionBlock.text().length()-1).toUInt());
mtbExecutionBlock = mtbExecutionBlock.next();
++mintCLine;
ucLastAct = ScriptingActionWaitTime;
UpdateStatusBar();
mtmrUpdateTimer.start(1000);
return;
}
else
{
//Comment line
ucLastAct = ScriptingActionOther;
}
}
else
{
//Blank line
ucLastAct = ScriptingActionOther;
}
UpdateStatusBar();
mtbExecutionBlock = mtbExecutionBlock.next();
++mintCLine;
}
//Means execution has finished
if (ui->spin_Repeats->value() != 0)
{
//Script repeating is enabled, check if we need to repeat the script
if (ui->spin_Repeats->value() == -1 || mnRepeats < ui->spin_Repeats->value())
{
//Repeat script and increment loop count
mintCLine = 0;
mtbExecutionBlock = ui->edit_Script->document()->firstBlock();
++mnRepeats;
//Clear data buffers
mbaRecvData.clear();
mbaMatchData.clear();
mbWaitingForReceive = false;
//Advance to the next (first) line
AdvanceLine();
return;
}
}
mintCLine = -1;
ui->edit_Script->SetExecutionLine(mintCLine);
mbIsRunning = false;
//Disable read only mode of editor
SetButtonStatus(true);
//Update status bar
QString strRepeatText;
if (mnRepeats > 0)
{
//Create text for repeat information
strRepeatText = QString(" with ").append(QString::number(mnRepeats)).append(" repeat").append(mnRepeats == 1 ? "" : "s").append(", ~");
double fElapsed = (double)gtmrScriptTimer.elapsed()/1000.0;
if (fElapsed == 0.0)
{
//Avoid division by zero
fElapsed = 1.0;
}
strRepeatText.append(QString::number(fElapsed/(double)mnRepeats, 'f', 1)).append(" seconds/loop");
}
msbStatusBar->showMessage(QString("Script complete after ~").append(QString::number(((double)gtmrScriptTimer.elapsed()/1000.0), 'f', 1)).append(" seconds").append(strRepeatText));
ui->progress_Complete->setValue(ui->progress_Complete->maximum());
gtmrScriptTimer.invalidate();
//Return window title
setWindowTitle("Scripting");
//Notify main form that script is no longer executing
emit ScriptFinished();
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Help_clicked(
)
{
//Display help
QString strMessage = "UwTerminalX Scripting: This is a simple scripting language for sending/receiving data and waiting for specific periods of time. Each line must begin directly with a valid command and the parameter for that command. Commands are:\r\n > Send data out\r\n < Wait to receive data\r\n ~ Wait for a period (in ms)\r\n // A null-operation comment (used for describing the code)\r\n\r\nValid commands will be highlighed in red and comments in green. Use the check button (yellow warning icon) to check for syntax errors in a script before running it.\r\n\r\nTo the left side of the editor are individual line colours which will change to indicate the following:\r\n Red: Syntax error with line (compile failed)\r\n Green: Currently executing line\r\n Black: Script execution failed on this line";
mFormAuto->SetMessage(&strMessage);
mFormAuto->show();
}
//=============================================================================
//=============================================================================
void
UwxScripting::SetUwTerminalXVersion(
const QString strVersion
)
{
//Update version string
mstrUwTerminalXVersion = strVersion;
}
//=============================================================================
//=============================================================================
bool
UwxScripting::CheckRecvMatchBuffers(
)
{
//Check if the receive buffer contains the match data
if (mbaRecvData.length() >= mbaMatchData.length())
{
//Length of receive buffer is greater than or equal to the match string, perform search
int intPos = mbaRecvData.indexOf(mbaMatchData);
if (intPos != -1)
{
//Data found
if (intPos < ui->spin_MaxRecBufSize->value())
{
//Position OK: shift array and progress to next line
mbaRecvData = mbaRecvData.right(mbaRecvData.length() - intPos - mbaMatchData.length());
mbWaitingForReceive = false;
return true;
}
else
{
//Text found but after buffer size limit, return failure
return false;
}
}
}
//Buffer doesn't contain requested data
return false;
}
//=============================================================================
//=============================================================================
void
UwxScripting::SerialPortWritten(
int iWritten
)
{
//Serial bytes have been written
if (mbIsRunning == true && ui->check_WaitForWrite->isChecked() == true)
{
//Remove from the expected number of bytes
mbBytesWriteRemain = mbBytesWriteRemain - iWritten;
if (mbBytesWriteRemain <= 0)
{
//Bytes have been fully written, advance to next line
mtbExecutionBlock = mtbExecutionBlock.next();
++mintCLine;
//Run the next line
AdvanceLine();
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Pause_toggled(
bool
)
{
//Pause status has been changed
if (mbIsRunning == true && !ui->btn_Pause->isChecked())
{
if (ucLastAct == ScriptingActionDataIn)
{
//Waiting for data to be received
AdvanceLine();
}
else if (ucLastAct == ScriptingActionDataOut)
{
//Waiting for data to be written
if (ui->check_WaitForWrite->isChecked() == true)
{
if (mbBytesWriteRemain <= 0)
{
//Bytes have been fully written, advance to next line
mtbExecutionBlock = mtbExecutionBlock.next();
++mintCLine;
//Run the next line
AdvanceLine();
}
}
else
{
//Recheck
AdvanceLine();
}
}
else if (ucLastAct == ScriptingActionWaitTime)
{
//Waiting for timer to end
if (!mtmrPauseTimer.isActive())
{
//Recheck
AdvanceLine();
}
}
else
{
//Recheck
AdvanceLine();
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::UpdateStatusBar(
)
{
//Updates status bar with current action
ui->progress_Complete->setValue((mintCLine-1)*100/mnScriptLines);
QString strPercent = QString::number(ui->progress_Complete->value()).append("%");
setWindowTitle(QString("Scripting (Running... ").append(strPercent).append(")"));
if (ucLastAct == ScriptingActionDataIn)
{
//Receiving data
double dblRecTimeSec = gtmrRecTimer.nsecsElapsed()/1000000000.0;
if ((int)dblRecTimeSec >= ui->spin_MaxRecTime->value())
{
//Time has expired
on_btn_Stop_clicked();
msbStatusBar->showMessage(QString("Script failed (expected data not found after ").append(ui->spin_MaxRecTime->text()).append(" seconds).").append((mnRepeats > 0 ? QString(" on repeat #").append(QString::number(mnRepeats)) : "")));
ui->edit_Script->SetExecutionLineStatus(true);
setWindowTitle("Scripting");
}
else
{
//Time left
msbStatusBar->showMessage(QString("#").append(QString::number(mintCLine+1)).append(": Waiting to receive data (").append(QString::number(mbaRecvData.length())).append(" bytes received in ").append(QString::number(dblRecTimeSec, 'f', 1)).append(" seconds)").append((mnRepeats > 0 ? QString(" with ").append(QString::number(mnRepeats)).append(" repeat").append(mnRepeats == 1 ? "" : "s") : "").append("... (").append(strPercent).append(")")));
}
}
else if (ucLastAct == ScriptingActionDataOut)
{
//Data output
if (ui->check_WaitForWrite->isChecked() == true)
{
//Sending data and waiting for it to be flushed
msbStatusBar->showMessage(QString("#").append(QString::number(mintCLine+1)).append(": Waiting to data to be flushed (").append(QString::number(mbBytesWriteRemain)).append(" bytes remaining)").append((mnRepeats > 0 ? QString(" with ").append(QString::number(mnRepeats)).append(" repeat").append(mnRepeats == 1 ? "" : "s") : "").append("... (").append(strPercent).append(")")));
}
else
{
//Sending data
msbStatusBar->showMessage(QString("#").append(QString::number(mintCLine+1)).append(": Outputting data... (").append(strPercent).append(")"));
}
}
else if (ucLastAct == ScriptingActionWaitTime)
{
//Wait period
msbStatusBar->showMessage(QString("#").append(QString::number(mintCLine)).append(": Wait period ").append(QString::number(mtmrPauseTimer.interval())).append("ms (").append(QString::number(mtmrPauseTimer.remainingTime())).append("ms left)").append((mnRepeats > 0 ? QString(" with ").append(QString::number(mnRepeats)).append(" repeat").append(mnRepeats == 1 ? "" : "s") : "").append("... (").append(strPercent).append(")")));
}
else
{
//Comment or blank line
msbStatusBar->showMessage(QString("#").append(QString::number(mintCLine+1)).append(": Comment/Unknown line (").append(strPercent).append(")"));
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::closeEvent(
QCloseEvent *ceClose
)
{
if (mbIsRunning == true)
{
//Script is running - ignore close event
ceClose->ignore();
}
else
{
//Accept close event
ceClose->accept();
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Options_clicked(
)
{
//Show options menu
gpOptionsMenu->popup(QCursor::pos());
}
//=============================================================================
//=============================================================================
void
UwxScripting::MenuSelected(
QAction *qaAction
)
{
//Menu item selected
int intItem = qaAction->data().toInt();
if (intItem == MenuActionChangeFont)
{
//Change font
ChangeFont();
}
else if (intItem == MenuActionExportStringPlayer)
{
//Export to string player
ExportToStringPlayer();
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::on_btn_Clear_clicked(
)
{
//Clears the editor
if (mbIsRunning == false)
{
//Check user really wants to lose all data
QMessageBox mbClearEditor;
mbClearEditor.setText("Are you sure you want to clear the editor contents? Unsaved changes will be lost.");
mbClearEditor.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
mbClearEditor.setDefaultButton(QMessageBox::No);
if (mbClearEditor.exec() == QMessageBox::Yes)
{
//Clear text
ui->edit_Script->clear();
ui->edit_Script->ClearBadLines();
mintCLine = -1;
ui->edit_Script->SetExecutionLine(mintCLine);
}
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::SetButtonStatus(
bool bStatus
)
{
//Change status of inputs
ui->edit_Script->setReadOnly(!bStatus);
ui->check_WaitForWrite->setEnabled(bStatus);
ui->spin_MaxRecBufSize->setEnabled(bStatus);
ui->spin_MaxRecTime->setEnabled(bStatus);
ui->btn_Run->setEnabled(bStatus);
ui->btn_Stop->setEnabled(!bStatus);
ui->btn_Clear->setEnabled(bStatus);
ui->btn_Compile->setEnabled(bStatus);
ui->btn_Load->setEnabled(bStatus);
ui->btn_Save->setEnabled(bStatus);
ui->btn_Options->setEnabled(bStatus);
}
//=============================================================================
//=============================================================================
void
UwxScripting::reject(
)
{
//Do not allow the dialog to be closed by pressing escape if a script is running
if (mbIsRunning == false)
{
//Allow close
QDialog::reject();
}
}
//=============================================================================
//=============================================================================
void
UwxScripting::SetEditorFocus(
)
{