Files
HPPA/HPPA/CommunicationViaTCP.cpp
tangchao0503 a49f416551 add,山地所贡嘎山5,初步实现:
1、监听tcp消息,收到位置后触发pica L和is11采集。
2、releases可编译;
2026-07-16 16:07:48 +08:00

123 lines
2.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include "CommunicationViaTCP.h"
using namespace MotorParams;
CommunicationViaTCP::CommunicationViaTCP(MotorParams::TCPConnectionParams connectionParams, QObject* parent)
:MotorParams::CommunicationInterfaceBase(parent)
{
m_bConnected = false;
m_tcpServer = new QTcpServer(this);
connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
m_tcpServer->listen(QHostAddress::Any, connectionParams.port);
}
CommunicationViaTCP::~CommunicationViaTCP()
{
m_tcpServer->close();
delete m_tcpServer;
//这两行代码要报错,为啥呢?????????????????
//m_tcpSocket->disconnectFromHost();
//delete m_tcpSocket;
}
bool CommunicationViaTCP::connect2Motor()
{
return true;
}
void CommunicationViaTCP::onNewConnection()
{
m_bConnected = true;
m_tcpSocket = m_tcpServer->nextPendingConnection();
connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onTcpSocketDisconnected()));
connect(m_tcpSocket, &QTcpSocket::readyRead, this, &CommunicationViaTCP::receiveData);
emit connected();
}
bool CommunicationViaTCP::isConnected() const
{
return m_bConnected;
}
//从拔掉客户端的电源(客户端m_tcpSocket断开连接)到这个函数被调用有延迟,所以这个函数调用也有延迟,导致拔掉电源后的一小段时间函数isConnected()还是返回true
void CommunicationViaTCP::onTcpSocketDisconnected()
{
int a = 1;
m_bConnected = false;
m_tcpSocket->deleteLater();
}
void CommunicationViaTCP::receiveData()
{
if (!isConnected())
{
qWarning() << "receiveData: No client connected";
return;
}
QByteArray data = m_tcpSocket->readAll();
if (data.isEmpty())
{
return;
}
bool ok;
int position = QString::fromUtf8(data).toInt(&ok);
if (ok)
{
qDebug() << "Received position:" << position;
emit positionReceived(position);
} else
{
qWarning() << "Failed to parse position data:" << data;
}
}
int CommunicationViaTCP::sendCommand(const QString cmd)
{
if (!isConnected()) {
QString error = "No client connected";
emit commandSendResult(-1, error);
qWarning() << error << "command:" << cmd;
return -1;
}
qint64 bytesWritten = m_tcpSocket->write(cmd.toUtf8().data());
m_tcpSocket->waitForBytesWritten(50);
return bytesWritten;
}
int CommunicationViaTCP::recvData(QByteArray& dataRecv)
{
if (!isConnected()) {
QString error = "No client connected";
return -1;
}
dataRecv.clear();
QByteArray temp;
temp = m_tcpSocket->readAll();
dataRecv.append(temp);
int counter = 0;
while (dataRecv.size() < 21)
{
counter++;
m_tcpSocket->waitForReadyRead(100);
temp = m_tcpSocket->readAll();
dataRecv.append(temp);
if (counter >= 5)
break;
}
//qDebug() << "Hex:" << dataRecv.toHex();
return dataRecv.size();
}