-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathTcpCommunicator.cpp
More file actions
1036 lines (880 loc) · 31.5 KB
/
TcpCommunicator.cpp
File metadata and controls
1036 lines (880 loc) · 31.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "TcpCommunicator.h"
#include "LineDrawingDialog.h"
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QStandardPaths>
#include <QDir>
#include <QFileInfo>
/**
* @brief TcpCommunicator 생성자
* @param parent 부모 객체
*/
TcpCommunicator::TcpCommunicator(QObject *parent)
: QObject(parent)
, m_socket(new QSslSocket(this))
, m_connectionTimer(nullptr)
, m_reconnectTimer(new QTimer(this))
, m_host("")
, m_port(0)
, m_isConnected(false)
, m_receivedData("")
, m_videoView(nullptr)
, m_connectionTimeoutMs(10000)
, m_reconnectEnabled(true)
, m_reconnectAttempts(0)
, m_maxReconnectAttempts(5)
, m_reconnectDelayMs(3000)
, m_autoReconnect(true)
, m_roadLinesReceived(false)
, m_detectionLinesReceived(false)
{
qDebug() << "[TCP] TcpCommunicator 생성자 호출";
m_socket = new QSslSocket(this);
setupSslConfiguration();
// Keep-Alive settings
m_socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
m_socket->setSocketOption(QAbstractSocket::LowDelayOption, 1);
// TCP 소켓 시그널 연결
connect(m_socket, &QSslSocket::connected, this, &TcpCommunicator::onConnected);
connect(m_socket, &QSslSocket::disconnected, this, &TcpCommunicator::onDisconnected);
connect(m_socket, &QSslSocket::readyRead, this, &TcpCommunicator::onReadyRead);
connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::errorOccurred),
this, &TcpCommunicator::onSocketError);
// Connect SSL signals
connect(m_socket, &QSslSocket::encrypted, this, &TcpCommunicator::onSslEncrypted);
connect(m_socket, QOverload<const QList<QSslError>&>::of(&QSslSocket::sslErrors),
this, &TcpCommunicator::onSslErrors);
// Connection timeout timer
m_connectionTimer = new QTimer(this);
m_connectionTimer->setSingleShot(true);
m_connectionTimer->setInterval(m_connectionTimeoutMs);
connect(m_connectionTimer, &QTimer::timeout, this, &TcpCommunicator::onConnectionTimeout);
// 재연결 타이머 설정
m_reconnectTimer->setSingleShot(true);
m_reconnectTimer->setInterval(m_reconnectDelayMs);
connect(m_reconnectTimer, &QTimer::timeout, this, &TcpCommunicator::onReconnectTimer);
qDebug() << "[TCP] TcpCommunicator 초기화 완료";
}
/**
* @brief TcpCommunicator 소멸자
*/
TcpCommunicator::~TcpCommunicator()
{
disconnectFromServer();
}
/**
* @brief 서버 연결 해제
*/
void TcpCommunicator::disconnectFromServer()
{
if (m_connectionTimer->isActive()) {
m_connectionTimer->stop();
}
if (m_reconnectTimer->isActive()) {
m_reconnectTimer->stop();
}
if (m_socket && m_socket->state() != QAbstractSocket::UnconnectedState) {
m_socket->disconnectFromHost();
if (m_socket->state() != QAbstractSocket::UnconnectedState) {
m_socket->waitForDisconnected(3000);
}
}
}
/**
* @brief SSL 설정 구성
*/
void TcpCommunicator::setupSslConfiguration() {
// Register server's CA certificate (e.g., ca-cert.pem file)
QSslConfiguration sslConfiguration = QSslConfiguration::defaultConfiguration();
// 2. Load server's CA certificate
QList<QSslCertificate> caCerts = QSslCertificate::fromPath(":/ca-cert.crt");
if (!caCerts.isEmpty()) {
qDebug() << "[TCP] CA certificates loaded:" << caCerts.size() << "items";
// 3. Add loaded CA certificates to SSL configuration
sslConfiguration.setCaCertificates(caCerts);
} else {
qDebug() << "[TCP] Warning: ca-cert.crt file not found or could not be read.";
qDebug() << "[TCP] SSL 인증서 검증을 완화하여 연결을 시도합니다.";
}
// 4. Apply SSL configuration to the socket
m_socket->setSslConfiguration(sslConfiguration);
// 5. Set server certificate verification mode
// 개발 환경에서는 VerifyNone으로 설정하여 연결 문제 해결
m_socket->setPeerVerifyMode(QSslSocket::VerifyNone);
qDebug() << "[TCP] SSL Peer verification mode set to VerifyNone for development";
}
/**
* @brief 서버에 연결
* @param host 호스트 주소
* @param port 포트 번호
*/
void TcpCommunicator::connectToServer(const QString &host, quint16 port)
{
qDebug() << "[TCP] connectToServer 호출 - 호스트:" << host << "포트:" << port;
m_host = host;
m_port = port;
// 이미 연결되어 있으면 연결 해제 후 재연결
if (m_socket->state() != QSslSocket::UnconnectedState) {
qDebug() << "[TCP] 기존 연결 해제 중... 현재 상태:" << m_socket->state();
m_socket->disconnectFromHost();
if (m_socket->state() != QSslSocket::UnconnectedState) {
m_socket->waitForDisconnected(1000);
}
}
qDebug() << "[TCP] 서버 연결 시도:" << host << ":" << port;
qDebug() << "[TCP] SSL 설정 확인 - Peer Verify Mode:" << m_socket->peerVerifyMode();
m_socket->connectToHostEncrypted(m_host, static_cast<qint16>(m_port));
// 연결 타임아웃 설정 (10초)
if (!m_socket->waitForConnected(10000)) {
qDebug() << "[TCP] 연결 타임아웃 또는 실패:" << m_socket->errorString();
emit errorOccurred("연결 타임아웃: " + m_socket->errorString());
} else {
qDebug() << "[TCP] TCP 연결 성공, SSL 핸드셰이크 대기 중...";
}
}
/**
* @brief 서버 연결 여부 반환
* @return 연결 여부
*/
bool TcpCommunicator::isConnectedToServer() const
{
return m_isConnected && m_socket && m_socket->state() == QAbstractSocket::ConnectedState;
}
/**
* @brief JSON 메시지 전송
* @param message 전송할 JSON 객체
* @return 성공 여부
*/
bool TcpCommunicator::sendJsonMessage(const QJsonObject &message)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] 메시지 전송 실패 - 서버에 연결되지 않음";
return false;
}
QJsonDocument doc(message);
QByteArray data = doc.toJson(QJsonDocument::Compact);
// qDebug() << "[TCP] JSON 메시지 전송 시도:" << data;
// 1. 데이터 길이(4바이트, 빅엔디안) 전송
quint32 dataLength = static_cast<quint32>(data.size());
QByteArray lengthBytes;
QDataStream lengthStream(&lengthBytes, QIODevice::WriteOnly);
lengthStream.setByteOrder(QDataStream::BigEndian);
lengthStream << dataLength;
// 2. 길이 + 데이터 순서로 전송
qint64 bytesWritten = m_socket->write(lengthBytes);
if (bytesWritten != 4) {
qDebug() << "[TCP] 길이 정보 전송 실패:" << m_socket->errorString();
return false;
}
bytesWritten = m_socket->write(data);
bool flushed = m_socket->flush();
if (bytesWritten == -1) {
qDebug() << "[TCP] 메시지 전송 실패:" << m_socket->errorString();
return false;
}
qDebug() << "[TCP] 메시지 전송 성공 - 바이트:" << bytesWritten << "플러시:" << flushed;
return true;
}
/**
* @brief 비디오 뷰 설정
* @param videoView VideoGraphicsView 포인터
*/
void TcpCommunicator::setVideoView(VideoGraphicsView* videoView)
{
m_videoView = videoView;
}
/**
* @brief 탐지선 데이터 전송
* @param lineData 탐지선 데이터
* @return 성공 여부
*/
bool TcpCommunicator::sendDetectionLine(const DetectionLineData &lineData)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] Failed to send detection line, no connection.";
emit errorOccurred("Not connected to server");
return false;
}
QJsonObject message;
message["request_id"] = 2;
QJsonObject data;
data["index"] = lineData.index;
data["x1"] = lineData.x1;
data["x2"] = lineData.x2;
data["y1"] = lineData.y1;
data["y2"] = lineData.y2;
data["name"] = lineData.name;
data["mode"] = lineData.mode;
message["data"] = data;
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] Detection line sent successfully - index:" << lineData.index;
} else {
qDebug() << "[TCP] Failed to send detection line.";
}
return success;
}
/**
* @brief 도로선 데이터 전송
* @param lineData 도로선 데이터
* @return 성공 여부
*/
bool TcpCommunicator::sendRoadLine(const RoadLineData &lineData)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] Failed to send road line, no connection.";
emit errorOccurred("Not connected to server");
return false;
}
QJsonObject message;
message["request_id"] = 5;
QJsonObject data;
data["index"] = lineData.index;
data["matrixNum1"] = lineData.matrixNum1;
data["x1"] = lineData.x1;
data["y1"] = lineData.y1;
data["matrixNum2"] = lineData.matrixNum2;
data["x2"] = lineData.x2;
data["y2"] = lineData.y2;
message["data"] = data;
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] Road line sent successfully - index:" << lineData.index;
} else {
qDebug() << "[TCP] Failed to send road line.";
}
return success;
}
/**
* @brief 저장된 도로선 데이터 요청
* @return 성공 여부
*/
bool TcpCommunicator::requestSavedRoadLines()
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] 연결이 없어 저장된 도로선 데이터 요청 실패";
emit errorOccurred("서버에 연결되지 않음");
return false;
}
// 서버에 저장된 도로선 데이터 요청 (request_id: 7)
QJsonObject message;
message["request_id"] = 7; // 도로선 select all 요청
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] 저장된 도로선 데이터 요청 성공 (request_id: 7)";
} else {
qDebug() << "[TCP] 저장된 도로선 데이터 요청 실패";
}
return success;
}
/**
* @brief 저장된 감지선 데이터 요청
* @return 성공 여부
*/
bool TcpCommunicator::requestSavedDetectionLines()
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] 연결이 없어 저장된 감지선 데이터 요청 실패";
emit errorOccurred("서버에 연결되지 않음");
return false;
}
// 서버에 저장된 감지선 데이터 요청 (request_id: 3)
QJsonObject message;
message["request_id"] = 3; // 감지선 select all 요청
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] 저장된 감지선 데이터 요청 전송 성공 (request_id: 3)";
} else {
qDebug() << "[TCP] 저장된 감지선 데이터 요청 전송 실패";
}
return success;
}
/**
* @brief 저장된 선 데이터 삭제 요청
* @return 성공 여부
*/
bool TcpCommunicator::requestDeleteLines()
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] 연결이 없어 저장된 선 데이터 삭제 실패";
emit errorOccurred("서버에 연결되지 않음");
return false;
}
// 서버에 저장된 감지선 데이터 요청 (request_id: 4)
QJsonObject message;
message["request_id"] = 4; // 감지선, 기준선, 수직선 delete all 요청
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] 저장된 선 데이터 삭제 전송 성공 (request_id: 4)";
} else {
qDebug() << "[TCP] 저장된 선 데이터 삭제 전송 실패";
}
return success;
}
/**
* @brief 여러 도로선 데이터 전송
* @param roadLines 도로선 데이터 리스트
* @return 성공 여부
*/
bool TcpCommunicator::sendMultipleRoadLines(const QList<RoadLineData> &roadLines)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] Failed to send multiple road lines, no connection.";
emit errorOccurred("Not connected to server");
return false;
}
bool allSuccess = true;
int successCount = 0;
for (const auto &line : roadLines) {
if (sendRoadLine(line)) {
successCount++;
} else {
allSuccess = false;
}
QThread::msleep(100);
}
qDebug() << "[TCP] Multiple road lines sending complete - Success:" << successCount
<< "/ Total:" << roadLines.size();
return allSuccess;
}
/**
* @brief 여러 탐지선 데이터 전송
* @param detectionLines 탐지선 데이터 리스트
* @return 성공 여부
*/
bool TcpCommunicator::sendMultipleDetectionLines(const QList<DetectionLineData> &detectionLines)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] Failed to send multiple detection lines, no connection.";
emit errorOccurred("Not connected to server");
return false;
}
bool allSuccess = true;
int successCount = 0;
for (const auto &line : detectionLines) {
if (sendDetectionLine(line)) {
successCount++;
} else {
allSuccess = false;
}
QThread::msleep(50);
}
qDebug() << "[TCP] Multiple detection lines sending complete - Success:" << successCount
<< "/ Total:" << detectionLines.size();
return allSuccess;
}
/**
* @brief 이미지 데이터 요청
* @param date 날짜(선택)
* @param hour 시간(선택)
*/
void TcpCommunicator::requestImageData(const QString &date, int hour)
{
if (!isConnectedToServer()) {
qDebug() << "[TCP] Failed to request image data, no connection.";
emit errorOccurred("Not connected to server");
return;
}
QJsonObject message;
message["request_id"] = 1;
QJsonObject data;
QString requestDate = date.isEmpty() ? QDate::currentDate().toString("yyyy-MM-dd") : date;
if (hour >= 0 && hour <= 23) {
data["start_timestamp"] = QString("%1T%2").arg(requestDate).arg(hour, 2, 10, QChar('0'));
data["end_timestamp"] = QString("%1T%2").arg(requestDate).arg(hour + 1, 2, 10, QChar('0'));
} else {
data["start_timestamp"] = requestDate + "T00";
data["end_timestamp"] = requestDate + "T23";
}
message["data"] = data;
bool success = sendJsonMessage(message);
if (success) {
qDebug() << "[TCP] Image request sent - request_id: 1, Date:" << requestDate << "Hour:" << hour;
emit statusUpdated("Requesting images...");
} else {
qDebug() << "[TCP] Failed to request image data.";
emit errorOccurred("Failed to send image request");
}
}
/**
* @brief 연결 타임아웃 설정
* @param timeoutMs 타임아웃(ms)
*/
void TcpCommunicator::setConnectionTimeout(int timeoutMs)
{
m_connectionTimeoutMs = timeoutMs;
}
/**
* @brief 자동 재연결 활성화 설정
* @param enabled 활성화 여부
*/
void TcpCommunicator::setReconnectEnabled(bool enabled)
{
m_reconnectEnabled = enabled;
}
/**
* @brief 서버 연결 슬롯
*/
void TcpCommunicator::onConnected()
{
m_connectionTimer->stop();
m_isConnected = true;
m_reconnectAttempts = 0;
qDebug() << "[TCP] Server connection successful.";
emit connected();
emit statusUpdated("Connected to server");
}
/**
* @brief 서버 연결 해제 슬롯
*/
void TcpCommunicator::onDisconnected()
{
m_isConnected = false;
qDebug() << "[TCP] Disconnected from server.";
// Add log for socket state
qDebug() << "[TCP] Socket state:" << m_socket->state();
qDebug() << "[TCP] Socket error:" << m_socket->errorString();
emit disconnected();
emit statusUpdated("Disconnected from server");
// Attempt reconnection only on unexpected disconnections
if (m_reconnectEnabled && m_reconnectAttempts < m_maxReconnectAttempts) {
qDebug() << "[TCP] Scheduling reconnection attempt...";
m_reconnectTimer->setInterval(m_reconnectDelayMs);
m_reconnectTimer->start();
}
}
/**
* @brief 데이터 수신 슬롯
*/
void TcpCommunicator::onReadyRead()
{
static QByteArray buffer;
static quint32 expectedLength = 0;
static bool lengthReceived = false;
// Read all available data from the socket
QByteArray newData = m_socket->readAll();
buffer.append(newData);
qDebug() << "[TCP] Data received:" << newData.size() << "bytes, Total buffer size:" << buffer.size();
while (true) {
// Step 1: Read message length (4 bytes)
if (!lengthReceived) {
if (buffer.size() < 4) {
// Length information has not fully arrived
break;
}
// Extract length information
QDataStream lengthStream(buffer.left(4));
lengthStream.setByteOrder(QDataStream::BigEndian);
lengthStream >> expectedLength;
buffer.remove(0, 4); // Remove length information
lengthReceived = true;
qDebug() << "[TCP] Message length received:" << expectedLength << "bytes";
}
// Step 2: Read the actual message data
if (lengthReceived) {
if (buffer.size() < expectedLength) {
// The message has not fully arrived
qDebug() << "[TCP] Waiting for message... Current:" << buffer.size() << "/ Required:" << expectedLength;
break;
}
// Extract the complete message
QByteArray messageData = buffer.left(expectedLength);
buffer.remove(0, expectedLength);
// Reset state
lengthReceived = false;
expectedLength = 0;
qDebug() << "[TCP] Complete message received:" << messageData.size() << "bytes";
// JSON parsing and processing
QString messageString = QString::fromUtf8(messageData);
QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(messageData, &error);
if (error.error == QJsonParseError::NoError && doc.isObject()) {
QJsonObject jsonObj = doc.object();
logJsonMessage(jsonObj, false);
processJsonMessage(jsonObj);
} else {
qDebug() << "[TCP] JSON parsing error:" << error.errorString();
qDebug() << "[TCP] Original message:" << messageString.left(200) << "...";
emit messageReceived(messageString);
}
}
}
}
/**
* @brief 에러 슬롯
* @param error 소켓 에러
*/
void TcpCommunicator::onError(QAbstractSocket::SocketError error)
{
m_connectionTimer->stop();
m_isConnected = false;
QString errorString;
switch (error) {
case QAbstractSocket::ConnectionRefusedError:
errorString = "Connection refused. Please check if the server is running.";
break;
case QAbstractSocket::RemoteHostClosedError:
errorString = "The remote host closed the connection.";
break;
case QAbstractSocket::HostNotFoundError:
errorString = "Host not found. Please check the IP address.";
break;
case QAbstractSocket::SocketTimeoutError:
errorString = "Connection timed out.";
break;
case QAbstractSocket::NetworkError:
errorString = "A network error occurred.";
break;
default:
errorString = QString("Socket error: %1").arg(m_socket->errorString());
break;
}
qDebug() << "[TCP] Socket error:" << errorString;
emit errorOccurred(errorString);
if (m_reconnectEnabled && m_reconnectAttempts < m_maxReconnectAttempts) {
m_reconnectTimer->setInterval(m_reconnectDelayMs);
m_reconnectTimer->start();
}
}
/**
* @brief 연결 타임아웃 슬롯
*/
void TcpCommunicator::onConnectionTimeout()
{
qDebug() << "[TCP] Connection timeout.";
m_socket->abort();
emit errorOccurred("Connection timed out.");
}
/**
* @brief SSL 암호화 슬롯
*/
void TcpCommunicator::onSslEncrypted() {
qDebug() << "[TCP] SSL encrypted connection established.";
}
/**
* @brief SSL 에러 슬롯
* @param errors SSL 에러 리스트
*/
void TcpCommunicator::onSslErrors(const QList<QSslError> &errors) {
qDebug() << "[TCP] SSL 오류 발생 - 총" << errors.size() << "개의 오류";
for (const auto &err : errors) {
qDebug() << "[TCP] SSL Error:" << err.errorString();
}
// 개발/테스트 환경에서는 SSL 오류를 무시하여 연결 진행
// 프로덕션 환경에서는 적절한 인증서를 설정해야 함
qDebug() << "[TCP] SSL 오류 무시하고 연결 계속 진행";
m_socket->ignoreSslErrors();
}
/**
* @brief 소켓 연결 슬롯
*/
void TcpCommunicator::onSocketConnected()
{
qDebug() << "[TCP] 소켓 연결 성공";
m_isConnected = true;
m_reconnectAttempts = 0;
stopReconnectTimer();
emit connected();
}
/**
* @brief 소켓 연결 해제 슬롯
*/
void TcpCommunicator::onSocketDisconnected()
{
qDebug() << "[TCP] 소켓 연결 해제";
m_isConnected = false;
emit disconnected();
// 자동 재연결 시도
if (m_autoReconnect && !m_host.isEmpty() && m_port > 0) {
startReconnectTimer();
}
}
/**
* @brief 소켓 데이터 수신 슬롯
*/
void TcpCommunicator::onSocketReadyRead()
{
while (m_socket->canReadLine()) {
QByteArray data = m_socket->readLine();
QString message = QString::fromUtf8(data).trimmed();
if (!message.isEmpty()) {
qDebug() << "[TCP] 메시지 수신:" << message;
QJsonParseError error;
QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
if (error.error == QJsonParseError::NoError && jsonDoc.isObject()) {
processJsonMessage(jsonDoc.object());
} else {
qDebug() << "[TCP] JSON 파싱 오류:" << error.errorString();
emit messageReceived(message);
}
}
}
}
/**
* @brief 소켓 에러 슬롯
* @param error 소켓 에러
*/
void TcpCommunicator::onSocketError(QAbstractSocket::SocketError error)
{
QString errorString = m_socket->errorString();
qDebug() << "[TCP] 소켓 오류:" << error << "-" << errorString;
m_isConnected = false;
emit errorOccurred(errorString);
// 자동 재연결 시도 (연결 오류인 경우)
if (m_autoReconnect && !m_host.isEmpty() && m_port > 0) {
startReconnectTimer();
}
}
/**
* @brief 재연결 타이머 슬롯
*/
void TcpCommunicator::onReconnectTimer()
{
if (m_reconnectAttempts >= m_maxReconnectAttempts) {
qDebug() << "[TCP] Maximum reconnection attempts exceeded.";
emit errorOccurred("Exceeded maximum reconnection attempts.");
return;
}
m_reconnectAttempts++;
qDebug() << "[TCP] Reconnection attempt" << m_reconnectAttempts << "/" << m_maxReconnectAttempts;
emit statusUpdated(QString("Reconnecting... (%1/%2)").arg(m_reconnectAttempts).arg(m_maxReconnectAttempts));
m_connectionTimer->start();
m_socket->connectToHostEncrypted(m_host, static_cast<qint16>(m_port));
}
/**
* @brief 재연결 타이머 시작
*/
void TcpCommunicator::startReconnectTimer()
{
if (!m_reconnectTimer->isActive() && m_reconnectAttempts < m_maxReconnectAttempts) {
qDebug() << "[TCP] 재연결 타이머 시작 (" << m_reconnectDelayMs << "ms 후)";
m_reconnectTimer->start();
}
}
/**
* @brief 재연결 타이머 중지
*/
void TcpCommunicator::stopReconnectTimer()
{
if (m_reconnectTimer->isActive()) {
qDebug() << "[TCP] 재연결 타이머 중지";
m_reconnectTimer->stop();
}
}
/**
* @brief JSON 메시지 처리
* @param jsonObj 수신된 JSON 객체
*/
void TcpCommunicator::processJsonMessage(const QJsonObject &jsonObj)
{
// request_id 또는 response_id 확인 (서버 호환성)
int requestId = jsonObj["request_id"].toInt();
if (requestId == 0) {
requestId = jsonObj["response_id"].toInt();
}
qDebug() << "[TCP] JSON 메시지 처리 - request_id/response_id:" << requestId;
// 기타 응답 처리
switch (requestId) {
case 10: // 이미지 요청 응답
handleImagesResponse(jsonObj);
break;
case 12:
// handleSavedDetectionLinesResponse(jsonObj);
handleDetectionLinesFromServer(jsonObj);
break;
case 16:
// handleSavedRoadLinesResponse(jsonObj);
handleRoadLinesFromServer(jsonObj);
break;
case 200: // BBox 데이터 응답
handleBBoxResponse(jsonObj);
break;
default:
qDebug() << "[TCP] 알 수 없는 request_id:" << requestId;
QJsonDocument doc(jsonObj);
emit messageReceived(doc.toJson(QJsonDocument::Compact));
break;
}
}
/**
* @brief 감지선 데이터 응답 처리
* @param jsonObj 수신된 JSON 객체
*/
void TcpCommunicator::handleDetectionLinesFromServer(const QJsonObject &jsonObj)
{
qDebug() << "[TCP] handleDetectionLinesFromServer 호출됨 (request_id: 12)";
QList<DetectionLineData> detectionLines;
if (jsonObj.contains("data") && jsonObj["data"].isArray()) {
QJsonArray dataArray = jsonObj["data"].toArray();
for (int i = 0; i < dataArray.size(); ++i) {
QJsonObject detectionLineObj = dataArray[i].toObject();
DetectionLineData detectionLine;
detectionLine.index = detectionLineObj["index"].toInt();
detectionLine.x1 = detectionLineObj["x1"].toInt();
detectionLine.y1 = detectionLineObj["y1"].toInt();
detectionLine.x2 = detectionLineObj["x2"].toInt();
detectionLine.y2 = detectionLineObj["y2"].toInt();
detectionLine.name = detectionLineObj["name"].toString();
detectionLine.mode = detectionLineObj["mode"].toString();
detectionLines.append(detectionLine);
}
}
// VideoGraphicsView 인스턴스에 감지선 데이터 전달
if (m_videoView) {
m_videoView->loadSavedDetectionLines(detectionLines);
} else {
qDebug() << "[TCP] m_videoView가 nullptr입니다. 감지선 데이터를 전달할 수 없습니다.";
}
}
/**
* @brief 도로선 데이터 응답 처리
* @param jsonObj 수신된 JSON 객체
*/
void TcpCommunicator::handleRoadLinesFromServer(const QJsonObject &jsonObj)
{
qDebug() << "[TCP] handleRoadLinesFromServer 호출됨 (request_id: 16)";
QList<RoadLineData> roadLines;
if (jsonObj.contains("data") && jsonObj["data"].isArray()) {
QJsonArray dataArray = jsonObj["data"].toArray();
for (int i = 0; i < dataArray.size(); ++i) {
QJsonObject roadLineObj = dataArray[i].toObject();
RoadLineData roadLine;
roadLine.index = roadLineObj["index"].toInt();
roadLine.x1 = roadLineObj["x1"].toInt();
roadLine.y1 = roadLineObj["y1"].toInt();
roadLine.x2 = roadLineObj["x2"].toInt();
roadLine.y2 = roadLineObj["y2"].toInt();
roadLine.matrixNum1 = roadLineObj["matrixNum1"].toInt();
roadLine.matrixNum2 = roadLineObj["matrixNum2"].toInt();
roadLines.append(roadLine);
}
}
// VideoGraphicsView 인스턴스에 감지선 데이터 전달
if (m_videoView) {
m_videoView->loadSavedRoadLines(roadLines);
} else {
qDebug() << "[TCP] m_videoView가 nullptr입니다. 도로기준선 데이터를 전달할 수 없습니다.";
}
}
/**
* @brief Base64 이미지 저장
* @param base64Data Base64 인코딩 이미지 데이터
* @param timestamp 타임스탬프
* @return 저장된 파일 경로
*/
QString TcpCommunicator::saveBase64Image(const QString &base64Data, const QString ×tamp)
{
QString cleanBase64 = base64Data;
if (cleanBase64.contains(",")) {
cleanBase64 = cleanBase64.split(",").last();
}
QByteArray imageData = QByteArray::fromBase64(cleanBase64.toUtf8());
QString tempDir = QStandardPaths::writableLocation(QStandardPaths::TempLocation);
QString cleanTimestamp = timestamp;
cleanTimestamp.replace(":", "_").replace("-", "_");
QString fileName = QString("CCTVImage%1.jpg").arg(cleanTimestamp);
QString filePath = QDir(tempDir).absoluteFilePath(fileName);
QFile file(filePath);
if (file.open(QIODevice::WriteOnly)) {
file.write(imageData);
file.close();
qDebug() << "[TCP] Base64 image saved successfully:" << filePath;
return filePath;
} else {
qDebug() << "[TCP] Failed to save Base64 image:" << filePath;
return QString();
}
}
/**
* @brief 이미지 응답 처리
* @param jsonObj 수신된 JSON 객체
*/
void TcpCommunicator::handleImagesResponse(const QJsonObject &jsonObj)
{
qDebug() << "[TCP] Processing image response...";
if (!jsonObj.contains("data")) {
qDebug() << "[TCP] 'data' field not found in response.";
emit errorOccurred("The 'data' field is missing in the server response.");
return;
}
QJsonArray dataArray = jsonObj["data"].toArray();
qDebug() << "[TCP] Size of data array:" << dataArray.size();
QList<ImageData> images;
for (int i = 0; i < dataArray.size(); ++i) {
QJsonValue value = dataArray[i];
if (!value.isObject()) {
qDebug() << "[TCP] data[" << i << "] is not an object.";
continue;
}
QJsonObject imageObj = value.toObject();
if (!imageObj.contains("image") || !imageObj.contains("timestamp")) {
qDebug() << "[TCP] Image object[" << i << "] is missing required fields.";
continue;
}
ImageData imageData;
QString base64Image = imageObj["image"].toString();
imageData.timestamp = imageObj["timestamp"].toString();
imageData.imagePath = saveBase64Image(base64Image, imageData.timestamp);
imageData.logText = QString("Detection time: %1").arg(imageData.timestamp);
imageData.detectionType = "vehicle";
imageData.direction = "unknown";
if (!imageData.imagePath.isEmpty()) {
images.append(imageData);
}
}
qDebug() << "[TCP] Number of parsed images:" << images.size();
emit imagesReceived(images);
emit statusUpdated(QString("Loaded %1 images.").arg(images.size()));
}
/**
* @brief JSON 메시지 로깅
* @param jsonObj JSON 객체
* @param outgoing 송신 여부
*/
void TcpCommunicator::logJsonMessage(const QJsonObject &jsonObj, bool outgoing) const
{
QString direction = outgoing ? "Sent" : "Received";
int requestId = jsonObj["request_id"].toInt();
qDebug() << QString("[TCP] JSON %1 - request_id: %2").arg(direction).arg(requestId);
// Only print full JSON in debug mode
#ifdef QT_DEBUG
QJsonDocument doc(jsonObj);
qDebug() << "JSON Content:" << doc.toJson(QJsonDocument::Compact);
#endif
}
/**
* @brief BBox 응답 처리
* @param jsonObj 수신된 JSON 객체
*/
void TcpCommunicator::handleBBoxResponse(const QJsonObject &jsonObj)
{