-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.cpp
More file actions
485 lines (421 loc) · 13.8 KB
/
Copy pathapp.cpp
File metadata and controls
485 lines (421 loc) · 13.8 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
#include "app.h"
#include "ui_app.h"
using nlohmann::json;
void to_json(json &j, const AppCfg cfg)
{
j["serPort"] = cfg.serPort;
j["baud"] = cfg.baud;
j["bytesize"] = cfg.bytesizeIdx;
j["stopIdx"] = cfg.stopIdx;
j["parityIdx"] = cfg.parityIdx;
j["isASCII"] = cfg.isASCII;
qInfo("To Json is OK");
}
void from_json(const json &j, AppCfg &cfg)
{
if (j.contains("serPort"))
j.at("serPort").get_to(cfg.serPort);
if (j.contains("baud"))
j.at("baud").get_to(cfg.baud);
if (j.contains("bytesize"))
j.at("bytesize").get_to(cfg.bytesizeIdx);
if (j.contains("stopIdx"))
j.at("stopIdx").get_to(cfg.stopIdx);
if (j.contains("parityIdx"))
j.at("parityIdx").get_to(cfg.parityIdx);
if (j.contains("isASCII"))
j.at("isASCII").get_to(cfg.isASCII);
qInfo("From Json is OK");
}
App::App(QWidget *parent)
: QWidget(parent)
, ui(new Ui::App)
{
ui->setupUi(this);
scanPort();
initAppCfg();
initUI();
initThread();
initTimer();
connectSignal();
}
void App::connectSignal()
{
// 连接/断开
connect(ui->pushButton, &QPushButton::clicked, this, [this](bool isCheck) {
if (isCheck) {
ui->pushButton->setChecked(false);
// 检查串口配置是否有效(是否为空)
if (ui->comboBox->currentText().isEmpty()) {
QMessageBox::warning(this, "串口打开失败", QString("串口号为空!请填入串口号再试"));
return;
}
if (ser.isOpen()) {
qInfo("Serial already open");
return;
}
int index = ui->comboBox->currentIndex();
uint32_t baud = ui->comboBox_2->currentText().toUInt();
serial::bytesize_t bytesize = (serial::bytesize_t)ui->comboBox_3->currentText().toInt();
serial::stopbits_t stopbits = (serial::stopbits_t)ui->comboBox_4->currentText().toInt();
serial::parity_t parity = (serial::parity_t)ui->comboBox_5->currentIndex();
serial::Timeout timeout = serial::Timeout::simpleTimeout(SERIAL_TIMEOUT_MS);
ser.setPort(allPorts[index].port);
ser.setBaudrate(baud);
ser.setBytesize(bytesize);
ser.setStopbits(stopbits);
ser.setParity(parity);
ser.setTimeout(timeout);
try {
ser.open();
} catch(const serial::IOException &e) {
ui->pushButton->setChecked(false);
QMessageBox::warning(this, "串口连接出错", QString("串口可能被占用, 错误代码:\n%1").arg(e.what()));
return;
}
qInfo("Serial open");
ui->pushButton->setText("关闭串口");
setEnPortEdit(false);
printLog("串口已连接");
ui->pushButton->setChecked(true);
} else {
ui->pushButton->setChecked(true);
if (ser.isOpen()) {
std::lock_guard<std::mutex> _lock(serMutex);
ser.close();
}
setEnPortEdit(true);
qInfo("Serial close");
ui->pushButton->setText("打开串口");
printLog("串口关闭");
ui->pushButton->setChecked(false);
}
});
// 发送
connect(ui->pushButton_2, &QPushButton::clicked, this, [this]() {
if (!ser.isOpen()) {
QMessageBox::warning(this, "发送失败", QString("串口未连接"));
return;
}
std::string sendStr;
QString displayStr;
// ASCII
if (ui->radioButton->isChecked()) {
sendStr = ui->textEdit->toPlainText().toStdString();
displayStr ="[ASC]: " + ui->textEdit->toPlainText();
// HEX
} else if (ui->radioButton_2->isChecked()) {
QStringList hexStrList = ui->textEdit->toPlainText().split(" ");
QString originalString;
displayStr = "[HEX]:";
for (const QString &hex : hexStrList) {
bool ok = false;
uchar value = hex.toUShort(&ok, 16);
if (hex.isEmpty()) {
continue;
} else if (hex.size() > 2) {
ok = false;
}
if (!ok) {
QMessageBox::warning(this, "发送失败", QString("发送数据有误\n[%1]无法解析为HEX").arg(hex));
return;
}
originalString.append(value);
displayStr += QString(" %1").arg(static_cast<int>(value), 2, 16, QChar('0')).toUpper(); // "01"
}
sendStr = originalString.toStdString();
}
std::lock_guard<std::mutex> _lock(sendMutex);
sendMsg.append(sendStr);
QTime currentTime = QTime::currentTime();
QString curTimeStr = currentTime.toString("hh:mm:ss.zzz");
displayStr = curTimeStr + " 发送: <br>" + displayStr;
ui->textBrowser->append(QString("<span style='color: blue;'>%1</span>").arg(displayStr));
});
// 清空
connect(ui->pushButton_3, &QPushButton::clicked, this, [this]() {
ui->textBrowser->clear();
});
connect(ui->textEdit, &QTextEdit::textChanged, this, [this]() {
QString text = ui->textEdit->toPlainText();
if (!text.isEmpty() && text.back().cell() == '\n') {
ui->pushButton_2->click();
}
if (!ui->radioButton_2->isChecked()) {
return;
}
QTextCursor cursor = ui->textEdit->textCursor();
// HEX文本检测和格式化
QString fText;
QString errChar;
char cIdx = 0;
for (auto &c : text) {
if (c == ' ') {
continue;
} else if ((c < '0' || c > '9') &&
(c < 'A' || c > 'F') &&
(c < 'a' || c > 'f')) {
errChar += c;
QToolTip::showText(QCursor::pos(), QString("<span style='color: red;'>%1</span>").arg("[HEX]模式下,只能输入十六进制文本(错误的输入:%1)").arg(errChar), this, QRect());
continue;
}
if (cIdx == 2) {
fText += ' ';
cIdx = 0;
}
fText += c.toUpper();
cIdx += 1;
}
ui->textEdit->blockSignals(true);
ui->textEdit->setText(fText);
ui->textEdit->blockSignals(false);
cursor.movePosition(QTextCursor::End);
ui->textEdit->setTextCursor(cursor);
});
}
void App::initTimer()
{
QTimer *_time1 = new QTimer(this);
connect(_time1, &QTimer::timeout, this, &App::update);
_time1->start(UI_PERIOD_MS);
}
void App::initThread()
{
std::thread _writeThread(&App::writeSerial, this);
std::thread _readThread(&App::readSerial, this);
_writeThread.detach();
_readThread.detach();
}
void App::updateScanPort()
{
static int scanCnt = 0;
if (scanCnt <= SLEEP_PERIOD_MS(1000)) {
++scanCnt;
return;
}
scanCnt = 0;
scanPort();
}
void App::scanPort()
{
allPorts = serial::list_ports();
bool _isRescan = false;
if (allPorts.size() != allPortsDesc.size()) {
_isRescan = true;
} else {
for (int i = 0; i < allPorts.size(); ++i) {
serial::PortInfo &port = allPorts[i];
if (port.port != allPortsDesc[i].toStdString()) {
_isRescan = true;
break;
}
}
}
if (!_isRescan) {
return;
}
allPortsDesc.clear();
ui->comboBox->clear();
for (serial::PortInfo &port : allPorts) {
QString portName = QString::fromStdString(port.port);
allPortsDesc.push_back(portName);
}
QStringList strL = QStringList::fromVector(allPortsDesc);
ui->comboBox->addItems(strL);
}
void App::initUI()
{
// 设置 QTextBrowser 支持 HTML 格式
ui->textBrowser->setHtml("");
ui->comboBox->setCurrentText(QString::fromStdString(appCfg.serPort));
ui->comboBox_2->setCurrentText(QString::number(appCfg.baud));
ui->comboBox_3->setCurrentIndex(appCfg.bytesizeIdx);
ui->comboBox_4->setCurrentIndex(appCfg.stopIdx);
ui->comboBox_5->setCurrentIndex(appCfg.parityIdx);
ui->radioButton->setChecked(appCfg.isASCII);
}
App::~App()
{
qInfo("Delete Serial App");
delete ui;
}
void App::setEnPortEdit(bool isEn)
{
ui->comboBox->setEnabled(isEn);
ui->comboBox_2->setEnabled(isEn);
ui->comboBox_3->setEnabled(isEn);
ui->comboBox_4->setEnabled(isEn);
ui->comboBox_5->setEnabled(isEn);
}
void App::writeSerial()
{
while (true) {
if (!ser.isOpen()) {
std::this_thread::sleep_for(std::chrono::milliseconds(THREAD_PERIOD_MS));
continue;
}
if (sendMsg.empty()) {
std::this_thread::sleep_for(std::chrono::milliseconds(THREAD_PERIOD_MS));
continue;
}
std::lock_guard<std::mutex> _lock(sendMutex);
try {
ser.write(sendMsg);
} catch(const serial::IOException &e) {
qWarning("Serial write error: %s", e.what());
}
sendMsg.clear();
}
}
void App::readSerial()
{
while (true) {
std::this_thread::sleep_for(std::chrono::milliseconds(THREAD_PERIOD_MS));
if (!ser.isOpen()) {
continue;
}
std::string _recvStr;
{
std::lock_guard<std::mutex> _lock(serMutex);
try {
_recvStr = ser.read(200);
} catch(const serial::IOException &e) {
qWarning("Serial read error: %s", e.what());
ser.close();
int retryCnt = 0;
while (!ser.isOpen() && retryCnt < 10) {
try {
printLog(QString("串口异常关闭,正在尝试重新连接...(%1/10)").arg(retryCnt + 1));
ser.open();
} catch(const serial::IOException &e) {
qWarning("Serial reopen error: %s", e.what());
} catch(const std::exception &e) {
qWarning("Serial reopen error: %s", e.what());
}
std::this_thread::sleep_for(std::chrono::seconds(1));
++retryCnt;
}
if (ser.isOpen()) {
printLog("串口重新连接成功!");
} else {
printLog("串口重新连接失败,请检查串口状态!");
}
continue;
}
}
if (_recvStr.empty()) {
continue;
}
{
std::lock_guard<std::mutex> _lock(recMutex);
receiveMsg.append(_recvStr);
}
}
}
void App::update()
{
updateScanPort();
updateUI();
autosave();
}
void App::updateUI()
{
if (receiveMsg.empty()) {
return;
}
QString displayStr;
// ASCII
if (ui->radioButton->isChecked()) {
displayStr = "[ASC]: " + QString::fromStdString(receiveMsg);
// HEX
} else if (ui->radioButton_2->isChecked()) {
displayStr = "[HEX]: " + stringToHexStr(receiveMsg);
}
QTime currentTime = QTime::currentTime();
QString curTimeStr = currentTime.toString("hh:mm:ss.zzz");
displayStr = curTimeStr + " 接收: <br>" + displayStr;
ui->textBrowser->append(QString("<span style='color: green;'>%1</span>").arg(displayStr));
std::lock_guard<std::mutex> _lock(recMutex);
receiveMsg.clear();
}
// 暂未使用
void App::updateSerSta()
{
if (ser.isOpen()) {
ui->pushButton->setChecked(true);
ui->pushButton->setText("关闭串口");
setEnPortEdit(false);
} else {
ui->pushButton->setChecked(false);
ui->pushButton->setText("打开串口");
setEnPortEdit(true);
}
}
QString App::stringToHexStr(std::string str)
{
QString data = QString::fromStdString(str);
QByteArray array = data.toUtf8();
QString hexString = array.toHex();
QString spacedHexString;
for (int i = 0; i < hexString.size(); i += 2) {
spacedHexString.append(hexString.mid(i, 2));
if (i < hexString.size() - 2) {
spacedHexString.append(" ");
}
}
return spacedHexString.toUpper();
}
void App::printLog(QString msg)
{
ui->textBrowser->append(QString("<span style='color: #cdcdcd;'>%1</span>").arg("[log]:" + msg));
}
void App::initAppCfg()
{
std::ifstream ifile(CONFIG_PATH);
if (!ifile.is_open()) {
autosave(true);
return;
}
json j;
try {
j = json::parse(ifile);
} catch(const nlohmann::json::exception& e) {
QMessageBox::critical(this, "配置文件出错",QString("配置文件可能被外部修改出错, 已恢复默认配置\n(错误代码:%1)").arg(e.what()));
autosave(true);
}
ifile.close();
if (!j.is_null()) {
appCfg = j;
}
}
/// @brief 当配置被修改后,自动保存
/// @param isForce 强制保存(缺省默认为false)
void App::autosave(bool isForce)
{
static int cnt = 0;
static AppCfg _prev = appCfg;
if (isForce) {
goto FORCE_SAVE;
}
if (++cnt <= AUTO_SAVE_PERIOD_MS_CNT) {
return;
}
FORCE_SAVE:
cnt = 0;
appCfg.serPort = ui->comboBox->currentText().toStdString();
appCfg.baud = ui->comboBox_2->currentText().toInt();
appCfg.bytesizeIdx = ui->comboBox_3->currentIndex();
appCfg.stopIdx = ui->comboBox_4->currentIndex();
appCfg.parityIdx = ui->comboBox_5->currentIndex();
appCfg.isASCII = ui->radioButton->isChecked();
if (_prev == appCfg) {
return;
}
_prev = appCfg;
json j = appCfg;
std::ofstream ofile(CONFIG_PATH);
if (ofile.is_open()) {
ofile << j/*.dump(4)*/ << std::endl;
ofile.close();
}
}