-
Notifications
You must be signed in to change notification settings - Fork 10
/
mainwindow.cpp
529 lines (471 loc) · 14.6 KB
/
mainwindow.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
#include "mainwindow.h"
#include "drivers/libusb.h"
#include "mutualtest.h"
#include <QDateTime>
#include <QDebug>
#include <QScrollBar>
#include <QSerialPortInfo>
#include <QTextCodec>
#include <QTimer>
#include <QWebChannel>
#include <QMessageBox>
#define INDEX_LINE_LF 0
#define INDEX_LINE_CRLF 1
#define INDEX_LINE_CR 2
#define INDEX_LINE_NONE 3
#define INDEX_SEND_UTF8 0
#define INDEX_SEND_BIG5 1
#define INDEX_SEND_GB18030 2
#define INDEX_SEND_SHIFTJIS 3
#define INDEX_SEND_HEX 4
#define INDEX_SEND_BASE64 5
#define INDEX_SEND_PERCENT 6
#define INDEX_RECV_UTF8 0
#define INDEX_RECV_BIG5 1
#define INDEX_RECV_GB18030 2
#define INDEX_RECV_SHIFTJIS 3
#define INDEX_RECV_HEX 4
void JsInterface::sendBytes(const QJsonArray& dat) const {
QJsonArray::const_iterator itrArray = dat.begin();
QByteArray aryBytes;
while( itrArray != dat.end() ) {
aryBytes.append(static_cast<char>(itrArray->toInt()));
itrArray++;
}
parentWindow->sendBytes(aryBytes);
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
setupUi(this);
ports = SerialPort::getAvailablePorts(this);
serialPortComboBox->clear();
for (auto port : ports) {
serialPortComboBox->addItem(port->portName());
connect(port, SIGNAL(receivedData(QByteArray)), this,
SLOT(onDataReceived(QByteArray)));
connect(port, SIGNAL(breakChanged(bool)), this, SLOT(onBreakChanged(bool)));
}
loadSettings();
bytesRecv = 0;
bytesSent = 0;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(onIdle()));
timer->start(100);
inputPlainTextEdit->installEventFilter(this);
webEngineView->load(QUrl("qrc:/resources/index.html"));
QWebChannel* channel = new QWebChannel(webEngineView);
JsInterface* intf = new JsInterface(this);
webEngineView->page()->setWebChannel(channel);
channel->registerObject(QString("interface"), intf);
statisticsLabel = new QLabel(this);
statusBar()->addPermanentWidget(statisticsLabel);
onReset(); // reset and show statistics
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(refreshStatistics()));
timer->start(250);
playIcon = QIcon(":/resources/play.svg");
stopIcon = QIcon(":/resources/stop.svg");
isOpened = false;
refreshOpenStatus();
}
inline int fromHex(char ch) {
if ('0' <= ch && ch <= '9') {
return ch - '0';
} else if ('a' <= ch && ch <= 'f') {
return ch - 'a' + 10;
} else if ('A' <= ch && ch <= 'F') {
return ch - 'A' + 10;
} else {
return -1;
}
}
inline QString toHumanRate(quint64 rate) {
if (rate < 1024) {
return QString("%1 B/s").arg(rate);
} else if (1024 <= rate && rate < 1024 * 1024) {
return QString("%1 KiB/s").arg(1.0 * rate / 1024, 0, 'f', 2);
} else if (1024 * 1024 <= rate && rate < 1024 * 1024 * 1024) {
return QString("%1 MiB/s").arg(1.0 * rate / 1024 / 1024, 0, 'f', 2);
} else {
return "really??";
}
}
void MainWindow::refreshStatistics() {
quint64 txspeed = 0;
for (auto pair : sentRecord) {
txspeed += pair.first;
}
quint64 rxspeed = 0;
for (auto pair : recvRecord) {
rxspeed += pair.first;
}
qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
while (!sentRecord.isEmpty() &&
sentRecord.first().second < currentTime - 1000) {
sentRecord.pop_front();
}
while (!recvRecord.isEmpty() &&
recvRecord.first().second < currentTime - 1000) {
recvRecord.pop_front();
}
auto txt = QString("TX: %1 (%2) RX: %3 (%4)")
.arg(bytesSent)
.arg(toHumanRate(txspeed))
.arg(bytesRecv)
.arg(toHumanRate(rxspeed));
statisticsLabel->setText(txt);
}
void MainWindow::sendBytes(const QByteArray& data) {
auto serialPort = ports[serialPortComboBox->currentIndex()];
if (!serialPort->isOpen()) {
return;
}
serialPort->sendData(data);
bytesSent += data.length();
qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
sentRecord.push_back(QPair<quint64, qint64>(data.length(), currentTime));
}
void MainWindow::onSend() {
onOpen();
auto text = inputPlainTextEdit->toPlainText();
auto codec = QTextCodec::codecForName("UTF-8");
auto textData = codec->fromUnicode(text);
QByteArray data;
bool isFirst;
int currentByte;
switch (sendParseAsComboBox->currentIndex()) {
case INDEX_SEND_UTF8:
// text utf-8
data = textData;
break;
case INDEX_SEND_BIG5:
// text big5
codec = QTextCodec::codecForName("Big5");
data = codec->fromUnicode(text);
break;
case INDEX_SEND_GB18030:
// text gb18030
codec = QTextCodec::codecForName("GB18030");
data = codec->fromUnicode(text);
break;
case INDEX_SEND_SHIFTJIS:
// text shift-jis
codec = QTextCodec::codecForName("Shift-JIS");
data = codec->fromUnicode(text);
break;
case INDEX_SEND_HEX:
// hex
isFirst = true;
currentByte = 0;
for (auto ch : textData) {
if (ch == ' ' || ch == '\r' || ch == '\n') {
continue;
}
if (ch == 'x' || ch == 'X') {
if (isFirst == false && currentByte == 0) {
// 0x
isFirst = true;
continue;
} else {
// fail
break;
}
}
int cur = fromHex(ch);
if (cur == -1) {
statusBar()->showMessage("Invalid hex");
return;
}
if (isFirst) {
currentByte = cur;
isFirst = false;
} else {
currentByte = (currentByte << 4) + cur;
data.append(currentByte);
isFirst = true;
}
}
if (!isFirst) {
statusBar()->showMessage("Invalid hex");
return;
}
break;
case INDEX_SEND_BASE64:
// base64
data = QByteArray::fromBase64(textData);
break;
case INDEX_SEND_PERCENT:
// percent encoding
data = QByteArray::fromPercentEncoding(textData);
break;
default:
// never happens
break;
}
if (sendParseAsComboBox->currentIndex() != INDEX_SEND_HEX) {
// no line ending in hex mode
switch (lineEndingComboBox->currentIndex()) {
case INDEX_LINE_LF:
// lf
data.append('\n');
break;
case INDEX_LINE_CRLF:
// cr lf
data.append('\r');
data.append('\n');
break;
case INDEX_LINE_CR:
// cr
data.append('\r');
break;
default:
// none
break;
}
}
if (echoCheckBox->isChecked()) {
if (sendShowTimeCheckBox->isChecked()) {
text = QString("[%1] %2")
.arg(QDateTime::currentDateTime().toString(Qt::ISODate))
.arg(text);
}
appendText(text, Qt::green);
}
sendBytes(data);
inputPlainTextEdit->setFocus();
}
inline char toHex(int value) {
if (0 <= value && value <= 9) {
return '0' + value;
} else if (10 <= value && value <= 15) {
return 'A' + value - 10;
} else {
return '?';
}
}
void MainWindow::onDataReceived(QByteArray data) {
bytesRecv += data.length();
qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
recvRecord.push_back(QPair<quint64, qint64>(data.length(), currentTime));
QString text;
QTextCodec *codec;
switch (recvShowAsComboBox->currentIndex()) {
case INDEX_RECV_UTF8:
// text utf-8
codec = QTextCodec::codecForName("UTF-8");
text = codec->toUnicode(data);
break;
case INDEX_RECV_BIG5:
// text big5
codec = QTextCodec::codecForName("Big5");
text = codec->toUnicode(data);
break;
case INDEX_RECV_GB18030:
// text gb18030
codec = QTextCodec::codecForName("GB18030");
text = codec->toUnicode(data);
break;
case INDEX_RECV_SHIFTJIS:
// text shift-jis
codec = QTextCodec::codecForName("Shift-JIS");
text = codec->toUnicode(data);
break;
case INDEX_RECV_HEX:
// hex
for (auto byte : data) {
text += toHex((byte & 0xF0) >> 4);
text += toHex(byte & 0x0F);
text += ' ';
}
break;
default:
// never happens
break;
}
appendText(text, Qt::red);
}
void MainWindow::appendText(QString text, QColor color) {
QString arr;
const ushort *s = text.utf16();
while (*s != 0) {
arr += QString("%1").arg(*s);
arr += ',';
s++;
}
fitTerminal();
QString js = QString("term.write(String.fromCharCode(") + arr + QString("));");
webEngineView->page()->runJavaScript(js);
if (recvShowTimeCheckBox->isChecked()) {
if (!textBrowser->toPlainText().endsWith('\n')) {
text = QString("\n") + text;
}
text.replace("\n", QString("\n[%1] ")
.arg(QDateTime::currentDateTime().toString(Qt::ISODate)));
}
auto cursor = textBrowser->textCursor();
cursor.movePosition(QTextCursor::End);
textBrowser->setTextCursor(cursor);
textBrowser->setTextColor(color);
textBrowser->insertPlainText(text);
textBrowser->verticalScrollBar()->setValue(textBrowser->verticalScrollBar()->maximum());
}
void MainWindow::onReset() {
bytesRecv = 0;
bytesSent = 0;
recvRecord.clear();
sentRecord.clear();
refreshStatistics();
}
void MainWindow::onIdle() {
struct timeval tv = {};
libusb_handle_events_timeout_completed(context, &tv, nullptr);
}
void MainWindow::refreshOpenStatus() {
auto serialPort = ports[serialPortComboBox->currentIndex()];
if (!isOpened) {
statusBar()->showMessage("");
serialPortComboBox->setEnabled(true);
baudRateComboBox->setEnabled(true);
dataBitsComboBox->setEnabled(true);
parityComboBox->setEnabled(true);
stopBitsComboBox->setEnabled(true);
flowControlComboBox->setEnabled(true);
sendButton->setText("Open and Send");
breakPushButton->setEnabled(false);
openCloseButton->setText("Open");
openCloseButton->setIcon(playIcon);
} else {
serialPortComboBox->setEnabled(false);
baudRateComboBox->setEnabled(false);
dataBitsComboBox->setEnabled(false);
parityComboBox->setEnabled(false);
stopBitsComboBox->setEnabled(false);
flowControlComboBox->setEnabled(false);
sendButton->setText("Send");
breakPushButton->setEnabled(true);
openCloseButton->setText("Close");
openCloseButton->setIcon(stopIcon);
}
}
void MainWindow::onOpen() {
auto serialPort = ports[serialPortComboBox->currentIndex()];
if (!isOpened) {
if (serialPort->open()) {
isOpened = true;
serialPort->setBaudRate(baudRateComboBox->currentText().toInt());
serialPort->setDataBits(
(QSerialPort::DataBits)dataBitsComboBox->currentText().toInt());
QSerialPort::Parity parity[] = {
QSerialPort::NoParity, QSerialPort::EvenParity,
QSerialPort::OddParity, QSerialPort::SpaceParity,
QSerialPort::MarkParity};
QString parityName[] = {"U", "N", "E", "O", "S", "M"};
serialPort->setParity(parity[parityComboBox->currentIndex()]);
serialPort->setStopBits(
(QSerialPort::StopBits)(stopBitsComboBox->currentIndex() + 1));
serialPort->setFlowControl(
(QSerialPort::FlowControl)flowControlComboBox->currentIndex());
statusBar()->showMessage(tr("%1 %2-%3%4%5-%6 Open")
.arg(serialPort->portName())
.arg(serialPort->getBaudRate())
.arg(dataBitsComboBox->currentText())
.arg(parityName[serialPort->getParity() + 1]) // getParity() may return -1
.arg(stopBitsComboBox->currentText())
.arg(flowControlComboBox->currentText()));
refreshOpenStatus();
saveSettings();
// set focus to corresponding widget upon connection
onTabPageChanged(tabWidget->currentIndex());
} else {
statusBar()->showMessage("Failed");
}
}
}
void MainWindow::onClose() {
auto serialPort = ports[serialPortComboBox->currentIndex()];
if (isOpened) {
isOpened = false;
serialPort->close();
refreshOpenStatus();
}
}
void MainWindow::onToggleOpen() {
if (isOpened) {
onClose();
} else {
onOpen();
}
}
void MainWindow::onBreak() {
auto serialPort = ports[serialPortComboBox->currentIndex()];
uint time = breakDurationLineEdit->text().toInt();
serialPort->triggerBreak(time);
}
void MainWindow::onBreakChanged(bool set) {
if (set) {
appendText("BREAK ON", Qt::blue);
} else {
appendText("BREAK OFF", Qt::blue);
}
}
void MainWindow::onClear() {
textBrowser->setPlainText("");
webEngineView->page()->runJavaScript(QString("if (term) term.clear();"));
}
void MainWindow::onMutualTest() {
MutualTest test;
test.exec();
}
bool MainWindow::eventFilter(QObject *object, QEvent *event) {
if (object == inputPlainTextEdit && event->type() == QEvent::KeyPress) {
QKeyEvent *key = (QKeyEvent *)event;
if (key->key() == Qt::Key_Return && key->modifiers() == Qt::ShiftModifier) {
onSend();
inputPlainTextEdit->selectAll();
return true;
}
}
return QMainWindow::eventFilter(object, event);
}
void MainWindow::fitTerminal() {
webEngineView->page()->runJavaScript(QString("if (term) term.fit();"));
}
void MainWindow::onTabPageChanged(int index) {
settings.setValue("tabPane", index);
if (index == tabWidget->indexOf(tab_term)) {
fitTerminal();
webEngineView->setFocus();
webEngineView->page()->runJavaScript(QString("if (term) term.focus();"));
} else if (index == tabWidget->indexOf(tab_text)) {
inputPlainTextEdit->setFocus();
}
}
void MainWindow::resizeEvent(QResizeEvent* event)
{
QMainWindow::resizeEvent(event);
// resize after the size change has propagated into the WebView
QTimer::singleShot(100, this, &MainWindow::fitTerminal);
}
void MainWindow::saveSettings() {
settings.setValue("baud", baudRateComboBox->currentText().toInt());
settings.setValue("dataBits", (QSerialPort::DataBits)dataBitsComboBox->currentText().toInt());
settings.setValue("parity", parityComboBox->currentIndex());
settings.setValue("stopBits", stopBitsComboBox->currentIndex());
settings.setValue("flowControl", flowControlComboBox->currentIndex());
settings.setValue("deviceName", serialPortComboBox->currentText());
}
void MainWindow::loadSettings() {
int baud = settings.value("baud", 115200).toInt();
baudRateComboBox->setCurrentText(QString::number(baud));
int dataBits = settings.value("dataBits", 8).toInt();
dataBitsComboBox->setCurrentText(QString::number(dataBits));
parityComboBox->setCurrentIndex(settings.value("parity", 0).toInt());
stopBitsComboBox->setCurrentIndex(settings.value("stopBits", 0).toInt());
flowControlComboBox->setCurrentIndex(settings.value("flowControl", 0).toInt());
QString name = settings.value("deviceName").toString();
for (int i = 0; i < serialPortComboBox->count(); i++) {
if (serialPortComboBox->itemText(i) == name) {
serialPortComboBox->setCurrentIndex(i);
}
}
tabWidget->setCurrentIndex(settings.value("tabPane", 0).toInt());
}