-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1538 lines (1306 loc) · 56.8 KB
/
Copy pathmain.cpp
File metadata and controls
1538 lines (1306 loc) · 56.8 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
/**
* @file main.cpp
* @brief 유닉스 도메인 소켓으로 ROI 설정과 영상 스트림을 받아 버스를 감지하고,
* 정제된 감지 결과를 공유 메모리에 기록하는 메인 프로그램
*/
#include <atomic>
#include <chrono>
#include <csignal>
#include <iomanip>
#include <iostream>
#include <thread>
// 시스템 헤더
#include <fcntl.h> // 공유 메모리
#include <sys/mman.h> // 공유 메모리
#include <sys/select.h> // select
#include <sys/socket.h> //소켓
#include <sys/stat.h> // chmod
#include <sys/un.h> // 유닉스 도메인 소켓
#include <unistd.h>
#include "checker.hpp" // check_bus_platform, PixelRatioInfo
#include "filters.hpp" // 차량 마스킹
#include "safeQueue.hpp"
#include "stop_status.hpp" // StopStatus 구조체
#if 1
#include <X11/Xlib.h> // XInitThreads
#endif
// 상수 정의
#define MAX_QUEUE_SIZE 2 // 큐사이즈가 클수록 딜레이 증가
#define MAX_PLATFORM_COUNT 20 // 최대 플랫폼 수
// 통신 경로
#define SHM_NAME_FRAME "/busbom_frame" // live stream
#define SHM_NAME_STATUS "/busbom_status" // bus stop status
#define SOCKET_PATH "/tmp/roi_socket" // roi info
// 프레임 설정
#define FRAME_WIDTH 1280
#define FRAME_HEIGHT 720
#define FRAME_CHANNELS 3
// --- 전역 설정 ---
const int TARGET_FPS = 15;
const std::chrono::milliseconds FRAME_DURATION(1000 / TARGET_FPS);
const char* STATION_ID = "101000004"; // 정류장 ID
// --- 상태 안정화(Debouncing)용 변수 ---
static int stable_status[MAX_PLATFORM_COUNT] = {0};
static int prev_stable_status[MAX_PLATFORM_COUNT] = {0};
// --- 시간 기반 정차 판단용 변수 ---
static std::chrono::steady_clock::time_point
detection_start_time[MAX_PLATFORM_COUNT];
static int detection_loss_counter[MAX_PLATFORM_COUNT] = {
0}; // 감지 손실 카운터
const double STABLE_TIME_THRESHOLD_S = 3.0; // 정차로 판단하기 위한 시간 (초)
const int LOSS_TOLERANCE_CYCLES = 5; // 감지 손실 허용 횟수 (사이클)
// --- 게이트 및 버스 카운팅용 변수 ---
static int entered_bus_count = 0;
static int exited_bus_count = 0;
static bool prev_entry_gate_status = false;
static bool prev_exit_gate_status = false;
static int entry_gate_loss_counter = 0;
static int exit_gate_loss_counter = 0;
const int GATE_LOSS_TOLERANCE_CYCLES = 5; // 게이트 감지 손실 허용 횟수
// --- 입구/출구 영역 상태 추적용 변수 ---
static bool entry_area_filled = false;
static bool exit_area_filled = false;
static bool prev_entry_area_filled = false;
static bool prev_exit_area_filled = false;
// --- 출구 영역 안정화를 위한 변수 ---
static int exit_detection_counter = 0;
static const int EXIT_DETECTION_THRESHOLD = 5; // 연속 3회 감지되면 출구로 인식
// --- 입구 영역 안정화를 위한 변수 ---
static int entry_detection_counter = 0;
static const int ENTRY_DETECTION_THRESHOLD = 8; // 연속 5회 감지되면 입구로 인식 (더 엄격)
// --- 단일 게이트 중복 방지를 위한 변수 ---
static std::chrono::steady_clock::time_point last_entry_gate_detection_time;
static std::chrono::steady_clock::time_point last_exit_gate_detection_time;
static const double ENTRY_GATE_COOLDOWN_TIME = 8.0; // 진입 게이트 쿨다운 시간 (초)
static const double EXIT_GATE_COOLDOWN_TIME = 4.0; // 진출 게이트 쿨다운 시간 (초)
// --- 진출 게이트 픽셀 비율 추적 변수 ---
static double exit_gate_max_ratio = 0.0; // 진출 게이트 최대 픽셀 비율
static double exit_gate_min_ratio = 1.0; // 진출 게이트 최소 픽셀 비율
static bool exit_gate_ratio_initialized = false; // 진출 게이트 비율 초기화 여부
// --- 전역 변수 ---
unsigned int PLATFORM_SIZE = 0;
std::vector<std::vector<cv::Point>> platform_rois;
bool BUS_PLATFORM_STATUS[MAX_PLATFORM_COUNT] = {false};
std::mutex rois_mutex;
bool debug_mode = false; // 디버그 모드 플래그
std::atomic<bool> running(true);
std::atomic<bool> is_config_ready(false); // ROI 설정 완료 여부 플래그
std::atomic<bool> initial_bus_count_set(false); // 초기 버스 수 설정 완료 여부 플래그
std::atomic<bool> bus_count_corrected(false); // 버스 수 보정 완료 여부 플래그
// --- 공유 메모리 포인터 (상태 출력용) ---
int status_shm_fd = -1;
StopStatus* status_shm_ptr = nullptr;
// --- 데이터 큐 ---
static ThreadSafeQueue<std::shared_ptr<cv::Mat>> frame_queue;
static ThreadSafeQueue<std::shared_ptr<std::vector<cv::Mat>>> warped_queue;
static ThreadSafeQueue<std::shared_ptr<std::vector<cv::Mat>>> masked_queue;
static ThreadSafeQueue<std::shared_ptr<cv::Mat>> debug_frame_queue; // 디버깅용
// --- 디버깅용 카운터 ---
unsigned int total_frame = 0;
unsigned int frame_wasted = 0;
unsigned int warped_wasted = 0;
unsigned int masked_wasted = 0;
// --- 입출구 관련 변수 ---
// [추가] 입출구 감지 상태 및 시간 보정 변수
bool prev_entry_roi_filled = false;
bool prev_exit_roi_filled = false;
std::chrono::steady_clock::time_point last_entry_detected;
std::chrono::steady_clock::time_point last_exit_detected;
const double ENTRY_DELAY_SEC = 2.5;
const double EXIT_DELAY_SEC = 2.5;
// [추가] 연속 감지 방지를 위한 변수
std::chrono::steady_clock::time_point last_entry_counted;
std::chrono::steady_clock::time_point last_exit_counted;
const double MIN_ENTRY_INTERVAL_SEC = 2.0; // 최소 진입 간격 (초) - 완화
const double MIN_EXIT_INTERVAL_SEC = 1.0; // 최소 진출 간격 (초) - 완화
// [추가] 정류장 내 추정 버스 수
int estimated_bus_in_station = 0;
void update_bus_count_by_entry_exit(unsigned int platform_count, const bool* raw_status);
void initialize_platform_status(unsigned int platform_count);
void reset_platform_status(unsigned int platform_count); // 카운터 리셋용
void set_initial_bus_count(unsigned int platform_count, const bool* raw_status);
void correct_bus_count_if_needed(unsigned int platform_count, const bool* raw_status);
void reset_bus_count_to_platform_status(unsigned int platform_count, const bool* raw_status);
void process_bus_status(unsigned int stop_platform_count,
const bool* raw_status);
void process_gate_status(unsigned int total_platform_count,
const bool* raw_status);
void process_entry_exit_status(unsigned int total_platform_count,
const bool* raw_status);
void update_shared_status(unsigned int platform_count);
void video_read_thread(const std::string& video_filename);
void signal_handler(int signum) {
std::cout << "\nTermination signal received. Shutting down..." << std::endl;
running.store(false);
}
/**
* @brief CGI 스크립트로부터 유닉스 도메인 소켓을 통해 바이너리 ROI 설정을
* 수신하는 스레드.
*/
void receive_roi_config_thread() {
int server_fd;
struct sockaddr_un address;
if ((server_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
return;
}
memset(&address, 0, sizeof(struct sockaddr_un));
address.sun_family = AF_UNIX;
strncpy(address.sun_path, SOCKET_PATH, sizeof(address.sun_path) - 1);
unlink(SOCKET_PATH);
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
perror("bind failed");
close(server_fd);
return;
}
if (chmod(SOCKET_PATH, 0777) < 0) {
perror("chmod failed");
close(server_fd);
unlink(SOCKET_PATH);
return;
}
if (listen(server_fd, 5) < 0) {
perror("listen failed");
close(server_fd);
unlink(SOCKET_PATH);
return;
}
while (running.load()) {
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(server_fd, &read_fds);
struct timeval timeout;
timeout.tv_sec = 1; // 1초 타임아웃
timeout.tv_usec = 0;
int activity = select(server_fd + 1, &read_fds, NULL, NULL, &timeout);
if ((activity < 0) && (errno != EINTR)) {
perror("select error");
break;
}
if (FD_ISSET(server_fd, &read_fds)) {
int client_fd = accept(server_fd, NULL, NULL);
if (client_fd < 0) {
if (running.load()) perror("accept failed");
break;
}
std::cout << "CGI client connected. Receiving ROI data..." << std::endl;
std::vector<char> buffer;
char temp_buf[4096];
ssize_t bytes_read;
while ((bytes_read = read(client_fd, temp_buf, sizeof(temp_buf))) > 0) {
buffer.insert(buffer.end(), temp_buf, temp_buf + bytes_read);
}
try {
std::vector<std::vector<cv::Point>> temp_rois;
size_t offset = 0;
auto read_from_buffer = [&](void* dest, size_t len) {
if (offset + len > buffer.size())
throw std::runtime_error("Buffer underflow");
memcpy(dest, buffer.data() + offset, len);
offset += len;
};
uint32_t stop_count;
read_from_buffer(&stop_count, sizeof(stop_count));
if (stop_count < 2) {
throw std::runtime_error("ROI count must be at least 2 for gates.");
}
for (uint32_t i = 0; i < stop_count; ++i) {
uint32_t point_count;
read_from_buffer(&point_count, sizeof(point_count));
std::vector<cv::Point> roi;
for (uint32_t j = 0; j < point_count; ++j) {
int32_t x, y;
read_from_buffer(&x, sizeof(x));
read_from_buffer(&y, sizeof(y));
roi.emplace_back(x, y);
}
temp_rois.push_back(roi);
}
std::lock_guard<std::mutex> lock(rois_mutex);
platform_rois = temp_rois;
PLATFORM_SIZE = platform_rois.size();
// 플랫폼 상태 및 공유 메모리 초기화
initialize_platform_status(PLATFORM_SIZE);
std::cout << "✅ ROI configuration updated. Total platforms: "
<< PLATFORM_SIZE << std::endl;
std::cout << " - Stop Platforms: "
<< (PLATFORM_SIZE > 1 ? PLATFORM_SIZE - 2 : 0) << std::endl;
std::cout << " - Exit Gate: Platform " << PLATFORM_SIZE - 2
<< std::endl;
std::cout << " - Entry Gate: Platform " << PLATFORM_SIZE - 1
<< std::endl;
is_config_ready = true;
} catch (const std::exception& e) {
std::cerr << "Error during deserialization: " << e.what() << std::endl;
}
close(client_fd);
}
}
close(server_fd);
unlink(SOCKET_PATH);
}
/**
* @brief 공유 메모리에서 지속적으로 영상 프레임을 읽어와 큐에 넣는 스레드 함수
*/
void shm_read_thread() {
const size_t frame_size = FRAME_WIDTH * FRAME_HEIGHT * FRAME_CHANNELS;
int shm_fd = -1;
std::cout << "Trying to connect to shared memory " << SHM_NAME_FRAME << "..."
<< std::endl;
while (shm_fd == -1 && running.load()) {
shm_fd = shm_open(SHM_NAME_FRAME, O_RDONLY, 0666);
if (shm_fd == -1) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
if (!running.load()) return;
std::cout << "✅ Connected to shared memory." << std::endl;
void* ptr = mmap(0, frame_size, PROT_READ, MAP_SHARED, shm_fd, 0);
if (ptr == MAP_FAILED) {
perror("shm_read_thread mmap");
close(shm_fd);
running = false;
return;
}
cv::Mat shared_frame(FRAME_HEIGHT, FRAME_WIDTH, CV_8UC3, ptr);
cv::Mat balanced;
std::shared_ptr<cv::Mat> garbage;
while (running.load()) {
auto start_time = std::chrono::high_resolution_clock::now();
if (shared_frame.empty() || shared_frame.data == (uchar*)-1) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
continue;
}
cv::Mat local_frame;
shared_frame.copyTo(local_frame);
// ----- Debug -----
cv::Mat debug_frame = local_frame.clone();
{
std::lock_guard<std::mutex> lock(rois_mutex);
if (!platform_rois.empty()) {
// 일반 플랫폼은 초록색, 게이트는 다른 색으로 표시
for (size_t i = 0; i < platform_rois.size(); ++i) {
cv::Scalar color;
if (i == PLATFORM_SIZE - 2)
color = cv::Scalar(0, 0, 255); // Exit=Red
else if (i == PLATFORM_SIZE - 1)
color = cv::Scalar(255, 0, 0); // Entry=Blue
else
color = cv::Scalar(0, 255, 0); // Platform=Green
cv::polylines(debug_frame,
std::vector<std::vector<cv::Point>>{platform_rois[i]},
true, color, 2);
}
}
}
if (debug_frame_queue.size() < 10) {
debug_frame_queue.push(std::make_shared<cv::Mat>(std::move(debug_frame)));
}
// ----------------
if (frame_queue.size() > MAX_QUEUE_SIZE) {
frame_queue.try_pop(garbage);
frame_wasted++;
}
auto_brightness_balance(local_frame, balanced);
total_frame++;
frame_queue.push(std::make_shared<cv::Mat>(std::move(balanced)));
auto elapsed = std::chrono::high_resolution_clock::now() - start_time;
auto sleep_time =
FRAME_DURATION -
std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
if (sleep_time > std::chrono::milliseconds(0)) {
std::this_thread::sleep_for(sleep_time);
}
}
munmap(ptr, frame_size);
close(shm_fd);
}
/**
* @brief 상태 정보를 기록할 공유 메모리를 설정합니다.
* @return 성공 시 true, 실패 시 false
*/
bool setup_status_shm() {
umask(0);
status_shm_fd = shm_open(SHM_NAME_STATUS, O_CREAT | O_RDWR, 0777);
if (status_shm_fd == -1) {
perror("shm_open for status failed");
return false;
}
if (ftruncate(status_shm_fd, sizeof(StopStatus)) == -1) {
perror("ftruncate for status failed");
close(status_shm_fd);
shm_unlink(SHM_NAME_STATUS);
return false;
}
status_shm_ptr = (StopStatus*)mmap(0, sizeof(StopStatus), PROT_WRITE,
MAP_SHARED, status_shm_fd, 0);
if (status_shm_ptr == MAP_FAILED) {
perror("mmap for status failed");
close(status_shm_fd);
shm_unlink(SHM_NAME_STATUS);
status_shm_ptr = nullptr;
return false;
}
std::cout << "✅ Status shared memory '" << SHM_NAME_STATUS << "' is ready."
<< std::endl;
return true;
}
/**
* @brief 프로그램 종료 시 상태 공유 메모리를 해제합니다.
*/
void cleanup_status_shm() {
if (status_shm_ptr != nullptr && status_shm_ptr != MAP_FAILED) {
munmap(status_shm_ptr, sizeof(StopStatus));
}
if (status_shm_fd != -1) {
close(status_shm_fd);
}
shm_unlink(SHM_NAME_STATUS);
std::cout << "Status shared memory cleaned up." << std::endl;
}
/**
* @brief ROI 설정에 따라 플랫폼 상태 및 공유 메모리를 초기화합니다. (카운터 보존)
*/
void initialize_platform_status(unsigned int platform_count) {
// 카운팅 관련 변수 초기화 (ROI 설정 시에는 보존)
// entered_bus_count = 0; // 보존
// exited_bus_count = 0; // 보존
prev_entry_gate_status = false;
prev_exit_gate_status = false;
entry_gate_loss_counter = 0;
exit_gate_loss_counter = 0;
// 입구/출구 영역 상태 초기화
entry_area_filled = false;
exit_area_filled = false;
prev_entry_area_filled = false;
prev_exit_area_filled = false;
exit_detection_counter = 0;
entry_detection_counter = 0;
// 연속 감지 방지 변수 초기화
last_entry_counted = std::chrono::steady_clock::time_point();
last_exit_counted = std::chrono::steady_clock::time_point();
// 게이트 중복 방지 변수 초기화
last_entry_gate_detection_time = std::chrono::steady_clock::time_point();
last_exit_gate_detection_time = std::chrono::steady_clock::time_point();
// 진출 게이트 픽셀 비율 추적 변수 초기화
exit_gate_max_ratio = 0.0;
exit_gate_min_ratio = 1.0;
exit_gate_ratio_initialized = false;
// 플랫폼 상태 초기화
for (unsigned int i = 0; i < MAX_PLATFORM_COUNT; ++i) {
stable_status[i] = 0;
prev_stable_status[i] = 0;
detection_start_time[i] = std::chrono::steady_clock::time_point();
detection_loss_counter[i] = 0;
}
// 초기 버스 수는 별도 함수에서 설정
estimated_bus_in_station = 0;
if (status_shm_ptr == nullptr) return;
// 공유 메모리 초기화
for (unsigned int i = 0; i < MAX_PLATFORM_COUNT; ++i) {
if (i < platform_count) {
status_shm_ptr->platform_status[i] =
0; // 사용 플랫폼은 0(empty)으로 초기화
} else {
status_shm_ptr->platform_status[i] = -1; // 미사용 플랫폼은 -1로 초기화
}
}
strncpy(status_shm_ptr->station_id, STATION_ID,
sizeof(status_shm_ptr->station_id) - 1);
// 공유 메모리 카운터는 보존 (ROI 설정 시에는 리셋하지 않음)
// status_shm_ptr->entered_bus_count = 0; // 보존
// status_shm_ptr->exited_bus_count = 0; // 보존
status_shm_ptr->current_bus_count = 0;
status_shm_ptr->updated_at = time(nullptr);
}
/**
* @brief 플랫폼 상태 및 카운터를 완전히 리셋합니다.
*/
void reset_platform_status(unsigned int platform_count) {
// 카운팅 관련 변수 완전 초기화
entered_bus_count = 0;
exited_bus_count = 0;
prev_entry_gate_status = false;
prev_exit_gate_status = false;
entry_gate_loss_counter = 0;
exit_gate_loss_counter = 0;
// 입구/출구 영역 상태 초기화
entry_area_filled = false;
exit_area_filled = false;
prev_entry_area_filled = false;
prev_exit_area_filled = false;
exit_detection_counter = 0;
entry_detection_counter = 0;
// 연속 감지 방지 변수 초기화
last_entry_counted = std::chrono::steady_clock::time_point();
last_exit_counted = std::chrono::steady_clock::time_point();
// 게이트 중복 방지 변수 초기화
last_entry_gate_detection_time = std::chrono::steady_clock::time_point();
last_exit_gate_detection_time = std::chrono::steady_clock::time_point();
// 진출 게이트 픽셀 비율 추적 변수 초기화
exit_gate_max_ratio = 0.0;
exit_gate_min_ratio = 1.0;
exit_gate_ratio_initialized = false;
// 플랫폼 상태 초기화
for (unsigned int i = 0; i < MAX_PLATFORM_COUNT; ++i) {
stable_status[i] = 0;
prev_stable_status[i] = 0;
detection_start_time[i] = std::chrono::steady_clock::time_point();
detection_loss_counter[i] = 0;
}
// 초기 버스 수는 별도 함수에서 설정
estimated_bus_in_station = 0;
if (status_shm_ptr == nullptr) return;
// 공유 메모리 완전 초기화
for (unsigned int i = 0; i < MAX_PLATFORM_COUNT; ++i) {
if (i < platform_count) {
status_shm_ptr->platform_status[i] =
0; // 사용 플랫폼은 0(empty)으로 초기화
} else {
status_shm_ptr->platform_status[i] = -1; // 미사용 플랫폼은 -1로 초기화
}
}
strncpy(status_shm_ptr->station_id, STATION_ID,
sizeof(status_shm_ptr->station_id) - 1);
status_shm_ptr->entered_bus_count = 0; // 카운터 리셋
status_shm_ptr->exited_bus_count = 0; // 카운터 리셋
status_shm_ptr->current_bus_count = 0;
status_shm_ptr->updated_at = time(nullptr);
}
/**
* @brief 원본 감지 결과를 안정화된 상태로 변환합니다. (정차 플랫폼 전용)
*/
void process_bus_status(unsigned int stop_platform_count,
const bool* raw_status) {
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (raw_status[i]) { // 버스가 감지된 경우
detection_loss_counter[i] = 0; // 감지되었으므로 손실 카운터 리셋
// 이전에 정차 상태가 아니었을 때 (새로 감지 시작)
if (stable_status[i] == 0) {
// 감지 시작 시간을 기록한 적이 없다면, 현재 시간을 기록
if (detection_start_time[i].time_since_epoch().count() == 0) {
detection_start_time[i] = std::chrono::steady_clock::now();
}
// 경과 시간 계산
auto elapsed_time =
std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::steady_clock::now() - detection_start_time[i]);
// 경과 시간이 임계값을 넘으면 정차로 확정
if (elapsed_time.count() >= STABLE_TIME_THRESHOLD_S) {
stable_status[i] = 1;
}
}
} else { // 버스가 감지되지 않은 경우
detection_loss_counter[i]++;
// 허용된 손실 횟수를 초과하면, 모든 상태를 완전히 리셋
if (detection_loss_counter[i] > LOSS_TOLERANCE_CYCLES) {
stable_status[i] = 0;
detection_start_time[i] = std::chrono::steady_clock::time_point();
}
// 허용치 이내라면, 아무것도 하지 않고 타이머를 유지 (다음 감지를 기다림)
}
}
}
/**
* @brief 게이트의 상태를 처리하고 버스 진입/진출을 카운트합니다.
* 단일 게이트 내에서의 중복 감지를 방지합니다.
*/
void process_gate_status(unsigned int total_platform_count,
const bool* raw_status) {
if (total_platform_count < 2) return;
unsigned int exit_gate_idx = total_platform_count - 2;
unsigned int entry_gate_idx = total_platform_count - 1;
// --- 시간적 보정을 포함한 현재 게이트 상태 결정 ---
bool current_entry_gate_status;
if (raw_status[entry_gate_idx]) {
current_entry_gate_status = true;
entry_gate_loss_counter = 0;
} else {
entry_gate_loss_counter++;
if (entry_gate_loss_counter > GATE_LOSS_TOLERANCE_CYCLES) {
current_entry_gate_status = false;
} else {
current_entry_gate_status = prev_entry_gate_status; // 이전 상태 유지
}
}
bool current_exit_gate_status;
if (raw_status[exit_gate_idx]) {
current_exit_gate_status = true;
exit_gate_loss_counter = 0;
} else {
exit_gate_loss_counter++;
if (exit_gate_loss_counter > GATE_LOSS_TOLERANCE_CYCLES) {
current_exit_gate_status = false;
} else {
current_exit_gate_status = prev_exit_gate_status; // 이전 상태 유지
}
}
auto now = std::chrono::steady_clock::now();
// --- 단일 게이트 중복 감지 방지 ---
auto time_since_last_entry_detection = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_entry_gate_detection_time).count();
auto time_since_last_exit_detection = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_exit_gate_detection_time).count();
// 진입 게이트 처리
std::cout << "🔍 Entry Gate: prev=" << (prev_entry_gate_status ? "FILLED" : "EMPTY")
<< ", current=" << (current_entry_gate_status ? "FILLED" : "EMPTY") << std::endl;
if (!prev_entry_gate_status && current_entry_gate_status) {
// 진입 게이트 쿨다운 확인
if (time_since_last_entry_detection >= ENTRY_GATE_COOLDOWN_TIME) {
// 최소 간격 확인
auto time_since_last_entry = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_entry_counted).count();
if (time_since_last_entry >= MIN_ENTRY_INTERVAL_SEC) {
entered_bus_count++; // 디버깅용 카운트
estimated_bus_in_station++; // 현재 버스 수 직접 증가
last_entry_counted = now;
last_entry_gate_detection_time = now;
std::cout << "🚌 Bus entered through entry gate - Current: " << estimated_bus_in_station << std::endl;
} else {
std::cout << "⚠️ Gate entry detection ignored (too soon: "
<< std::fixed << std::setprecision(1) << time_since_last_entry
<< "s < " << MIN_ENTRY_INTERVAL_SEC << "s)" << std::endl;
}
} else {
std::cout << "⚠️ Entry gate cooldown active ("
<< std::fixed << std::setprecision(1) << time_since_last_entry_detection
<< "s < " << ENTRY_GATE_COOLDOWN_TIME << "s), ignoring" << std::endl;
}
} else if (prev_entry_gate_status != current_entry_gate_status) {
// 게이트 상태 변화 디버그 출력
std::cout << "🔍 Entry gate state: " << (prev_entry_gate_status ? "FILLED" : "EMPTY")
<< " -> " << (current_entry_gate_status ? "FILLED" : "EMPTY") << std::endl;
}
// 진출 게이트 처리
std::cout << "🔍 Exit Gate: prev=" << (prev_exit_gate_status ? "FILLED" : "EMPTY")
<< ", current=" << (current_exit_gate_status ? "FILLED" : "EMPTY") << std::endl;
if (!prev_exit_gate_status && current_exit_gate_status) {
// 진출 게이트 쿨다운 확인
if (time_since_last_exit_detection >= EXIT_GATE_COOLDOWN_TIME) {
// 최소 간격 확인
auto time_since_last_exit = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_exit_counted).count();
if (time_since_last_exit >= MIN_EXIT_INTERVAL_SEC) {
exited_bus_count++; // 디버깅용 카운트
estimated_bus_in_station--; // 현재 버스 수 직접 감소
if (estimated_bus_in_station < 0) estimated_bus_in_station = 0; // 음수 방지
last_exit_counted = now;
last_exit_gate_detection_time = now;
std::cout << "🚌 Bus exited through exit gate - Current: " << estimated_bus_in_station << std::endl;
} else {
std::cout << "⚠️ Gate exit detection ignored (too soon: "
<< std::fixed << std::setprecision(1) << time_since_last_exit
<< "s < " << MIN_EXIT_INTERVAL_SEC << "s)" << std::endl;
}
} else {
std::cout << "⚠️ Exit gate cooldown active ("
<< std::fixed << std::setprecision(1) << time_since_last_exit_detection
<< "s < " << EXIT_GATE_COOLDOWN_TIME << "s), ignoring" << std::endl;
}
} else if (prev_exit_gate_status != current_exit_gate_status) {
// 게이트 상태 변화 디버그 출력
std::cout << "🔍 Exit gate state: " << (prev_exit_gate_status ? "FILLED" : "EMPTY")
<< " -> " << (current_exit_gate_status ? "FILLED" : "EMPTY") << std::endl;
}
// 다음 사이클을 위해 현재 상태를 이전 상태로 저장
prev_entry_gate_status = current_entry_gate_status;
prev_exit_gate_status = current_exit_gate_status;
}
/**
* @brief ROI 설정 후 초기 버스 수를 플랫폼 중 filled된 개수로 설정합니다.
*/
void set_initial_bus_count(unsigned int platform_count, const bool* raw_status) {
if (platform_count < 2) return;
unsigned int stop_platform_count = platform_count - 2;
estimated_bus_in_station = 0;
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (raw_status[i]) {
estimated_bus_in_station++;
stable_status[i] = 1; // 이미 정차 상태로 설정
std::cout << " Platform " << i << ": BUS DETECTED (initial)" << std::endl;
}
}
std::cout << "🚌 Initial bus count set to: " << estimated_bus_in_station
<< " (based on " << stop_platform_count << " platforms)" << std::endl;
}
/**
* @brief 현재 버스 수와 실제 감지된 버스 수를 비교하여 필요시 보정합니다.
* 단순한 진입-진출 방식으로 변경되었으므로 보정 로직을 단순화합니다.
*/
void correct_bus_count_if_needed(unsigned int platform_count, const bool* raw_status) {
if (platform_count < 2) return;
unsigned int stop_platform_count = platform_count - 2;
int detected_bus_count = 0;
// 현재 플랫폼에서 감지된 버스 수 계산
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (raw_status[i]) {
detected_bus_count++;
}
}
// 현재 추정 버스 수와 감지된 버스 수 비교
if (detected_bus_count != estimated_bus_in_station) {
std::cout << "🔧 Bus count correction needed:" << std::endl;
std::cout << " Current estimated: " << estimated_bus_in_station << std::endl;
std::cout << " Actually detected: " << detected_bus_count << std::endl;
// 단순히 감지된 버스 수로 설정 (진입-진출 카운트는 보존)
estimated_bus_in_station = detected_bus_count;
std::cout << " ✅ Bus count corrected to: " << estimated_bus_in_station << std::endl;
}
}
/**
* @brief R키를 눌렀을 때 호출되는 보정 함수. 현재 버스 수를 채워진 플랫폼 수로 맞추고 진입/진출 카운트를 0으로 리셋합니다.
*/
void reset_bus_count_to_platform_status(unsigned int platform_count, const bool* raw_status) {
if (platform_count < 2) return;
unsigned int stop_platform_count = platform_count - 2;
int detected_bus_count = 0;
// 현재 플랫폼에서 감지된 버스 수 계산
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (raw_status[i]) {
detected_bus_count++;
}
}
std::cout << "\n🔄 Manual bus count reset (R key pressed):" << std::endl;
std::cout << " Previous estimated: " << estimated_bus_in_station << std::endl;
std::cout << " Previous entered: " << entered_bus_count << std::endl;
std::cout << " Previous exited: " << exited_bus_count << std::endl;
std::cout << " Currently detected: " << detected_bus_count << std::endl;
// 현재 버스 수를 감지된 플랫폼 수로 설정
estimated_bus_in_station = detected_bus_count;
// 진입/진출 카운트를 0으로 리셋
entered_bus_count = 0;
exited_bus_count = 0;
std::cout << " ✅ Reset completed:" << std::endl;
std::cout << " Current bus count: " << estimated_bus_in_station << std::endl;
std::cout << " Entry count: " << entered_bus_count << std::endl;
std::cout << " Exit count: " << exited_bus_count << std::endl;
}
/**
* @brief 입구/출구 영역의 상태 변화를 감지하여 버스 진입/진출을 추적합니다.
* 안정화된 상태 변화 감지 알고리즘을 사용합니다.
*/
void process_entry_exit_status(unsigned int total_platform_count,
const bool* raw_status) {
if (total_platform_count < 2) return;
unsigned int exit_gate_idx = total_platform_count - 2;
unsigned int entry_gate_idx = total_platform_count - 1;
// 현재 입구/출구 영역 상태
bool current_entry_filled = raw_status[entry_gate_idx];
bool current_exit_filled = raw_status[exit_gate_idx];
// 이전 상태와 비교하여 변화 감지
bool entry_state_changed = (prev_entry_area_filled != current_entry_filled);
bool exit_state_changed = (prev_exit_area_filled != current_exit_filled);
// 출구 영역 안정화 로직
if (current_exit_filled) {
exit_detection_counter++;
} else {
exit_detection_counter = 0;
}
// 입구 영역 안정화 로직
if (current_entry_filled) {
entry_detection_counter++;
} else {
entry_detection_counter = 0;
}
auto now = std::chrono::steady_clock::now();
// --- 단일 게이트 중복 감지 방지 ---
auto time_since_last_entry_detection = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_entry_gate_detection_time).count();
auto time_since_last_exit_detection = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_exit_gate_detection_time).count();
// 출구 영역이 빈 상태였다가 안정적으로 찬 상태가 되면 버스가 나가는 것으로 인식
if (!prev_exit_area_filled && exit_detection_counter >= EXIT_DETECTION_THRESHOLD) {
// 진출 게이트 쿨다운 확인
if (time_since_last_exit_detection >= EXIT_GATE_COOLDOWN_TIME) {
// 최소 간격 확인
auto time_since_last_exit = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_exit_counted).count();
if (time_since_last_exit >= MIN_EXIT_INTERVAL_SEC) {
exited_bus_count++; // 디버깅용 카운트
estimated_bus_in_station--; // 현재 버스 수 직접 감소
if (estimated_bus_in_station < 0) estimated_bus_in_station = 0; // 음수 방지
last_exit_counted = now;
last_exit_gate_detection_time = now;
std::cout << "🚌 Bus exited through exit gate (stable detection) - Current: " << estimated_bus_in_station << std::endl;
} else {
std::cout << "⚠️ Exit detection ignored (too soon: "
<< std::fixed << std::setprecision(1) << time_since_last_exit
<< "s < " << MIN_EXIT_INTERVAL_SEC << "s)" << std::endl;
}
} else {
std::cout << "⚠️ Exit gate cooldown active (stable: "
<< std::fixed << std::setprecision(1) << time_since_last_exit_detection
<< "s < " << EXIT_GATE_COOLDOWN_TIME << "s), ignoring" << std::endl;
}
}
// 입구 영역이 찬 상태였다가 안정적으로 빈 상태가 되면 버스가 맨 뒤 플랫폼에 진입한 것으로 판단
if (prev_entry_area_filled && entry_detection_counter == 0) {
// 진입 게이트 쿨다운 확인
if (time_since_last_entry_detection >= ENTRY_GATE_COOLDOWN_TIME) {
// 최소 간격 확인
auto time_since_last_entry = std::chrono::duration_cast<std::chrono::duration<double>>(
now - last_entry_counted).count();
if (time_since_last_entry >= MIN_ENTRY_INTERVAL_SEC) {
entered_bus_count++; // 디버깅용 카운트
estimated_bus_in_station++; // 현재 버스 수 직접 증가
last_entry_counted = now;
last_entry_gate_detection_time = now;
std::cout << "🚌 Bus entered through entry gate (stable detection) - Current: " << estimated_bus_in_station << std::endl;
} else {
std::cout << "⚠️ Entry detection ignored (too soon: "
<< std::fixed << std::setprecision(1) << time_since_last_entry
<< "s < " << MIN_ENTRY_INTERVAL_SEC << "s)" << std::endl;
}
} else {
std::cout << "⚠️ Entry gate cooldown active (stable: "
<< std::fixed << std::setprecision(1) << time_since_last_entry_detection
<< "s < " << ENTRY_GATE_COOLDOWN_TIME << "s), ignoring" << std::endl;
}
}
// 현재 정류장 내 버스 수는 직접 증감 방식으로 관리 (진입/진출 카운트는 디버깅용)
if (estimated_bus_in_station < 0) {
estimated_bus_in_station = 0; // 음수가 되지 않도록 보정
}
// 다음 사이클을 위해 현재 상태를 이전 상태로 저장
// 입구 영역은 안정화된 상태로만 업데이트
if (entry_detection_counter >= ENTRY_DETECTION_THRESHOLD) {
prev_entry_area_filled = true;
} else if (entry_detection_counter == 0) {
prev_entry_area_filled = false;
}
// 출구 영역은 안정화된 상태로만 업데이트
if (exit_detection_counter >= EXIT_DETECTION_THRESHOLD) {
prev_exit_area_filled = true;
} else if (exit_detection_counter == 0) {
prev_exit_area_filled = false;
}
// 디버그 정보 출력 (상태 변화 시)
if (exit_state_changed) {
std::cout << "🔍 Exit gate state changed: "
<< (prev_exit_area_filled ? "FILLED" : "EMPTY")
<< " -> "
<< (current_exit_filled ? "FILLED" : "EMPTY")
<< " (counter: " << exit_detection_counter << "/" << EXIT_DETECTION_THRESHOLD << ")" << std::endl;
}
if (entry_state_changed) {
std::cout << "🔍 Entry gate state changed: "
<< (prev_entry_area_filled ? "FILLED" : "EMPTY")
<< " -> "
<< (current_entry_filled ? "FILLED" : "EMPTY")
<< " (counter: " << entry_detection_counter << "/" << ENTRY_DETECTION_THRESHOLD << ")" << std::endl;
}
}
/**
* @brief 플랫폼 상태가 순차적으로 채워져 있는지 확인합니다.
* @return true: 순차적으로 채워짐 (예: 0000, 1000, 1100, 1110, 1111), false: 그렇지 않음
*/
bool is_platform_status_sequential(unsigned int platform_count) {
if (platform_count < 2) return false;
unsigned int stop_platform_count = platform_count - 2;
if (stop_platform_count == 0) return true;
// 모든 플랫폼이 비어있는 경우 (0000)
bool all_empty = true;
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (stable_status[i] != 0) {
all_empty = false;
break;
}
}
if (all_empty) return true;
// 순차적으로 채워져 있는지 확인 (0번부터 연속으로)
// true: 0000, 1000, 1100, 1110, 1111
// false: 1001, 0110, 1010, 0101 등 (중간에 빈 플랫폼이 있거나 0번부터 시작하지 않는 경우)
// 첫 번째로 채워진 플랫폼의 위치 찾기
int first_filled = -1;
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (stable_status[i] != 0) {
first_filled = i;
break;
}
}
// 버스가 하나도 없으면 true (0000)
if (first_filled == -1) return true;
// 첫 번째 버스가 0번이 아니면 false (0110, 0101 등)
if (first_filled != 0) return false;
// 0번부터 연속으로 채워져 있는지 확인
for (unsigned int i = 0; i < stop_platform_count; ++i) {
if (stable_status[i] == 0) {
// 빈 플랫폼을 찾았으면, 그 이후로는 모두 빈 플랫폼이어야 함
for (unsigned int j = i + 1; j < stop_platform_count; ++j) {
if (stable_status[j] != 0) {
return false; // 중간에 빈 플랫폼이 있는데 그 뒤에 버스가 있으면 false
}
}
break; // 첫 번째 빈 플랫폼 이후는 모두 빈 플랫폼이어야 함
}
}
return true;
}
/**
* @brief 진입/진출이 발생했는지 확인합니다.
* @return true: 진입 또는 진출이 발생, false: 발생하지 않음
*/
bool has_entry_or_exit_occurred() {
static int prev_entered_count = 0;
static int prev_exited_count = 0;
bool entry_occurred = (entered_bus_count != prev_entered_count);
bool exit_occurred = (exited_bus_count != prev_exited_count);
prev_entered_count = entered_bus_count;
prev_exited_count = exited_bus_count;