2026-03-11 23:40:06 +08:00

81 lines
2.6 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.

#ifndef TCPSERVERPROTOCOL_H
#define TCPSERVERPROTOCOL_H
#include <functional>
#include <vector>
#include <string>
#include <map>
#include <QByteArray>
#include "IYTCPServer.h"
#include "ProtocolCommon.h"
/**
* @brief TCP服务器协议封装类文本协议
*
* 触发格式(客户端→服务端):
* X1 RbtX-23.45 RbtY-23.45 RbtZ-23.45 RbtRoll-23.45 RbtPitch-123.45 RbtYaw-23.45\n
* X后跟1或2区分相机RbtX/Y/Z/Roll/Pitch/Yaw为机器人法兰位姿
*
* 返回格式(服务端→客户端):
* PointNum_X1_Y1_Z1_Roll1_Pitch1_Yaw1/X2_Y2_Z2_Roll2_Pitch2_Yaw2/\n
* 第一个值是孔洞数量_分隔同一孔洞各分量/分隔不同孔洞
*/
class TCPServerProtocol
{
public:
using TCPStatus = ConnectionStatus;
/**
* @brief 检测触发回调
* @param cameraIndex 相机索引1或2
* @param robotPose 机器人法兰位姿
* @return 是否成功触发检测
*/
using DetectionTriggerCallback = std::function<bool(int cameraIndex, const RobotFlangePose& robotPose)>;
public:
TCPServerProtocol();
~TCPServerProtocol();
int Initialize(uint16_t port = 5020);
void Deinitialize();
/**
* @brief 发送文本格式结果给客户端
* @param text 文本内容(不含末尾换行,函数内部会自动添加)
* @param pClient 目标客户端nullptr则发送给所有客户端
* @return 0-成功,其他-错误码
*/
int SendTextResult(const std::string& text, const TCPClient* pClient = nullptr);
TCPStatus GetConnectionStatus() const;
void SetConnectionCallback(const ConnectionCallback& callback);
void SetDetectionTriggerCallback(const DetectionTriggerCallback& callback);
bool IsRunning() const;
private:
void OnTCPEvent(const TCPClient* pClient, TCPServerEventType eventType);
void OnTCPDataReceived(const TCPClient* pClient, const char* pData, unsigned int nLen);
/**
* @brief 解析一行文本命令
* @param pClient 客户端对象
* @param line 一行完整命令(不含换行符)
*/
void ParseTextCommand(const TCPClient* pClient, const QByteArray& line);
private:
IYTCPServer* m_pTCPServer;
bool m_bServerRunning;
uint16_t m_nPort;
TCPStatus m_connectionStatus;
ConnectionCallback m_connectionCallback;
DetectionTriggerCallback m_detectionTriggerCallback;
// 每个客户端的接收缓冲区(处理粘包/分包)
std::map<const TCPClient*, QByteArray> m_clientBuffers;
};
#endif // TCPSERVERPROTOCOL_H