add,计划采集8:

实现部分计划采集功能:电源通断控制
This commit is contained in:
tangchao0503
2026-06-05 18:01:38 +08:00
parent 467bebe9dd
commit 4a62d9a007
11 changed files with 681 additions and 1 deletions

View File

@ -0,0 +1,95 @@
#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()));
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();
}
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();
}