基于QT嵌入式ARM数据采集上位机设计(四)——网络传输协议(UDP)+ 线程
上一篇《基于QT嵌入式ARM数据采集上位机设计 (三) —— qwt和fft使用》
源代码 github仓库 https://github.com/xiaoliu-406/simpledata
UDP配置
在QT中使用网络传输协议时,需要在.pro
文件中添加
QT += network
在这个项目中用到的是UDP组播模式进行网络数据传输,所以如下配置为UDP组播模式
#include "sll_udp.h"
#include <QDebug>
#include <QHostAddress>
#include <QHostInfo>
#include <QByteArray>
SLL_UDP::SLL_UDP(QObject *parent) : QObject(parent)
{
}
void SLL_UDP::sll_UdpInit(quint16 pot,QString ip)
{
UdpSocket = new QUdpSocket();
UdpSocket->bind(QHostAddress::AnyIPv4,pot,QAbstractSocket::ShareAddress);
UdpSocket->joinMulticastGroup(QHostAddress(ip));
UdpSocket->setSocketOption(UdpSocket->MulticastLoopbackOption,0);
// connect(UdpSocket,&QUdpSocket::readyRead,this,&SLL_UDP::dealmsg);
qDebug() << "udpthread111" ;
}
void SLL_UDP::dealmsgthread()
{
qDebug() << "dealmsgthread"<< QThread::currentThreadId();
QByteArray udpdata ;
qint64 len;
QVector<double> ChangeDoubleData;
while(1)
{
while(UdpSocket->hasPendingDatagrams()&StartRevMsg){
udpdata.resize(UdpSocket->pendingDatagramSize());
len = UdpSocket->readDatagram(udpdata.data(),udpdata.size());
quint8 *q = (quint8 *)udpdata.data();
for(quint16 i = 0; i < len;i = i+4){
ChangeDoubleData.push_back(datachange(q + i));
}
emit sll_UdpMsg(ChangeDoubleData);
ChangeDoubleData.resize(0);
}
}
}
void SLL_UDP::setstartfalg(bool flag)
{
StartRevMsg = flag;
}
void SLL_UDP::ParmetConfig(quint16 pot,QString ip,bool startrevmsg)
{
StartRevMsg = startrevmsg;
sendipflag = startrevmsg;
sll_UdpInit(pot,ip);
// boardcastip = ip;
QByteArray cha;
cha.append(char(startrevmsg));
qDebug() << "cha"<< cha.toHex();
// qDebug() << "parment"<< QThread::currentThreadId();
UdpSocket->writeDatagram(cha,QHostAddress(boardcastip),pot);
}
项目整合
本项目使用到线程处理传输过来的数据,**dealmsgthread()**
这个函数为线程的槽函数,需要使用connnect进行启动,这个槽函数的使用,是在function.cpp文件中:如下方式,可翻看基于QT嵌入式ARM数据采集卡上位机(二)——页面布局,查看,如有不是特理解的将第二部分的页面布局,对着翻出来看一下,即可
sll_udp = new SLL_UDP;
udpthread = new QThread(this);
connect(this,&functionui::startudpthread,sll_udp,&SLL_UDP::dealmsgthread);
将下述函数添加到function.cpp文件中,可以实现实时改变IP以及PORT。
void functionui::GetLocalIpandPort()
{
static bool flag = 0;
if(flag == 0)
{
flag = 1;
QString ip_str = ip_linedit->text();
quint16 port = port_linedit->text().toInt();
testbutton->setStyleSheet("QPushButton:checked{background-color: red;}");
sll_udp->ParmetConfig(port,ip_str,flag);
udpthread->start();
emit startudpthread();
qDebug() << "translate ip and port" ;
}
else{
flag = 0;
// QString ip_str = ip_linedit->text();
// quint16 port = port_linedit->text().toInt();
emit udpthreadstop(flag);
}
}
实现线程的退出
void functionui::udpthreadstopfun(bool flag)
{
sll_udp->setstartfalg(flag);
udpthread->quit();
// udpthread->wait();
}
至此本项目,所有代码更新完毕,其实,我还是想多讲一点文字的描述,但是,总觉得代码上来之后,就不需要过多的解释,如有网友需要,解释的话,我在更新一点新内容。我后面会将这个项目做成视频,如有不弃,请关注我哦,视频毕竟需要讲解,解说的可能更多一点。