GrabBag/App/WheelMeasure/WheelMeasureApp/Presenter/Inc/WheelMeasureTCPProtocol.h

126 lines
3.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.

#ifndef WHEELMEASURETCPPROTOCOL_H
#define WHEELMEASURETCPPROTOCOL_H
#include <functional>
#include <vector>
#include <string>
#include <QString>
#include <QMutex>
#include "IYTCPServer.h"
/**
* @brief 车轮测量TCP服务器协议
*
* 协议格式:
* - 接收start,100 (start命令100是参数)
* - 发送1,100,200;2,100,200;3,100,200;4,100,200
* - 格式相机ID,中心点到地面距离,轮眉到地面距离
* - 多个相机结果用分号分隔
* - 错误码:
* - 400扫描/匹配失败
* - 401工件为空
* - 示例1,400;2,100,200;3,100,200;4,100,200 (相机1失败)
*/
class WheelMeasureTCPProtocol
{
public:
/**
* @brief 单个相机的测量结果
*/
struct CameraMeasureResult {
int cameraId = 0; // 相机ID (1-4)
int errorCode = 0; // 错误码0-成功400-扫描失败401-工件为空
double centerDistance = 0; // 中心点到地面距离
double archDistance = 0; // 轮眉到地面距离
};
/**
* @brief 检测触发回调函数类型
* @param param 从start命令解析的参数
* @return true-成功触发检测false-失败
*/
using DetectionTriggerCallback = std::function<bool(int param)>;
public:
WheelMeasureTCPProtocol();
~WheelMeasureTCPProtocol();
/**
* @brief 初始化TCP服务器
* @param port TCP端口号
* @return 0-成功,其他-错误码
*/
int Initialize(uint16_t port = 6800);
/**
* @brief 反初始化,停止服务
*/
void Deinitialize();
/**
* @brief 发送测量结果给客户端
* @param results 所有相机的测量结果
* @return 0-成功,其他-错误码
*/
int SendMeasureResults(const std::vector<CameraMeasureResult>& results);
/**
* @brief 设置检测触发回调
* @param callback 回调函数
*/
void SetDetectionTriggerCallback(const DetectionTriggerCallback& callback);
/**
* @brief 获取服务运行状态
* @return true-运行中false-已停止
*/
bool IsRunning() const { return m_bServerRunning; }
/**
* @brief 获取当前连接的客户端数量
* @return 客户端数量
*/
int GetClientCount() const;
private:
/**
* @brief TCP客户端连接事件处理
* @param pClient 客户端对象
* @param eventType 事件类型
*/
void OnTCPEvent(const TCPClient* pClient, TCPServerEventType eventType);
/**
* @brief TCP数据接收处理
* @param pClient 客户端对象
* @param pData 数据指针
* @param nLen 数据长度
*/
void OnTCPDataReceived(const TCPClient* pClient, const char* pData, unsigned int nLen);
/**
* @brief 解析命令
* @param pClient 客户端对象
* @param command 命令字符串
*/
void ParseCommand(const TCPClient* pClient, const QString& command);
/**
* @brief 发送数据给指定客户端
* @param pClient 客户端对象nullptr表示发送给所有客户端
* @param data 数据字符串
* @return true-成功false-失败
*/
bool SendData(const TCPClient* pClient, const QString& data);
private:
IYTCPServer* m_pTCPServer; // TCP服务器实例
bool m_bServerRunning; // 服务器运行状态
uint16_t m_nPort; // TCP端口
DetectionTriggerCallback m_detectionCallback; // 检测触发回调
QMutex m_mutex; // 线程安全锁
const TCPClient* m_pCurrentClient; // 当前请求的客户端
};
#endif // WHEELMEASURETCPPROTOCOL_H