GrabBag/App/Workpiece/WorkpieceApp/Presenter/Src/TCPServerProtocol.cpp

260 lines
7.9 KiB
C++
Raw Normal View History

#include "TCPServerProtocol.h"
#include "VrLog.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDateTime>
TCPServerProtocol::TCPServerProtocol()
: m_pTCPServer(nullptr)
, m_bServerRunning(false)
, m_nPort(5020)
, m_connectionStatus(STATUS_DISCONNECTED)
{
}
TCPServerProtocol::~TCPServerProtocol()
{
Deinitialize();
}
int TCPServerProtocol::Initialize(uint16_t port)
{
LOG_DEBUG("Initializing TCP server protocol on port %d\n", port);
m_nPort = port;
// 创建TCP服务器实例
if (!VrCreatYTCPServer(&m_pTCPServer)) {
LOG_ERROR("Failed to create TCP server instance\n");
return -1;
}
// 初始化TCP服务器
if (!m_pTCPServer->Init(port)) {
LOG_ERROR("Failed to initialize TCP server on port %d\n", port);
delete m_pTCPServer;
m_pTCPServer = nullptr;
return -2;
}
// 设置事件回调
m_pTCPServer->SetEventCallback([this](const TCPClient* pClient, TCPServerEventType eventType) {
this->OnTCPEvent(pClient, eventType);
});
// 启动TCP服务器
if (!m_pTCPServer->Start([this](const TCPClient* pClient, const char* pData, const unsigned int nLen) {
this->OnTCPDataReceived(pClient, pData, nLen);
})) {
LOG_ERROR("Failed to start TCP server\n");
m_pTCPServer->Close();
delete m_pTCPServer;
m_pTCPServer = nullptr;
return -3;
}
m_bServerRunning = true;
m_connectionStatus = STATUS_CONNECTED;
LOG_DEBUG("TCP server protocol initialized successfully on port %d\n", port);
return 0;
}
void TCPServerProtocol::Deinitialize()
{
if (m_pTCPServer) {
LOG_DEBUG("Stopping TCP server protocol\n");
m_bServerRunning = false;
m_connectionStatus = ConnectionStatus::STATUS_DISCONNECTED;
m_pTCPServer->Stop();
m_pTCPServer->Close();
delete m_pTCPServer;
m_pTCPServer = nullptr;
LOG_DEBUG("TCP server protocol stopped\n");
}
}
int TCPServerProtocol::SendDetectionResult(const DetectionResultData& result, const TCPClient* pClient)
{
if (!m_pTCPServer || !m_bServerRunning) {
LOG_ERROR("TCP server is not running\n");
return -1;
}
// 构造JSON响应
QJsonObject response;
response["code"] = result.code;
response["success"] = result.success;
response["message"] = result.message;
response["timestamp"] = result.timestamp;
// 构造结果数组
QJsonArray resultArray;
for (const auto& weldLine : result.result) {
QJsonArray lineArray;
for (const auto& point : weldLine) {
lineArray.append(point);
}
resultArray.append(lineArray);
}
response["result"] = resultArray;
// 转换为JSON字符串
QJsonDocument doc(response);
QByteArray jsonData = doc.toJson(QJsonDocument::Compact);
// 发送数据
bool success = false;
if (pClient) {
// 发送给指定客户端
success = m_pTCPServer->SendData(pClient, jsonData.constData(), jsonData.size());
LOG_DEBUG("Sent detection result to specific client, size: %d bytes\n", jsonData.size());
} else {
// 发送给所有客户端
success = m_pTCPServer->SendAllData(jsonData.constData(), jsonData.size());
LOG_DEBUG("Sent detection result to all clients, size: %d bytes\n", jsonData.size());
}
if (!success) {
LOG_ERROR("Failed to send detection result\n");
return -2;
}
return 0;
}
TCPServerProtocol::TCPStatus TCPServerProtocol::GetConnectionStatus() const
{
return m_connectionStatus;
}
void TCPServerProtocol::SetConnectionCallback(const ConnectionCallback& callback)
{
m_connectionCallback = callback;
}
void TCPServerProtocol::SetDetectionTriggerCallback(const DetectionTriggerCallback& callback)
{
m_detectionTriggerCallback = callback;
}
bool TCPServerProtocol::IsRunning() const
{
return m_bServerRunning;
}
void TCPServerProtocol::OnTCPEvent(const TCPClient* pClient, TCPServerEventType eventType)
{
switch (eventType) {
case TCP_EVENT_CLIENT_CONNECTED:
LOG_DEBUG("TCP client connected: %p\n", pClient);
m_connectionStatus = STATUS_CONNECTED;
if (m_connectionCallback) {
m_connectionCallback(true);
}
break;
case TCP_EVENT_CLIENT_DISCONNECTED:
LOG_DEBUG("TCP client disconnected: %p\n", pClient);
// 注意:这里不立即设置为断开状态,因为可能还有其他客户端连接
if (m_connectionCallback) {
m_connectionCallback(false);
}
break;
case TCP_EVENT_CLIENT_EXCEPTION:
LOG_WARNING("TCP client exception: %p\n", pClient);
if (m_connectionCallback) {
m_connectionCallback(false);
}
break;
}
}
void TCPServerProtocol::OnTCPDataReceived(const TCPClient* pClient, const char* pData, unsigned int nLen)
{
if (!pData || nLen == 0) {
LOG_WARNING("Received empty data from client %p\n", pClient);
return;
}
LOG_DEBUG("Received TCP data from client %p, size: %u bytes\n", pClient, nLen);
// 解析JSON数据
QByteArray data(pData, nLen);
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(data, &error);
if (error.error != QJsonParseError::NoError) {
LOG_ERROR("JSON parse error: %s\n", error.errorString().toStdString().c_str());
SendErrorResponse(pClient, -1, "JSON格式错误", 0);
return;
}
if (!doc.isObject()) {
LOG_ERROR("Received JSON is not an object\n");
SendErrorResponse(pClient, -2, "JSON数据必须是对象格式", 0);
return;
}
ParseJSONCommand(pClient, doc.object());
}
void TCPServerProtocol::ParseJSONCommand(const TCPClient* pClient, const QJsonObject& jsonData)
{
// 获取命令类型
QString command = jsonData["command"].toString();
qint64 timestamp = jsonData["timestamp"].toVariant().toLongLong();
LOG_DEBUG("Received command: %s, timestamp: %lld\n", command.toStdString().c_str(), timestamp);
if (command == "start_detection") {
HandleStartDetectionCommand(pClient, timestamp);
} else {
LOG_WARNING("Unknown command: %s\n", command.toStdString().c_str());
SendErrorResponse(pClient, -3, QString("未知命令: %1").arg(command), timestamp);
}
}
void TCPServerProtocol::HandleStartDetectionCommand(const TCPClient* pClient, qint64 timestamp)
{
LOG_DEBUG("Handling start_detection command, timestamp: %lld\n", timestamp);
bool success = false;
int cameraIndex = -1; // -1表示所有相机
// 触发检测回调
if (m_detectionTriggerCallback) {
success = m_detectionTriggerCallback(true, cameraIndex, timestamp);
} else {
LOG_WARNING("Detection trigger callback not set\n");
SendErrorResponse(pClient, -4, "检测服务未准备就绪", timestamp);
return;
}
if (!success) {
LOG_ERROR("Failed to trigger detection\n");
SendErrorResponse(pClient, -5, "检测启动失败", timestamp);
return;
}
// 注意:这里不立即发送结果,实际的检测结果将通过 SendDetectionResult 方法异步发送
LOG_DEBUG("Detection triggered successfully, waiting for results...\n");
}
void TCPServerProtocol::SendErrorResponse(const TCPClient* pClient, int code, const QString& message, qint64 timestamp)
{
DetectionResultData errorResult;
errorResult.code = code;
errorResult.success = false;
errorResult.message = message;
errorResult.timestamp = timestamp;
errorResult.result.clear(); // 错误时返回空结果
SendDetectionResult(errorResult, pClient);
}