该模块主要用于和无人机地面站通信单元进行数据的收发,基于udpsocket.
cpp
#pragma once
#include <QObject>
#include "libCore.h"
#include "LkCommonStruct.h"
class LkUavUdpSocket : public LkUdpSocket
{
Q_OBJECT
public:
LkUavUdpSocket(QObject *parent = 0);
~LkUavUdpSocket();
//向无人机发送命令
template <class T>
int cmdToUav(T cmd, MsgHeader type)
{
int len = cmd.ByteSize();
char* buff;
buff = new char[len];
memset(buff, 0, len);
cmd.SerializeToArray(buff, len);
QByteArray sendTo;
LittleEndianStream(out, sendTo);
out << int(type);
out.writeRawData(buff, len);
delete buff;
//qDebug() << QString("cmdToUav:Type %1: %2").arg(type).arg(QDateTime::currentDateTime().toString("hh:mm:ss:.zzz"));
int r = mSendSocket->writeDatagram(sendTo.data(), sendTo.size(), QHostAddress(mUavComIp), mUavSendPort);
//qDebug() << QString("cmdToUav:End %1: %2").arg(type).arg(QDateTime::currentDateTime().toString("hh:mm:ss:.zzz"));
return r;
}
void init(QString ip, int port);
private:
void parse(QByteArray &ba);
public slots:
virtual void readPendingDatagrams();
signals:
public:
QString mUavComIp;
int mUavSendPort;
QSharedPointer<LkUdpSocket> mSendSocket;
private:
};
```cpp
#include "LkUavUdpSocket.h"
LkUavUdpSocket::LkUavUdpSocket(QObject *parent)
: LkUdpSocket(parent)
{
connect(this, &LkUavUdpSocket::readyRead, this, &LkUavUdpSocket::readPendingDatagrams);
mSendSocket = QSharedPointer<LkUdpSocket>::create();
}
LkUavUdpSocket::~LkUavUdpSocket()
{
}
void LkUavUdpSocket::init(QString ip, int port)
{
bool b = bind(QHostAddress::Any, port);
mUavComIp = ip;
}
void LkUavUdpSocket::readPendingDatagrams()
{
while (hasPendingDatagrams())
{
QByteArray datagram;
datagram.resize(pendingDatagramSize());
QNetworkDatagram netDgm = receiveDatagram();
QString senderIP = netDgm.senderAddress().toString();
datagram = netDgm.data();
parse(datagram);
}
}
void LkUavUdpSocket::parse(QByteArray &ba)
{
LittleEndianStream(in, ba);
int msgId;
in >> msgId;
if (msgId > 0)
{
LkMessageEvent me(QString::number(msgId));
me.setData(ba.size() - sizeof(int), ba.data() + sizeof(int));
gNetListener->dispatch(me);
}
}