工作上自己自学的Qt开发的一个较为简单,但是使用了常用方法的上位机,当时苦于找不到相应的demo来学习,所以现在开源整个项目,下面直接上代码,不懂的可以直接私信。
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCharts>
#include <QMessageBox>
#include "mysocket.h"
#include "myserialport.h"
#include <QStringList>
#include <QTcpSocket>
#include <QMetaObject>
#include <QMetaType>
#include <QThread>
#include "serialportthread.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QByteArray SerialportRecrivebuff;
void Charts_Init(QVector<double> xValues,QVector<double> yValues,double a,double b,double c);
void Charts_Init2(QVector<double> xValues,QVector<double> yValues,QVector<double> x1Values,QVector<double> y1Values,double a,double b,double c);
QVector<uint16_t> TypeConverter(QByteArray data);
signals:
void SendserialportData(QByteArray data);
void SendsocketData(QByteArray data);
// void Send__Datas(QByteArray data);
private slots:
void on_strat_clicked();
void on_rease_clicked();
void on_comcheck_clicked();
void on_strat_2_clicked();
void on_strat_3_clicked();
void on_LeastSquare_clicked();
void on_openFile_clicked();
void on_clearChart_clicked();
void on_save_clicked();
void on_REBOOT_clicked();
void on_CLOSE_clicked();
void on_saveExcel_clicked();
void on_sendCMD_clicked();
void on_pushButtons_clicked();
void timerOver();
void timerOver2();
void on_sendCMD_2_clicked();
void on_sendCMD_5_clicked();
void on_CAN_BTN_clicked();
void on_RS422_BTN_clicked();
void on_SPI_BTN_clicked();
void on_SSI_BTN_clicked();
private:
Ui::MainWindow *ui;
// myserialport * Myserial;
SerialportThread * Myserial;
Mysocket * socketusing ;
QByteArray SSI = {"AA 01 12 00 11 2A 88 23 03 01 02 0C 04"};
QByteArray CAN = {"AA 01 00 00 0F 42 40 00 02 00 01 10 00"};
QByteArray RS422 = {"AA 01 01 00 09 60 00 04 05 03 02 0F 00"};
QByteArray SPI = {"AA 01 03 00 11 2A 88 10 02 00 01 0F 00"};
QByteArray Begin= {"AA 02"};
QByteArray Stop = {"AA 03"};
QByteArray Once = {"AA 04"};
QByteArray name;
QByteArray MyserialData;
QByteArray MysocketData;
QString MyserialData_str;
QString MysocketData_str;
QStringList Datalist;
QThread *serialThread;
QString Txtdata;
QVector<double> xValues;
QVector<double> yValues;
QVector<uint16_t> MyValues;
QVector<double> savedata;
QTimer *timer;
QTimer *timer2;
QVector<double> VOLTdata;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "mysocket.h"
#include "mythreadpool.h"
#include "myserialport.h"
#include "qcustomplot.h"
#include "serialportthread.h"
#include <QtAlgorithms>
#include <algorithm>
#include <QThreadPool>
#include <QtSerialPort/QSerialPort> //提供访问串行端口的功能
#include <QtSerialPort/QSerialPortInfo>
#include <QByteArray>
#include <QString>
#include <QVector>
#include <QTimer>
#include <QFile>
#include <QFileDialog>
#include <windows.h>
#include <QList>
#define PowerID "RIGOL TECHNOLOGIES,DP831A,DP8A242800304,00.01.16\n"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
this->setWindowIcon(QIcon(":/qier"));
this->setWindowTitle("Test System By Kirmot");
this->ui->lcdNumber->setStyleSheet("color:red");
this->ui->lcdNumber_2->setStyleSheet("color:red");
//this->ui->IPline->setText("192.168.1.8"); //万用表
this->ui->IPline->setText("192.168.1.6"); //电源
this->ui->PORTline->setText("5555");
this->ui->strat_3->setDisabled(true);
this->ui->rease->setDisabled(true);
QList<QSerialPortInfo> comList = QSerialPortInfo::availablePorts();
for(int i = 0; i < comList.size(); i ++)
{ ui->cominfobox->addItem(comList[i].portName());
// ui->cominfobox->addItem(comList[i].description());//设备描述
}
// qDebug() << "UI thread ID: " << QThread::currentThreadId();
ui->CustomPlot->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
ui->CustomPlot_2->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::Charts_Init(QVector<double> xValues,QVector<double> yValues,
double a,double b,double c)
{
ui->CustomPlot->addGraph();
ui->CustomPlot->graph(0)->setPen(QPen(Qt::red));
ui->CustomPlot->graph(0)->setBrush(QBrush(QColor(255,0,0,20)));
ui->CustomPlot->graph(0)->setData(xValues, yValues);
ui->CustomPlot->graph(0)->setName("角度曲线");// 设置图例名
// 为坐标轴添加标签
ui->CustomPlot->xAxis->setLabel("数量");
ui->CustomPlot->yAxis->setLabel("角度值");
// 设置坐标轴的范围,以看到所有数据
ui->CustomPlot->xAxis->setRange(a, b);
ui->CustomPlot->yAxis->setRange(a, c);
ui->CustomPlot->legend->setVisible(true); // 显示图例
// 重画图像
ui->CustomPlot->replot();
}
void MainWindow::Charts_Init2(QVector<double> xValues,QVector<double> yValues,
QVector<double> x1Values,QVector<double> y1Values,double a,double b,double c)
{
ui->CustomPlot_2->addGraph();
ui->CustomPlot_2->graph(0)->setPen(QPen(Qt::green));
ui->CustomPlot_2->graph(0)->setBrush(QBrush(QColor(0,255,0,80)));
ui->CustomPlot_2->graph(0)->setData(xValues, yValues);
ui->CustomPlot_2->graph(0)->setName("数据曲线");// 设置图例名
ui->CustomPlot_2->addGraph();
ui->CustomPlot_2->graph(1)->setPen(QPen(Qt::red));
ui->CustomPlot_2->graph(1)->setBrush(QBrush(QColor(0,0,255,50)));
ui->CustomPlot_2->graph(1)->setData(x1Values, y1Values);
ui->CustomPlot_2->graph(1)->setName("拟合曲线");// 设置图例名
// 为坐标轴添加标签
ui->CustomPlot_2->xAxis->setLabel("数量");
ui->CustomPlot_2->yAxis->setLabel("角度值");
// 设置坐标轴的范围,以看到所有数据
ui->CustomPlot_2->xAxis->setRange(a, b);
ui->CustomPlot_2->yAxis->setRange(a, c);
ui->CustomPlot_2->legend->setVisible(true); // 显示图例
ui->CustomPlot_2->replot();
}
void MainWindow::on_strat_clicked()//串口确认
{
ui->rease->setDisabled(false);
ui->strat->setDisabled(true);
name = (ui->cominfobox->currentText()).toUtf8();
Myserial = new SerialportThread(name,this);
Myserial->start();
connect(this,&MainWindow::SendserialportData,Myserial,[=](QByteArray data){
//Myserial->SendData(data);
QMetaObject::invokeMethod(Myserial, "SendData",
Qt::QueuedConnection,Q_ARG(QByteArray,data));//跨线程调用
});
connect(Myserial,&SerialportThread::ReceiveData,this,[=](QByteArray data){
MyserialData.append(data);
},Qt::QueuedConnection);
SendserialportData("AA 10");
}
void MainWindow::on_rease_clicked()//串口选择取消
{
ui->rease->setDisabled(true);
ui->strat->setDisabled(false);
Myserial->deleteLater();
}
void MainWindow::on_comcheck_clicked()//传感器数据采集
{
// QByteArray RecD = MyserialData.toHex().toUpper();
// if( RecD == "04D2")
// {
MyserialData.clear();
SendserialportData(Begin);
timer2 = new QTimer(this);
timer2->setInterval(10000);
connect(timer2, SIGNAL(timeout()), this, SLOT(timerOver2()));
timer2->start();
// }
}
void MainWindow::timerOver2()
{ ui->comcheck->setEnabled(true);
SendserialportData(Stop);
timer2->stop();
disconnect(timer2, SIGNAL(timeout()), this, SLOT(timerOver2()));
QByteArray shch = MyserialData;
QVector<uint16_t> value ;
value = TypeConverter(MyserialData);
MyValues = TypeConverter(shch);
MyserialData.clear();
if(MyValues.isEmpty())
{ QMessageBox::information(NULL,"提示","Myvalues无数据",QMessageBox::Yes); }
else
{this->on_LeastSquare_clicked();}
}
void MainWindow::on_strat_2_clicked()//socket 初始化
{
this->ui->strat_3->setDisabled(false);
QString ip = ui->IPline->text();
quint16 port = ui->PORTline->text().toUShort();
socketusing = new Mysocket(ip,port);
connect(this,&MainWindow::SendsocketData,socketusing,[=](QByteArray data){
socketusing->SendDatas(data);
},Qt::QueuedConnection);//发送数据
connect(socketusing,&Mysocket::Rece_Datas,this,[=](QByteArray data){
// qDebug()<<"Socket :"<<data;
MysocketData .append( data ) ;
// qDebug()<<"MysocketData :"<<data;
},Qt::QueuedConnection);//接收数据
if(socketusing->connectStaions==true)
{
ui->strat_2->setDisabled(true);
}
}
void MainWindow::on_strat_3_clicked()//socket断开连接
{
if(socketusing!=nullptr)
{
socketusing->deleteLater();
ui->strat_2->setDisabled(false);
}
}
void MainWindow::on_openFile_clicked()//读取本地文件的数据
{
QFile file;
QString fileName = QFileDialog::getOpenFileName(this);
file.setFileName(fileName);
file.open(QIODevice::ReadOnly | QIODevice::Text|QIODevice::WriteOnly);
QByteArray datas,framedata ;
datas= file.readAll();
QList<QByteArray> framelist,bytelist;
bytelist = datas.split(' ');
for(int i=0;i<bytelist.size();i+=4)
{
foreach (QByteArray ba, (bytelist.mid(i,4)))
{
framedata += ba;
}
if (framedata.startsWith("AA"))
{
framelist.append(framedata);
}
framedata.clear();
}
for (const QByteArray &frame : framelist)
{
QByteArray hexData = frame.mid(2, 2)+ frame.mid(4, 2);
QByteArray hexData1 = frame.mid(2, 2); //H
QByteArray hexData2 = frame.mid(4, 2); //L
QByteArray checkData = frame.mid(6, 2); // check
uint16_t uint16Value = hexData.toUShort(nullptr, 16);
uint16_t uint16Value1 = hexData1.toUShort(nullptr, 16);
uint16_t uint16Value2 = hexData2.toUShort(nullptr, 16);
uint16_t sumV = uint16Value1 + uint16Value2;
sumV = static_cast<uint8_t>(sumV);
uint16_t CheckValue = checkData.toUShort(nullptr, 16);
uint8_t CheckValue_8 = static_cast<uint8_t>(CheckValue);
if(sumV == CheckValue_8)
{
MyValues.append(uint16Value);
// qDebug() << QString("0x%1").arg(uint16Value, 4, 16, QLatin1Char('0'));}
}
// uint16_t CheckValue = checkData.toUShort(nullptr, 16);
// if((uint16Value1+uint16Value2)==CheckValue)
// {
// MyValues.append(uint16Value);
// // qDebug() << QString("0x%1").arg(uint16Value, 4, 16, QLatin1Char('0'));}
// }
}
ui->LeastSquare->setDisabled(false);
}
void MainWindow::on_LeastSquare_clicked() //算法处理 图像显示
{
ui->CustomPlot->clearPlottables();
ui->CustomPlot->clearItems();
ui->CustomPlot_2->clearPlottables();
ui->CustomPlot_2->clearItems();
ui->CustomPlot->replot();
ui->CustomPlot_2->replot();
QVector<uint16_t> datax = MyValues;
MyValues.clear();
for(auto it = datax.begin(); it != datax.end(); ++it)
{
double value = static_cast<double>(*it); // 类型转换
yValues.append(value);
}
QVector<double> X,Y;
Y = yValues;
int size = Y.size();
X.resize(size);
std::iota(X.begin(),X.end(),1);//元素赋值 递增值为1
Charts_Init(X,Y,0,100000,17000);
// QVector<double> doubleVecX = xValues;
QVector<double> doubleVecY = yValues;
double start_index = 0;
double max_index = 0;
//int count = 0;
double max_value = *std::max_element(doubleVecY.begin(), doubleVecY.end());//取最大值
for(auto i = 1;i<doubleVecY.size();i++)
{
if(doubleVecY[i-1] == 0 && doubleVecY[i] > 0 && doubleVecY[i+1] >= doubleVecY[i])
{
start_index = static_cast<double>(i);
}
if(doubleVecY[i]==max_value)
{
max_index = static_cast<double>(i);
}
if(max_index<start_index)
{
max_index = 0;
}
if(max_index>start_index)
{
break;
}
}
int start_int = static_cast<int>(start_index);
int max_int = static_cast<int>(max_index);
QVector<double> doubleVecY2 = doubleVecY.mid(start_int,(max_int-start_int));
int sizes = doubleVecY2.size();
xValues.resize(sizes);
std::iota(xValues.begin(),xValues.end(),1);
// qDebug()<<"start:"<<start_int<<"max:"<<max_int;
// qDebug()<<"size:"<<sizes;
savedata = doubleVecY2;
LeastSquaresTask *task = new LeastSquaresTask(xValues,doubleVecY2);
QThreadPool::globalInstance()->start(task); //启动线程池
// Charts_Init2(xValues,doubleVecY2);
QThread::msleep(100);
if(task->isfinshed)
{
task->slope();
task->intercept();
task->isfinshed = false;
qDebug()<<"斜率:"<<task->slope()<<"截距:"<<task->intercept();
}
double s = task->slope();
double m = task->intercept();
ui->LeastSquare->setDisabled(true);
//y = sk+m
int num = max_int-start_int;
QVector<double> x(num), y(num);
for(int i=0;i<num;i++)
{
x[i]=i;
y[i]=s*x[i]+m;
}
Charts_Init2(xValues,doubleVecY2,x,y,0,10000,17000);
ui->lcdNumber->display(s);
ui->lcdNumber_2->display(m);
MyValues.clear();
yValues.clear();
}
void MainWindow::on_clearChart_clicked()//图像清除
{
ui->CustomPlot->clearGraphs();
ui->CustomPlot_2->clearGraphs();
ui->CustomPlot->clearItems();
ui->CustomPlot_2->clearItems();
ui->CustomPlot->replot();
ui->CustomPlot_2->replot();
}
void MainWindow::on_save_clicked() //保存文件
{
QFileDialog fileDialog;
QString fileName = fileDialog.getSaveFileName(this,tr("保存文件到"),"/Receivedata",tr(" File(*.txt)"));
if(fileName == "")
{
return;
}
QFile file(fileName);//可以自己选择路径来保存文件名
if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::warning(this,tr("错误"),tr("打开文件失败"));
return;
}
else
{
QTextStream textStream(&file);
for (int i = 0; i < savedata.size(); i++)
{
textStream << savedata[i] << "\n";
}
QMessageBox::warning(this,tr("提示"),tr("保存文件成功"));
file.close();
}
}
void MainWindow::on_REBOOT_clicked()//重启
{
QString program = QApplication::applicationFilePath();
QStringList arguments = QApplication::arguments();
QString workingDirectory = QDir::currentPath();
QProcess::startDetached(program, arguments, workingDirectory);
QApplication::exit();
exit(0);
}
void MainWindow::on_CLOSE_clicked() //关闭
{
this->close();
}
void MainWindow::on_saveExcel_clicked()//保存Excel
{
CoInitialize(NULL); //初始化COM库
MyThreadpool * taskofExcel = new MyThreadpool();
QThreadPool::globalInstance()->start(taskofExcel); //启动线程池
connect(taskofExcel,&MyThreadpool::finshed,[](){
CoUninitialize();
});
}
void MainWindow::on_sendCMD_clicked()//电压连续自动测试
{
this->ui->sendCMD->setDisabled(true);
qDebug()<<"Test begin!";
this->SendsocketData(":CONFigure:VOLTage:DC 20,MAX\n");
// this->SendsocketData(":CONF:VOLT:DC 20,6.0E-5\n");
QThread::msleep(50);
this->SendsocketData("VOLT:DC:NPLC 0.02\n");
QThread::msleep(50);
this->SendsocketData(":SAMPle:COUNt 2500\n");
// this->SendsocketData(":SAMPle:COUNt 50\n");
QThread::msleep(50);
this->SendsocketData(":INIT\n");
QThread::msleep(50);
this->SendsocketData(":SYST:BEEP\n");
this->SendsocketData(":FETCh?\n");
timer = new QTimer(this);
timer->setInterval(14000);
connect(timer, SIGNAL(timeout()), this, SLOT(timerOver()));
timer->start();
MysocketData.clear();
}
void MainWindow::timerOver() //电压数据处理 图像绘制
{
this->ui->sendCMD->setDisabled(false);
qDebug()<<"定时时间到";
timer->stop();
// qDebug()<<"VOLTdata:"<<VOLTdata;
// QVector<double> s = VOLTdata;
// QMetaObject::invokeMethod(socketusing, "ReceDatas", Qt::QueuedConnection,
// Q_ARG(QByteArray,data));//跨线程调用
QList<QByteArray> Voltlist;
Voltlist = MysocketData.split(',');
//QByteArray b = MysocketData;
for(auto i=Voltlist.begin();i!=Voltlist.end();i++)
{
// QString ms = QString::fromUtf8((*i).mid(0,6));
QString ms = QString::fromUtf8(*i);
// QList<QString>Stlist = ms.split('e');
double sm = ms.toDouble();
// double sm = QString((*i).mid(0,6)).toDouble();
VOLTdata.append(sm);
}
Voltlist.clear();
ui->CustomPlot->clearPlottables();
ui->CustomPlot->clearItems();
ui->CustomPlot_2->clearPlottables();
ui->CustomPlot_2->clearItems();
ui->CustomPlot->replot();
ui->CustomPlot_2->replot();
QVector<double>X,Y;
int size = VOLTdata.size();
Y = VOLTdata;
savedata = VOLTdata;
X.resize(size);
std::iota(X.begin(),X.end(),1);//元素赋值 递增值为1
Charts_Init(X,Y,0,2600,5.5);
int start=0,last=0;
// QVector<double>c = VOLTdata;
for(int index = 0;index < VOLTdata.size();index++)
{
if (VOLTdata.at(index)<0.04)
{
start = index;
}
if(VOLTdata.at(index)>4.52)
{
last = index;
}
if(start>last)
{
last = 0;
}
if(last>start && start!=0)
{
break;
}
}
QVector<double> UsingDt = VOLTdata.mid(start,(last-start));//一个周期
QVector<double> emptX;
int ofsize = UsingDt.size();
emptX.resize(ofsize);
std::iota(emptX.begin(),emptX.end(),1);
LeastSquaresTask *task2 = new LeastSquaresTask(emptX,UsingDt);
QThreadPool::globalInstance()->start(task2); //启动线程
QThread::msleep(100);
if(task2->isfinshed)
{
task2->slope();
task2->intercept();
task2->isfinshed = false;
qDebug()<<"斜率:"<<task2->slope()<<"截距:"<<task2->intercept();
}
double s = task2->slope();
double m = task2->intercept();
ofsize++;
QVector<double> x1(ofsize), y1(ofsize);
for(int i=0;i<ofsize;i++)
{
x1[i]=i;
y1[i]=s*x1[i]+m;
}
Charts_Init2(emptX,UsingDt,x1,y1,0,100,5.5);
ui->lcdNumber->display(s);
ui->lcdNumber_2->display(m);
VOLTdata.clear();
MysocketData.clear();
}
QVector<uint16_t> MainWindow::TypeConverter(QByteArray data)//数据类型转换函数
{
QVector<uint16_t> value;
QByteArray datas = data.toHex().toUpper();
QByteArray angleData = datas;
qDebug()<<"datas:"<<datas;
QByteArray framedata;
QList<QByteArray> framelist;
//如果遇到掉数 会扔掉一帧正确的数据帧 =1时不会扔掉 但是可能是错误数据 校验会扔掉
int StartIndex = 1;
int Oindex = 0,Nindex = 0;
for(int i=0;i<angleData.size();i++)
{
Nindex = angleData.indexOf("AA",StartIndex);
if((Nindex-Oindex)== 8 ||(Nindex-Oindex)== 0 ||(Nindex-Oindex)== 1)//等于0是第一个
{
framedata = angleData.mid(Nindex,8);
if(framedata.startsWith("AA"))
{
framelist.append(framedata);
}
framedata.clear();
}
Oindex = Nindex;
StartIndex++;
while(Nindex == -1)
break;
}
// 缺陷:会导致正确帧识别错误 如AA201A3AAA201A3A 识别为AAA201A3
// AA5555AAAA5555AA 识别为AA5555AA AAAA5555(丢掉)
// int STARTindex=1;
// int index = 0;
// for(int i=0;i<angleData.size();i++)
// {
// index = angleData.indexOf("AA",StartIndex);
// framedata = angleData.mid(index,8);
// if (framedata.startsWith("AA"))
// {
// framelist.append(framedata);
// }
// framedata.clear();
// STARTindex++;
// while(index==-1)
// { break;}
// }
// for(int i=0;i<i<angleData.size();i+=8)//每8个字节分割一次 中间掉数就会出问题
// {
// QByteArray data = angleData.mid(i,8);
// if(data.startsWith("AA"))
// {framelist.append(data);}
// data.clear();
// }
// QList<QByteArray> framelist2 = framelist.mid(10000,9999);
// QList<QByteArray> framelist3 = framelist.mid(20000,9999);
// QList<QByteArray> framelist4 = framelist.mid(30000,9999);
// qDebug()<<"bytelist:"<<bytelist;
// qDebug()<<"framelist:"<<framelist;
for (const QByteArray &frame : framelist)
{
QByteArray hexData = frame.mid(2, 2)+ frame.mid(4, 2);//sum
QByteArray hexData1 = frame.mid(2, 2); //H
QByteArray hexData2 = frame.mid(4, 2); //L
QByteArray checkData = frame.mid(6, 2); // check
uint16_t uint16Value = hexData.toUShort(nullptr, 16);
uint16_t uint16Value1 = hexData1.toUShort(nullptr, 16);
uint16_t uint16Value2 = hexData2.toUShort(nullptr, 16);
uint16_t CheckValue = checkData.toUShort(nullptr, 16);
uint16_t sumV = uint16Value1 + uint16Value2;
uint8_t sumV8 = static_cast<uint8_t>(sumV);
uint8_t CheckValue_8 = static_cast<uint8_t>(CheckValue);
//qDebug()<<sumV<<""<<CheckValue_8;
if(sumV8 == CheckValue_8 )
{
if(uint16Value < 16383)
{
value.append(uint16Value);
// qDebug() << QString("0x%1").arg(uint16Value, 4, 16, QLatin1Char('0'));
}
}
}
return value;
}
void MainWindow::on_pushButtons_clicked() //发送指令
{
if(ui->radioButton->isChecked())
{
QString CMD = ui->lineEdit->text();
QByteArray CMDQ = CMD.toUtf8();
CMDQ.append("\n");
this->SendsocketData(CMDQ);
//this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_2->isChecked())
{
QString CMD2 = ui->lineEdit_2->text();
QByteArray CMDQ2 = CMD2.toUtf8();
CMDQ2.append("\n");
this->SendsocketData(CMDQ2);
// this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_3->isChecked())
{
QString CMD3 = ui->lineEdit_3->text();
QByteArray CMDQ3 = CMD3.toUtf8();
CMDQ3.append("\n");
this->SendsocketData(CMDQ3);
this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_4->isChecked())
{
QString CMD4 = ui->lineEdit_4->text();
QByteArray CMDQ4 = CMD4.toUtf8();
CMDQ4.append("\n");
this->SendsocketData(CMDQ4);
this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_5->isChecked())
{
QString CMD5 = ui->lineEdit_5->text();
QByteArray CMDQ5 = CMD5.toUtf8();
CMDQ5.append("\n");
this->SendsocketData(CMDQ5);
this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_6->isChecked())
{
QString CMD6 = ui->lineEdit_6->text();
QByteArray CMDQ6 = CMD6.toUtf8();
CMDQ6.append("\n");
this->SendsocketData(CMDQ6);
this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_7->isChecked())
{
QString CMD7 = ui->lineEdit_7->text();
QByteArray CMDQ7 = CMD7.toUtf8();
CMDQ7.append("\n");
this->SendsocketData(CMDQ7);
this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_8->isChecked())
{
QString CMD8 = ui->lineEdit_8->text();
QByteArray CMDQ8 = CMD8.toUtf8();
CMDQ8.append("\n");
this->SendsocketData(CMDQ8);
this->SendsocketData(":SYST:BEEP:IMM\n");
// this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_9->isChecked())
{
QString CMD9 = ui->lineEdit_9->text();
QByteArray CMDQ9 = CMD9.toUtf8();
CMDQ9.append("\n");
this->SendsocketData(CMDQ9);
this->SendsocketData(":SYST:BEEP:IMM\n");
// this->SendsocketData(":SYST:BEEP\n");
}
if(ui->radioButton_10->isChecked())
{
QString CMD10 = ui->lineEdit_10->text();
QByteArray CMDQ10 = CMD10.toUtf8();
CMDQ10.append("\n");
this->SendsocketData(CMDQ10);
this->SendsocketData(":SYST:BEEP:IMM\n");
// this->SendsocketData(":SYST:BEEP\n");
}
}
void MainWindow::on_sendCMD_2_clicked()//电源指令
{
SendsocketData(":SYST:BEEP:IMM\n");
SendsocketData(":CURR:PROT 1\n"); //ch1 过流保护 1A
SendsocketData(":CURR:PROT:STAT ON\n");//打开过流保护
SendsocketData(":APPL CH1,5,1\n"); //选择通道1 设置电压5v 电流1a
SendsocketData(":OUTP CH1,ON\n"); //开启通道1输出
}
void MainWindow::on_sendCMD_5_clicked()//电压筛选
{
if(1)
{
SendsocketData(":INST CH1\n"); //选择通道1
SendsocketData(":TIME:GROUP 20\n"); //设置输出组数 20组
SendsocketData(":TIME:CYCLE N,2\n"); //设置定时器循环数 20
SendsocketData(":TIME:ENDS LAST\n"); //设置终止状态 最后一组
SendsocketData(":TIME:TEMP:SEL SINE\n"); //选择模板 Sine
SendsocketData(":TIME:TEMP:OBJ V,1\n"); //选择编辑对象为电压 并设置电流为1A
SendsocketData(":TIME:TEMP:MAXV 5\n"); //最大值
SendsocketData(":TIME:TEMP:MINV 0\n"); //最小值
SendsocketData(":TIME:TEMP:POINT 20\n"); //设置点数
SendsocketData(":TIME:TEMP:INTE 3\n"); //时间间隔5s
SendsocketData(":TIME:TEMP:INVE OFF\n"); //打开反相
SendsocketData(":TIME:TEMP:SEL UP\n"); //模板类型为阶梯上升
SendsocketData(":TIME:TEMP:CONST\n"); //构建定时器参数
SendsocketData(":MEM:STOR RTF,1\n"); //保存定时参数到内部
SendsocketData(":OUTP CH1,ON\n"); //打开CH1的输出
SendsocketData(":TIME ON\n"); //打开定时输出
SendsocketData(":SYST:BEEP:IMM\n");
}
if(0)
{
SendsocketData(":INST CH1\n");
SendsocketData(":DELAY:GROUP 20\n");
SendsocketData(":DELAY:CYCLE N,20\n");
SendsocketData(":DELAY:ENDS LAST\n");
SendsocketData(":DELAY:STAT:GEN 10P\n");
SendsocketData(":DELAY:TIME:GEN INC,2,5\n");
SendsocketData(":DELAY:STOP >V,5\n");
SendsocketData(":MEM:STOP RDF,1\n");
SendsocketData(":OUTP CH1,ON\n");
SendsocketData(":DELAY ON\n");
SendsocketData(":SYST:BEEP:IMM\n");
}
if(0)
{
SendsocketData(":TRIG:SOUR BUS\n"); //软件触发
SendsocketData(":TRIG:DEL 3\n"); //延时时间3S
SendsocketData(":SOUR1:VOLT:TRIG 5\n");//触发电压5v
SendsocketData(":SOUR1:CURR:TRIG 1\n");//触发电流1A
SendsocketData(":INIT\n");
SendsocketData("*TRG\n");
SendsocketData(":SYST:BEEP:IMM\n");
}
}
void MainWindow::on_CAN_BTN_clicked()//传感器接口CAN
{
SendserialportData(CAN);
}
void MainWindow::on_RS422_BTN_clicked()//422接口
{
SendserialportData(RS422);
}
void MainWindow::on_SPI_BTN_clicked()//spi接口
{
SendserialportData(SPI);
}
void MainWindow::on_SSI_BTN_clicked()//ssi接口
{
SendserialportData(SSI);
}
SerialportThread.h
#ifndef SERIALPORTTHREAD_H
#define SERIALPORTTHREAD_H
#include <QObject>
#include <QString>
#include <QThread>
#include <QtSerialPort/QSerialPort>
class SerialportThread : public QThread
{
Q_OBJECT
public:
explicit SerialportThread(QString name,QObject *parent = nullptr);
~SerialportThread();
void run() override;
bool connectStaion = false;
signals:
void ReceiveData(QByteArray data);
public slots:
void SendData(QByteArray data);
void FromData();
private:
QSerialPort * serialThread;
};
#endif // SERIALPORTTHREAD_H
SerialportThread.cpp
#include "serialportthread.h"
#include <QMessageBox>
#include <QDebug>
SerialportThread::SerialportThread(QString name,QObject *parent)
{
serialThread = new QSerialPort(name,parent);
serialThread->setBaudRate(256000);
serialThread->setDataBits(QSerialPort::Data8);
serialThread->setStopBits(QSerialPort::OneStop);
serialThread->setParity(QSerialPort::NoParity);
serialThread->setFlowControl(QSerialPort::NoFlowControl);
serialThread->setReadBufferSize(0);
bool satte = serialThread->open(QIODevice::ReadWrite);
if(!satte)
{
QMessageBox::critical(NULL,"提示","无法打开串口,请检查是否被占用。",QMessageBox::Yes);
return;
}
else
{
QMessageBox::information(NULL,"提示","串口已经连接",QMessageBox::Yes);
}
//qDebug()<<"Serial ID:"<<QThread::currentThread();
}
SerialportThread::~SerialportThread()
{
if (serialThread) {
serialThread->close();
delete serialThread;
serialThread = nullptr;
}
}
void SerialportThread::run()
{
QObject::connect(serialThread,&QSerialPort::readyRead,this,[this](){
qint64 bytelen = serialThread->bytesAvailable();
if(bytelen<1)
{
qDebug()<<"串口无数据接收";
return;
}
QByteArray Receivebuff = serialThread->readAll();
// qDebug()<<"SerialReceive:"<<Receivebuff;
emit ReceiveData(Receivebuff);
});
// exec();
// while (!isInterruptionRequested()) {
// if (serialThread->bytesAvailable() < 1) {
// msleep(50); // 没有数据,等待一段时间
// continue;
// }
// QByteArray data = serialThread->readAll();
// // 处理接收到的数据...
// emit ReceiveData(data);
// qDebug()<<"SendSerialData ID:"<< QThread::currentThreadId();
// qDebug() << data;
// }
}
void SerialportThread::SendData(QByteArray data)
{
QString command = QString(data);
QStringList commadList = command.split(' ');
QByteArray datas;
datas.resize(commadList.count());//初始化新数组
bool ok = false;
for(int i = 0; i < commadList.count(); i++)
{
datas[i]=static_cast<char>(commadList.at(i).toInt(&ok,16));
}
datas.toUpper();
serialThread->write(datas);
//qDebug()<<"Serial SendData "<< datas;
}
void SerialportThread::FromData()
{
qint64 bytelen = serialThread->bytesAvailable();
if(bytelen<1)
{
qDebug()<<"串口无数据接收";
return;
}
QByteArray Receivebuff = serialThread->readAll();
qDebug()<<"串口接收"<<Receivebuff;
// qDebug()<<"串口接收线程ID为:"<<QThread::currentThread();
emit ReceiveData(Receivebuff);
}
Mysocket.h
#ifndef MYSOCKET_H
#define MYSOCKET_H
#include <QObject>
#include <QHostAddress>
#include <QTcpSocket>
class Mysocket : public QObject
{
Q_OBJECT
public:
explicit Mysocket(QString ip,quint16 port);
~Mysocket();
bool connectStaions ;
signals:
void Rece_Datas(QByteArray tmp);
public slots:
void socket_Init(QString ip,quint16 port);
void SendDatas(QByteArray data);
void ReceDatas(void);
private:
QTcpSocket * socket;
QThread * SocketThread;
};
#endif // MYSOCKET_H
Mysocket.cpp
#include "mysocket.h"
#include <qtcpsocket.h>
#include <QThread>
#include <QMessageBox>
//#define ip 192.168.1.1
//#define port 8899
Mysocket::Mysocket(QString ip,quint16 port)
{
socket = new QTcpSocket();
SocketThread = new QThread();
socket_Init(ip,port);
socket->setReadBufferSize(100*1024*1024);//1M
this->moveToThread(SocketThread);
socket->moveToThread(SocketThread);
SocketThread->start();
// qDebug()<<"socket线程ID为:"<<QThread::currentThread();
//qDebug()<<"IP:"<<ip<<"PORT:"<<port;
}
Mysocket::~Mysocket()
{
socket->disconnectFromHost();
socket->deleteLater();
SocketThread->quit();
//SocketThread->wait();
SocketThread->deleteLater();
}
void Mysocket::socket_Init(QString ip,quint16 port)
{
socket->connectToHost(QHostAddress(ip),port);
connect(socket,&QTcpSocket::readyRead,this,&Mysocket::ReceDatas);
if(!socket->waitForConnected())
{
QMessageBox::critical(NULL,"提示","无法到服务器,请检查。",QMessageBox::Yes);
return;
connectStaions = false;
}
else
{
QMessageBox::information(NULL,"提示","socket已经连接",QMessageBox::Yes);
connectStaions = true;
}
}
void Mysocket::SendDatas(QByteArray data)
{
socket->write(data);
}
void Mysocket::ReceDatas()
{
QByteArray str =socket->readAll();
emit Rece_Datas(str);
}
还有几个文件懒得截图了0.0 有什么问题可以私聊 有什么错误 欢迎指正!