-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerialWidget.cpp
639 lines (565 loc) · 21.5 KB
/
SerialWidget.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
#include "SerialWidget.h"
#include "ui_SerialWidget.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include<QTextLayout>
#include <QTextEdit>
#include <QScrollBar>
#include <QVector>
#include <QTimer>
#include <QSettings>
#include <string.h>
#define qout qDebug()
SerialWidget::SerialWidget(QWidget *parent) :
QDialog(parent),
ui(new Ui::SerialWidget)
{
minTextCurse = 0;
ui->setupUi(this);
activePort = nullptr;
ui->checkBox_caseSensitive->setCheckState(Qt::CheckState::Checked);
caseSensitive = Qt::CaseSensitive;
ui->tEdit_shell->installEventFilter(this);
ui->tEdit_shell->setHtml("<body bgcolor=\"#000000\"></body>");
ui->tEdit_shell->setTextColor("red");
ui->tEdit_shell->insertPlainText("Bottod Uart Shell V0.1\n");
ui->tEdit_shell->setFocus();
ui->checkBox_autoConect->setCheckState(Qt::CheckState::Checked);
// ui->tEdit_shell->setTextColor("red");
// history.resize(10);
quickComplets.append("@CMD.clean");
loadseting();
scanport();
minTextCurse = ui->tEdit_shell->textCursor().position();
overTimer.stop();
connect(&overTimer,SIGNAL(timeout()),this,SLOT(on_timerOver()));
// ui->tEdit_shell->setTextBackgroundColor("black");
ui->textEdit->setReadOnly(true);
ui->textEdit->setText("<font color='red' size=20><b>解决Linux中普通用户无权限访问串口设备问题</b></font>");
ui->textEdit->append("\n\n以root身份执行:\n"
"vim /etc/udev/rules.d/70-ttyusb.rules\n\n"
"内容为:\n"
R"(KERNEL=="ttyUSB[0-9]*",MODE="0666")");
}
SerialWidget::~SerialWidget()
{
saveseting();
if(activePort->isOpen())
{
activePort->clear();
activePort->close();
}
delete ui;
}
bool SerialWidget:: eventFilter(QObject* target,QEvent * event)
{
if(target == ui->tEdit_shell)
{
QTextCursor txtcur = ui->tEdit_shell->textCursor();
if(event->type()==QEvent::KeyPress)
{
if(ui->tEdit_shell->textCursor().position()< minTextCurse)
return true ;
QKeyEvent *k = static_cast<QKeyEvent *>(event);
if(k->key() == Qt::Key_Return || k->key() == Qt::Key_Enter)
{
txtcur.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
txtcur.setPosition(minTextCurse,QTextCursor::KeepAnchor);
QString msg = txtcur.selectedText();
if(history.isEmpty() || QString::compare(msg,history.back()) != 0)
history.append(msg);
if(msg.compare("@CMD.clean") == 0)
{
ui->tEdit_shell->setText("");
ui->tEdit_shell->setTextColor(ui->cBox_ColorList->currentText());
ui->tEdit_shell->setHtml("<body bgcolor=\"#000000\"></body>");
ui->tEdit_shell->append("clean");
minTextCurse = ui->tEdit_shell->textCursor().position();
// ui->tEdit_shell->setFocus();
}else
sendText(msg);
historyNum = history.size();
ui->tEdit_shell->append("");
txtcur.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
ui->tEdit_shell->setTextCursor(txtcur);
minTextCurse = ui->tEdit_shell->textCursor().position();
return true;
}else if (static_cast<QKeyEvent *>(event)->key() == Qt::Key_Up) {
QTextCursor tc = ui->tEdit_shell->textCursor();
if(history.size() == 0) return true;//如果没有历史记录,则不操作
tc.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
tc.setPosition(minTextCurse,QTextCursor::KeepAnchor);
tc.removeSelectedText();
if(historyNum == 0)
historyNum = history.size();
if(historyNum > history.size())
historyNum = 1;
ui->tEdit_shell->insertPlainText(history[historyNum-1]); //插入上一个输入的历史记录
lastTextCurse = ui->tEdit_shell->textCursor().position();
qout<<history[historyNum-1]<<"history size "<< history.length();
historyNum--;
qout<<"使用上一个记录"<<endl;
return true;
}else if (static_cast<QKeyEvent *>(event)->key() == Qt::Key_Down) {
QTextCursor tc = ui->tEdit_shell->textCursor();
if(history.size() == 0) return true;//如果没有历史记录,则不操作
tc.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
tc.setPosition(minTextCurse,QTextCursor::KeepAnchor);
tc.removeSelectedText();
if(historyNum > history.size())
historyNum = 1;
if(historyNum == 0)
historyNum = history.size();
ui->tEdit_shell->insertPlainText(history[historyNum-1]); //插入上一个输入的历史记录
lastTextCurse = ui->tEdit_shell->textCursor().position();
qout<<history[historyNum-1]<<"history size "<< history.length();
historyNum++;
qout<<"使用下一个记录"<<endl;
return true;
}else if (static_cast<QKeyEvent *>(event)->key() == Qt::Key_Tab) {
qout<<"tab"<<endl;
//得到最后一行的字符
QTextCursor txtcur = ui->tEdit_shell->textCursor();
txtcur.movePosition(QTextCursor::StartOfLine,QTextCursor::KeepAnchor);
QString msg = txtcur.selectedText();
int index = msg.lastIndexOf(' ');
if(index == -1) index = 0;else index++;
QString ins = msg.mid(index);
const QString insertStr = findQuickCompletString( ins);
if(insertStr != "")
{
txtcur = ui->tEdit_shell->textCursor();
txtcur.movePosition(QTextCursor::Left,QTextCursor::KeepAnchor,ins.length());
txtcur.removeSelectedText();
ui->tEdit_shell->insertPlainText(findQuickCompletString( msg.mid( msg.lastIndexOf(' ')+1)));
}
qout<<"ins :" <<ins <<endl;
return true;
}else if (static_cast<QKeyEvent *>(event)->key() == Qt::Key_Backspace) {
QTextCursor tc = ui->tEdit_shell->textCursor();
qout<<"back";
if(tc.position()<=minTextCurse)
{
qout << "delete over";
return true;
}
}else if(static_cast<QKeyEvent *>(event)->key() == Qt::Key_Left){
if(minTextCurse == ui->tEdit_shell->textCursor().position())
{
return true;
}
}
}
}
return QWidget::eventFilter(target,event);
}
void SerialWidget::sendText(QString & text)
{
// int indx;
for(int i = 0;i<text.length();i++)
{
if(text.at(i) == '\\' && (i+1)<text.length())
{
if(text.at(i+1) == '\\')
{
text.remove(i+1,1);
}else if(text.at(i+1) == 't') {
text.replace(i,1,'\t');
text.remove(i+1,1);
}else if (text.at(i+1) == 'n') {
text.replace(i,1,'\n');
text.remove(i+1,1);
}
}
}
text.append("\r\n");qout<<text<<endl;
qout<<"send has be called,will send string:"<<text<<endl;
activePort->write(text.toLocal8Bit());
// activePort->w
}
void SerialWidget:: scanport(void)
{
/* 新建串口类 */
if(activePort == nullptr)
{
activePort = new QSerialPort();}
if(activePort != nullptr)
{
/* 查找可用串口 */
if(activePort->isOpen())
{
ui->tLine_message->setText("请先关闭串口再扫描串口");
return;
}
ui->cBox_Portlist->clear();
foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
{
QSerialPort serial;
serial.setPort(info);
/* 判断端口是否能打开 */
if(serial.open(QIODevice::ReadWrite))
{
int isHaveItemInList = 0;
/* 判断是不是已经在列表中了 */
for(int i=0; i<ui->cBox_Portlist->count(); i++)
{
/* 如果,已经在列表中了,那么不添加这一项了就 */
if(QString::compare( ui->cBox_Portlist->itemData(i).toString(), serial.portName(),caseSensitive) == 0)
{
isHaveItemInList++;
}
}
qout<<"find a" << serial.portName() <<endl;
if(isHaveItemInList == 0)
{
ui->cBox_Portlist->addItem(serial.portName());
}
serial.close();
}
}
QString msg = "串口更新成功.共";
msg.append (QString::number( ui->cBox_Portlist->count()));
qDebug()<<ui->cBox_Portlist->count();
msg.append(" 个");
ui->tLine_message->setText(msg);
ui->cBox_Baudlist->setCurrentText("");
if(ui->checkBox_autoConect->checkState() == Qt::CheckState::Checked && ui->cBox_Portlist->count() == 1)
{
qout<<"auto conect";
ui->cBox_Portlist->setCurrentIndex(0);
openprot(ui->cBox_Portlist->currentText(),ui->cBox_autoBaud ->currentText().toInt());
qout<<ui->cBox_Baudlist->currentText();
}
}else
{
/* 串口没有初始化成功,先不处理异常 */
// 警告对话框
ui->tLine_message->setText("串口初始化失败");
}
}
void SerialWidget::on_tEdit_shell_cursorPositionChanged()
{
//do nothing;
if(ui->tEdit_shell->textCursor().position()<minTextCurse)
ui->tEdit_shell->setReadOnly(true);
else {
ui->tEdit_shell->setReadOnly(false);
}
}
void SerialWidget::on_pButton_send_clicked()
{
QTextCursor txtcur = ui->tEdit_shell->textCursor();
txtcur.movePosition(QTextCursor::End,QTextCursor::MoveAnchor);
txtcur.movePosition(QTextCursor::StartOfLine,QTextCursor::MoveAnchor);
txtcur.movePosition(QTextCursor::EndOfLine,QTextCursor::KeepAnchor);
QString msg = txtcur.selectedText();
if(history.isEmpty() || QString::compare(msg,history.back()) != 0)
history.append(msg);
sendText(msg);
historyNum = history.size();
ui->tEdit_shell->append("");
ui->tEdit_shell->setFocus();
}
void SerialWidget::on_pushButton_2_clicked()
{
openprot();
}
void SerialWidget::receiveInfo()
{
static int flag = 0;
qint64 recnum = activePort->readLine((receiverBuff+flag),2048);
if(recnum > 0)
{
qout<<"received:>"<<receiverBuff<<endl;
flag += recnum;
if(receiverBuff[flag-1] != '\n')
{
overTimer.stop();
overTimer.start(50);
// overTimer.setSingleShot(true);
return;
}
else
{
overTimer.stop();
overTimer.start(50);
}
}else {
return;
}
QString str = QString::fromLocal8Bit(receiverBuff);
qout<<"send msg";
ui->tEdit_shell->insertPlainText(str);
flag = 0;
QString nstr = str;
if(nstr.indexOf("QuickComplet:") == 0)
{
str.remove("QuickComplet:");
if(ui->plaintEdit_quickCompleat->textCursor().position()!= 0)
{
ui->plaintEdit_quickCompleat->insertPlainText(",\n");
}
QStringList strlist = nstr.split("\",\"");
for(int i = 0;i<strlist.size();i++)
{
bool isrepead = false;
if(i== 0) strlist[i].remove(0,strlist[i].indexOf("\"")+1);
if(i == (strlist.size()-1))
strlist[i].remove(strlist[i].lastIndexOf("\""),
strlist[i].length()-strlist[i].lastIndexOf("\""));
for(int j = 0;j<quickComplets.size();j++)
{
if(QString::compare( quickComplets[j],strlist[i],caseSensitive) == 0)
{
isrepead = true;break;
}
}
if(isrepead) continue;
quickComplets.append(strlist[i]);
ui->plaintEdit_quickCompleat->insertPlainText(strlist[i]);
if(i != (strlist.size()-1))
{
ui->plaintEdit_quickCompleat->insertPlainText(",\n");
}
qout<<"strlist["<<i<<"]:"<<strlist[i]<<endl;
}
ui->tEdit_shell->append("检测到快捷关键字.已添加\n");
}
minTextCurse = ui->tEdit_shell->textCursor().position();
// receiveBuff.clear();
// }else{
// if(overTimer.isActive()) overTimer.stop();
// overTimer.start(10);
// overTimer.setSingleShot(true);
// qout<<"timestar:"<<receiveBuff<<endl;
// connect(&overTimer,SIGNAL(timeout()),this,SLOT(on_timerOver()));
// }
qDebug()<<"receive info:"<<receiverBuff;
receiverBuff[0] = '\0';
}
void SerialWidget::openprot(const QString & portname,const int baud)
{
// if(activePort == nullptr)
// scanport();
if(activePort->isOpen()) //如果串口打开着就关闭
{
// activePort->clear();
qout<<"port close";
activePort->clear();
activePort->close();
// delete activePort;
ui->cBox_Portlist->setEnabled(true);
ui->cBox_Baudlist ->setEnabled(true);
ui->pushButton->setEnabled(true);
ui->pushButton_2->setText("打开串口");
ui->tLine_message->setText("串口"+ui->cBox_Portlist->currentText()+"已关闭");
}else{ //关闭着就打开
activePort->setPortName(portname);
if(activePort->open(QIODevice::ReadWrite)== true)
{
qout<<"port open";
activePort->setBaudRate(baud,QSerialPort::AllDirections);//设置波特率和读写方向
activePort->setDataBits(QSerialPort::Data8); //数据位为8位
activePort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
activePort->setParity(QSerialPort::NoParity); //无校验位
activePort->setStopBits(QSerialPort::OneStop); //一位停止位
ui->tLine_message->setText(ui->cBox_Portlist->currentText()+"打开成功");
connect(activePort,SIGNAL(readyRead()),this,SLOT(receiveInfo()));
ui->pushButton_2->setText("关闭串口");
ui->tEdit_shell->setFocus();
ui->cBox_Portlist->setEnabled(false);
ui->cBox_Baudlist ->setEnabled(false);
ui->pushButton->setEnabled(false);
}else {
ui->tLine_message->setText("打开失败,检查串口是否被占用");
ui->pushButton_2->setText("打开串口");
}
}
}
void SerialWidget::openprot()
{
SerialWidget::openprot(ui->cBox_Portlist->currentText(),ui->cBox_Baudlist->currentText().toInt());
}
void SerialWidget::on_pushButton_clicked()
{
scanport();
}
void SerialWidget::on_tEdit_shell_textChanged()
{
QScrollBar *qbar = ui->tEdit_shell->verticalScrollBar();
qbar->setValue(qbar->maximum());
}
const QString & SerialWidget::findQuickCompletString(const QString & str)
{
int retindex = -1;
for(int i = 0;i<quickComplets.size();i++)
{
qout<<"find quitck index :" << i<<"quickComplets[i].indexOf("<<str<<") == "<<quickComplets[i].indexOf(str,0,caseSensitive) <<endl;
if(quickComplets[i].indexOf(str,0,caseSensitive) == 0)
{
if(retindex == -1)
retindex = i;
else {
retindex = -1;
break;
}
}
}
if(retindex == -1)
return emptyStr;
else
return quickComplets[retindex];
}
void SerialWidget::on_timerOver(void)
{
qout<<"timerOver"<<endl;
if(receiverBuff[0] != '\0')
{
QTextCursor tc = ui->tEdit_shell->textCursor();
tc.movePosition(QTextCursor::End);
ui->tEdit_shell->setTextCursor(tc);
ui->tEdit_shell->insertPlainText( QString::fromLocal8Bit(receiverBuff));
minTextCurse = ui->tEdit_shell->textCursor().position();
}else {
QByteArray rec = activePort->readAll();
QString str = QString::fromLocal8Bit(rec);
QTextCursor tc = ui->tEdit_shell->textCursor();
tc.movePosition(QTextCursor::End);
ui->tEdit_shell->setTextCursor(tc);
ui->tEdit_shell->insertPlainText(str);
minTextCurse = ui->tEdit_shell->textCursor().position();
}
// if(! receiveBuff.isEmpty())
// {
// qout<<"resc"<<receiveBuff<<endl;
// QTextCursor tc = ui->tEdit_shell->textCursor();
// tc.movePosition(QTextCursor::End);
// ui->tEdit_shell->setTextCursor(tc);
// ui->tEdit_shell->insertPlainText(receiveBuff);
// receiveBuff.clear();
// minTextCurse = ui->tEdit_shell->textCursor().position();
// }
overTimer.stop();
}
void SerialWidget::on_cBox_ColorList_currentTextChanged(const QString &arg1)
{
qout<<"change str"<<arg1<<endl;
ui->tEdit_shell->setTextColor(arg1);
QTextCursor tc = ui->tEdit_shell->textCursor();
tc.movePosition(QTextCursor::End);
// ui->tEdit_shell->setTextCursor(tc);
ui->tEdit_shell->insertPlainText("text color change :"+arg1+"\n");
minTextCurse = ui->tEdit_shell->textCursor().position();
}
void SerialWidget::on_pButton_AddquickCompelat_clicked()
{
QString plaintext = ui->plaintEdit_quickCompleat->toPlainText();
plaintext.remove('\n');
plaintext.remove(' ');
qout<<"plaintext"<<plaintext;
QStringList sliplist = plaintext.split(',');
//插入到快捷补全的数组中去.
for(int i = 0;i<sliplist.size();i++)
{
bool is_exist = false;
if(sliplist[i].size() == 0) continue;
for(int j = 0;j<quickComplets.size();j++)
{
if(QString::compare(sliplist[i],quickComplets[j],caseSensitive) == 0)
{
qout<<"检测到"<<sliplist[i]<<"重复"<<endl;
is_exist = true;
break;
}
}
if(is_exist == true)
continue;
else {
quickComplets.append(sliplist[i]);
}
}
}
void SerialWidget::on_serialErrorOccured()
{
qout<<"error serial "<<endl;
if(activePort->isOpen())
openprot();
}
void SerialWidget::on_SerialWidget_destroyed()
{
qout<<"关闭"<<endl;
}
void SerialWidget::saveseting(void)
{
QSettings setting("BottodSerialShell","BottodSerialShell");
setting.setValue("isAutosive",1);
setting.setValue("iscaseSensitive",caseSensitive);
setting.setValue("textcolor",ui->cBox_ColorList->currentText());
setting.setValue("defaultBaud",ui->cBox_autoBaud ->currentText());
setting.setValue("autoConnect",ui->checkBox_autoConect->checkState());
setting.sync();
}
void SerialWidget::loadseting(void)
{
QSettings setting("BottodSerialShell","BottodSerialShell");
if(setting.value("isAutosive").toInt() == 0)
return ;
if(setting.value("iscaseSensitive").toInt() == 1)
{
caseSensitive = Qt::CaseSensitive;
ui->checkBox_caseSensitive->setCheckState(Qt::CheckState::Checked);
}else
{
caseSensitive = Qt::CaseInsensitive;
ui->checkBox_caseSensitive->setCheckState(Qt::CheckState::Unchecked);
}
if(setting.value("autoConnect").toInt() == 0)
{
ui->checkBox_autoConect->setCheckState(Qt::CheckState::Unchecked);
}else
{
ui->checkBox_autoConect->setCheckState(Qt::CheckState::Checked);
}
ui->tEdit_shell->setTextColor(setting.value("textcolor").toString());
ui->cBox_ColorList->setCurrentText(setting.value("textcolor").toString());
ui->tEdit_shell->setTextColor(ui->cBox_ColorList->currentText());
ui->cBox_autoBaud ->setCurrentText(setting.value("defaultBaud").toString());
ui->cBox_Baudlist->setCurrentText(setting.value("defaultBaud").toString());
setting.setValue("isAutosive",1);
setting.sync();
}
void SerialWidget::on_tabWidget_currentChanged(int index)
{
qout<<"index"<<index;
if(index == 1)
{
//reflash quick complet list
QString listStr = "";
for(int i = 0;i<quickComplets.size();i++)
{
listStr.append(quickComplets[i]+",\n");
}
listStr.remove( listStr.lastIndexOf(','),1);
ui->plaintEdit_quickCompleat->clear();
ui->plaintEdit_quickCompleat->setPlainText(listStr);
//reflash over
}
}
void SerialWidget::on_pButton_delquickCompelat_clicked()
{
QString selecttext = ui->plaintEdit_quickCompleat->textCursor().selectedText() ;
selecttext.remove(' ');
selecttext.remove(',');
selecttext.remove('\n');
quickComplets.remove( quickComplets.indexOf(selecttext),1);
ui->plaintEdit_quickCompleat->textCursor().removeSelectedText();
}
void SerialWidget::on_checkBox_caseSensitive_stateChanged(int arg1)
{
if(arg1== 0)
caseSensitive = Qt::CaseInsensitive;
else {
caseSensitive = Qt::CaseSensitive;
}
}