generated from Fac2Real/.github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp2.py
More file actions
758 lines (659 loc) · 46.2 KB
/
app2.py
File metadata and controls
758 lines (659 loc) · 46.2 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
import streamlit as st
from service.ZoneScenario import ZoneScenario # 실제 클래스 경로로 가정
from service.EquipScenario import EquipScenario # 실제 클래스 경로로 가정
import asyncio
import time
import threading
from mqtt.publish import AwsMQTT # 실제 클래스 경로로 가정
# --- asyncio 루프를 별도 스레드에서 관리하기 위한 헬퍼 ---
def run_async_in_thread(loop, coro):
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(coro)
except Exception as e:
# Streamlit UI에 오류 로깅 (애플리케이션이 실행 중일 때만 가능)
try:
st.error(f"비동기 스레드 오류: {e}")
except Exception: # st.error가 실패할 수 있는 경우 (예: 앱 종료 중)
pass
print(f"비동기 스레드 오류: {e}") # 디버깅을 위해 콘솔에 출력
import traceback
traceback.print_exc()
finally:
# 스레드가 종료될 때 루프가 닫히도록 함
# run_until_complete가 모든 작업을 완료하면 루프를 중지함
# loop.close() # 여기서 닫으면 run_coroutine_threadsafe 문제 발생 가능
print("Async thread loop processing finished.")
# --- MQTT 및 시나리오 초기화 ---
# (기존 MQTT 및 시나리오 경로 초기화 유지)
if "conn_zone_temp" not in st.session_state:
st.session_state.conn_zone_temp = AwsMQTT("zone_temp")
if "conn_zone_voc" not in st.session_state:
st.session_state.conn_zone_voc = AwsMQTT("zone_voc")
if "conn_zone_humidity" not in st.session_state:
st.session_state.conn_zone_humidity = AwsMQTT("zone_humid")
if "conn_zone_dust" not in st.session_state:
st.session_state.conn_zone_dust = AwsMQTT("zone_dust")
if "conn_temp" not in st.session_state:
st.session_state.conn_temp = AwsMQTT("temp")
if "conn_humid" not in st.session_state:
st.session_state.conn_humid = AwsMQTT("humid")
if "conn_pressure" not in st.session_state:
st.session_state.conn_pressure = AwsMQTT("pressure")
if "conn_vibration" not in st.session_state:
st.session_state.conn_vibration = AwsMQTT("vibration")
if "conn_active" not in st.session_state:
st.session_state.conn_active = AwsMQTT("active")
if "conn_reactive" not in st.session_state:
st.session_state.conn_reactive = AwsMQTT("reactive")
################################################################################################
# 시나리오 파일 경로 설정(공간) - 중합공정
env_temp_normal_path = r".\data\scenario1_중합공정\공간\온도센서\중합설비_온도_정상.csv"
env_temp_normal_to_warn_path = r".\data\scenario1_중합공정\공간\온도센서\중합설비_온도_정상_이상.csv"
env_temp_warn_path = r".\data\scenario1_중합공정\공간\온도센서\중합설비_온도_이상.csv"
env_temp_warn_to_normal_path = r".\data\scenario1_중합공정\공간\온도센서\중합설비_온도_이상_정상.csv"
env_voc_normal_path = r".\data\scenario1_중합공정\공간\voc센서\중합설비_voc_정상.csv"
env_voc_normal_to_warn_path = r".\data\scenario1_중합공정\공간\voc센서\중합설비_voc_정상_이상.csv"
env_voc_warn_path = r".\data\scenario1_중합공정\공간\voc센서\중합설비_voc_이상.csv"
env_voc_warn_to_normal_path = r".\data\scenario1_중합공정\공간\voc센서\중합설비_voc_이상_정상.csv"
# 시나리오 파일 경로 설정(설비) - 중합공정
eqp_temp_normal_path = r".\data\scenario1_중합공정\설비\온도센서\중합설비_온도_정상.csv"
eqp_temp_normal_to_warn_path = r".\data\scenario1_중합공정\설비\온도센서\중합설비_온도_정상_이상.csv"
eqp_temp_warn_path = r".\data\scenario1_중합공정\설비\온도센서\중합설비_온도_이상.csv"
eqp_temp_warn_to_normal_path = r".\data\scenario1_중합공정\설비\온도센서\중합설비_온도_이상_정상.csv"
eqp_humidity_normal_path = r".\data\scenario1_중합공정\설비\습도센서\중합설비_습도_정상.csv"
eqp_humidity_normal_to_warn_path = r".\data\scenario1_중합공정\설비\습도센서\중합설비_습도_정상_이상.csv"
eqp_humidity_warn_path = r".\data\scenario1_중합공정\설비\습도센서\중합설비_습도_이상.csv"
eqp_humidity_warn_to_normal_path = r".\data\scenario1_중합공정\설비\습도센서\중합설비_습도_이상_정상.csv"
eqp_pressure_normal_path = r".\data\scenario1_중합공정\설비\압력센서\중합설비_압력_정상.csv"
eqp_pressure_normal_to_warn_path = r".\data\scenario1_중합공정\설비\압력센서\중합설비_압력_정상_이상.csv"
eqp_pressure_warn_path = r".\data\scenario1_중합공정\설비\압력센서\중합설비_압력_이상.csv"
eqp_pressure_warn_to_normal_path = r".\data\scenario1_중합공정\설비\압력센서\중합설비_압력_이상_정상.csv"
eqp_vibration_normal_path = r".\data\scenario1_중합공정\설비\진동센서\중합설비_진동_정상.csv"
eqp_vibration_normal_to_warn_path = r".\data\scenario1_중합공정\설비\진동센서\중합설비_진동_정상_이상.csv"
eqp_vibration_warn_path = r".\data\scenario1_중합공정\설비\진동센서\중합설비_진동_이상.csv"
eqp_vibration_warn_to_normal_path = r".\data\scenario1_중합공정\설비\진동센서\중합설비_진동_이상_정상.csv"
eqp_active_normal_path = r".\data\scenario1_중합공정\설비\active\중합설비_active_정상.csv"
eqp_active_normal_to_warn_path = r".\data\scenario1_중합공정\설비\active\중합설비_active_정상_이상.csv"
eqp_active_warn_path = r".\data\scenario1_중합공정\설비\active\중합설비_active_이상.csv"
eqp_active_warn_to_normal_path = r".\data\scenario1_중합공정\설비\active\중합설비_active_이상_정상.csv"
eqp_reactive_normal_path = r".\data\scenario1_중합공정\설비\reactive\중합설비_reactive_정상.csv"
eqp_reactive_normal_to_warn_path = r".\data\scenario1_중합공정\설비\reactive\중합설비_reactive_정상_이상.csv"
eqp_reactive_warn_path = r".\data\scenario1_중합공정\설비\reactive\중합설비_reactive_이상.csv"
eqp_reactive_warn_to_normal_path = r".\data\scenario1_중합공정\설비\reactive\중합설비_reactive_이상_정상.csv"
################################################################################################
# 시나리오 파일 경로 설정(공간) - 탈휘공정
scenario2_env_temp_normal_path = r".\data\scenario2_탈휘공정\공간\온도센서\온도_정상.csv"
scenario2_env_temp_normal_to_warn_path = r".\data\scenario2_탈휘공정\공간\온도센서\온도_정상_이상.csv"
scenario2_env_temp_warn_path = r".\data\scenario2_탈휘공정\공간\온도센서\온도_이상.csv"
scenario2_env_temp_warn_to_normal_path = r".\data\scenario2_탈휘공정\공간\온도센서\온도_이상_정상.csv"
scenario2_env_voc_normal_path = r".\data\scenario2_탈휘공정\공간\voc센서\voc_정상.csv"
scenario2_env_voc_normal_to_warn_path = r".\data\scenario2_탈휘공정\공간\voc센서\voc_정상_이상.csv"
scenario2_env_voc_warn_path = r".\data\scenario2_탈휘공정\공간\voc센서\voc_이상.csv"
scenario2_env_voc_warn_to_normal_path = r".\data\scenario2_탈휘공정\공간\voc센서\voc_이상_정상.csv"
scenario2_env_humidity_normal_path = r".\data\scenario2_탈휘공정\공간\습도센서\습도_정상.csv"
scenario2_env_humidity_normal_to_warn_path = r".\data\scenario2_탈휘공정\공간\습도센서\습도_정상_이상.csv"
scenario2_env_humidity_warn_path = r".\data\scenario2_탈휘공정\공간\습도센서\습도_이상.csv"
scenario2_env_humidity_warn_to_normal_path = r".\data\scenario2_탈휘공정\공간\습도센서\습도_이상_정상.csv"
scenario2_env_dust_normal_path = r".\data\scenario2_탈휘공정\공간\먼지센서\먼지_정상.csv"
scenario2_env_dust_normal_to_warn_path = r".\data\scenario2_탈휘공정\공간\먼지센서\먼지_정상_이상.csv"
scenario2_env_dust_warn_path = r".\data\scenario2_탈휘공정\공간\먼지센서\먼지_이상.csv"
scenario2_env_dust_warn_to_normal_path = r".\data\scenario2_탈휘공정\공간\먼지센서\먼지_이상_정상.csv"
# 시나리오 파일 경로 설정(설비) - 탈휘공정
scenario2_eqp_temp_normal_path = r".\data\scenario2_탈휘공정\설비\온도센서\온도_정상.csv"
scenario2_eqp_temp_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\온도센서\온도_정상_이상.csv"
scenario2_eqp_temp_warn_path = r".\data\scenario2_탈휘공정\설비\온도센서\온도_이상.csv"
scenario2_eqp_temp_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\온도센서\온도_이상_정상.csv"
scenario2_eqp_humidity_normal_path = r".\data\scenario2_탈휘공정\설비\습도센서\습도_정상.csv"
scenario2_eqp_humidity_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\습도센서\습도_정상_이상.csv"
scenario2_eqp_humidity_warn_path = r".\data\scenario2_탈휘공정\설비\습도센서\습도_이상.csv"
scenario2_eqp_humidity_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\습도센서\습도_이상_정상.csv"
scenario2_eqp_pressure_normal_path = r".\data\scenario2_탈휘공정\설비\압력센서\압력_정상.csv"
scenario2_eqp_pressure_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\압력센서\압력_정상_이상.csv"
scenario2_eqp_pressure_warn_path = r".\data\scenario2_탈휘공정\설비\압력센서\압력_이상.csv"
scenario2_eqp_pressure_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\압력센서\압력_이상_정상.csv"
scenario2_eqp_vibration_normal_path = r".\data\scenario2_탈휘공정\설비\진동센서\진동_정상.csv"
scenario2_eqp_vibration_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\진동센서\진동_정상_이상.csv"
scenario2_eqp_vibration_warn_path = r".\data\scenario2_탈휘공정\설비\진동센서\진동_이상.csv"
scenario2_eqp_vibration_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\진동센서\진동_이상_정상.csv"
scenario2_eqp_active_normal_path = r".\data\scenario2_탈휘공정\설비\active\active_정상.csv"
scenario2_eqp_active_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\active\active_정상_이상.csv"
scenario2_eqp_active_warn_path = r".\data\scenario2_탈휘공정\설비\active\active_이상.csv"
scenario2_eqp_active_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\active\active_이상_정상.csv"
scenario2_eqp_reactive_normal_path = r".\data\scenario2_탈휘공정\설비\reactive\reactive_정상.csv"
scenario2_eqp_reactive_normal_to_warn_path = r".\data\scenario2_탈휘공정\설비\reactive\reactive_정상_이상.csv"
scenario2_eqp_reactive_warn_path = r".\data\scenario2_탈휘공정\설비\reactive\reactive_이상.csv"
scenario2_eqp_reactive_warn_to_normal_path = r".\data\scenario2_탈휘공정\설비\reactive\reactive_이상_정상.csv"
################################################################################################
# 상태 초기화
if "zone_scenario_temp" not in st.session_state:
st.session_state.zone_scenario_temp = ZoneScenario(
env_temp_normal_path, env_temp_normal_to_warn_path, env_temp_warn_path, env_temp_warn_to_normal_path, st.session_state.conn_zone_temp
)
if "zone_scenario_voc" not in st.session_state:
st.session_state.zone_scenario_voc = ZoneScenario(
env_voc_normal_path, env_voc_normal_to_warn_path, env_voc_warn_path, env_voc_warn_to_normal_path, st.session_state.conn_zone_voc
)
# EquipScenario 인스턴스가 ZoneScenario와 동일한 인터페이스를 갖는다고 가정
if "equip_scenario_temp" not in st.session_state:
st.session_state.equip_scenario_temp = EquipScenario( # 또는 ZoneScenario를 사용하지만 다른 경로로
eqp_temp_normal_path, eqp_temp_normal_to_warn_path, eqp_temp_warn_path, eqp_temp_warn_to_normal_path, st.session_state.conn_temp
)
if "equip_scenario_humidity" not in st.session_state:
st.session_state.equip_scenario_humidity = EquipScenario(
eqp_humidity_normal_path, eqp_humidity_normal_to_warn_path, eqp_humidity_warn_path, eqp_humidity_warn_to_normal_path, st.session_state.conn_humid
)
if "equip_scenario_pressure" not in st.session_state:
st.session_state.equip_scenario_pressure = EquipScenario(
eqp_pressure_normal_path, eqp_pressure_normal_to_warn_path, eqp_pressure_warn_path, eqp_pressure_warn_to_normal_path, st.session_state.conn_pressure
)
if "equip_scenario_vibration" not in st.session_state:
st.session_state.equip_scenario_vibration = EquipScenario(
eqp_vibration_normal_path, eqp_vibration_normal_to_warn_path, eqp_vibration_warn_path, eqp_vibration_warn_to_normal_path, st.session_state.conn_vibration
)
if "equip_scenario_active" not in st.session_state:
st.session_state.equip_scenario_active = EquipScenario(
eqp_active_normal_path, eqp_active_normal_to_warn_path, eqp_active_warn_path, eqp_active_warn_to_normal_path, st.session_state.conn_active
)
if "equip_scenario_reactive" not in st.session_state:
st.session_state.equip_scenario_reactive = EquipScenario(
eqp_reactive_normal_path, eqp_reactive_normal_to_warn_path, eqp_reactive_warn_path, eqp_reactive_warn_to_normal_path, st.session_state.conn_reactive
)
if "scenario2_zone_temp" not in st.session_state:
st.session_state.scenario2_zone_temp = ZoneScenario(
scenario2_env_temp_normal_path,
scenario2_env_temp_normal_to_warn_path,
scenario2_env_temp_warn_path,
scenario2_env_temp_warn_to_normal_path,
st.session_state.conn_zone_temp
)
if "scenario2_zone_voc" not in st.session_state:
st.session_state.scenario2_zone_voc = ZoneScenario(
scenario2_env_voc_normal_path,
scenario2_env_voc_normal_to_warn_path,
scenario2_env_voc_warn_path,
scenario2_env_voc_warn_to_normal_path,
st.session_state.conn_zone_voc
)
if "scenario2_zone_humidity" not in st.session_state:
st.session_state.scenario2_zone_humidity = ZoneScenario(
scenario2_env_humidity_normal_path,
scenario2_env_humidity_normal_to_warn_path,
scenario2_env_humidity_warn_path,
scenario2_env_humidity_warn_to_normal_path,
st.session_state.conn_zone_humidity
)
if "scenario2_zone_dust" not in st.session_state:
st.session_state.scenario2_zone_dust = ZoneScenario(
scenario2_env_dust_normal_path,
scenario2_env_dust_normal_to_warn_path,
scenario2_env_dust_warn_path,
scenario2_env_dust_warn_to_normal_path,
st.session_state.conn_zone_dust
)
if "scenario2_equip_temp" not in st.session_state:
st.session_state.scenario2_equip_temp = EquipScenario(
scenario2_eqp_temp_normal_path,
scenario2_eqp_temp_normal_to_warn_path,
scenario2_eqp_temp_warn_path,
scenario2_eqp_temp_warn_to_normal_path,
st.session_state.conn_temp
)
if "scenario2_equip_humidity" not in st.session_state:
st.session_state.scenario2_equip_humidity = EquipScenario(
scenario2_eqp_humidity_normal_path,
scenario2_eqp_humidity_normal_to_warn_path,
scenario2_eqp_humidity_warn_path,
scenario2_eqp_humidity_warn_to_normal_path,
st.session_state.conn_humid
)
if "scenario2_equip_pressure" not in st.session_state:
st.session_state.scenario2_equip_pressure = EquipScenario(
scenario2_eqp_pressure_normal_path,
scenario2_eqp_pressure_normal_to_warn_path,
scenario2_eqp_pressure_warn_path,
scenario2_eqp_pressure_warn_to_normal_path,
st.session_state.conn_pressure
)
if "scenario2_equip_vibration" not in st.session_state:
st.session_state.scenario2_equip_vibration = EquipScenario(
scenario2_eqp_vibration_normal_path,
scenario2_eqp_vibration_normal_to_warn_path,
scenario2_eqp_vibration_warn_path,
scenario2_eqp_vibration_warn_to_normal_path,
st.session_state.conn_vibration
)
if "scenario2_equip_active" not in st.session_state:
st.session_state.scenario2_equip_active = EquipScenario(
scenario2_eqp_active_normal_path,
scenario2_eqp_active_normal_to_warn_path,
scenario2_eqp_active_warn_path,
scenario2_eqp_active_warn_to_normal_path,
st.session_state.conn_active
)
if "scenario2_equip_reactive" not in st.session_state:
st.session_state.scenario2_equip_reactive = EquipScenario(
scenario2_eqp_reactive_normal_path,
scenario2_eqp_reactive_normal_to_warn_path,
scenario2_eqp_reactive_warn_path,
scenario2_eqp_reactive_warn_to_normal_path,
st.session_state.conn_reactive
)
# 시나리오 실행 상태 및 비동기 루프/스레드에 대한 세션 상태
if "scenario_running" not in st.session_state:
st.session_state.scenario_running = False
if "async_loop" not in st.session_state:
st.session_state.async_loop = asyncio.new_event_loop()
if "async_thread" not in st.session_state:
st.session_state.async_thread = None
if "scenario2_running" not in st.session_state:
st.session_state.scenario2_running = False
if "async_thread_tab2" not in st.session_state:
st.session_state.async_thread_tab2 = None
# 비동기 상태 변경 및 실행 함수 (코루틴)
async def start_scenario_task(scenario_obj):
"""
단일 시나리오 객체의 current_state 및 stop_event를 기반으로 실행 루프를 관리합니다.
또한 전환이 진행 중인지 확인하기 위해 transition_in_progress_event를 사용합니다.
"""
scenario_name = scenario_obj.__class__.__name__
# 객체에 고유한 경로 속성이 있는 경우 식별자 추가 (ZoneScenario, EquipScenario 모두 해당)
if hasattr(scenario_obj, 'normal_path') and scenario_obj.normal_path:
try:
scenario_name += f" ({scenario_obj.normal_path.split(r'\\')[-1]})" # 원시 문자열 경로 분할
except: # 경로가 예상과 다를 경우를 대비한 예외 처리
scenario_name += " (path error)"
print(f"APP: [{scenario_name}] 관리자 작업 시작 중")
# 초기 시작 시 상태를 "normal"로 설정하고 stop_event를 해제합니다.
# transition_in_progress_event도 "set"(전환 중 아님)으로 설정되어 있는지 확인합니다.
if scenario_obj.current_state == "stopped": # 새로운 시작일 때만
scenario_obj.current_state = "normal"
if hasattr(scenario_obj, 'stop_event'): # stop_event가 있는지 확인
scenario_obj.stop_event.clear()
if hasattr(scenario_obj, 'transition_in_progress_event'): # transition_in_progress_event가 있는지 확인
scenario_obj.transition_in_progress_event.set() # 자유로운 상태로 설정
while hasattr(scenario_obj, 'stop_event') and not scenario_obj.stop_event.is_set():
# 새 안정 상태 루프를 실행하기 전에 진행 중인 전환이 완료될 때까지 기다립니다.
if hasattr(scenario_obj, 'transition_in_progress_event'):
# print(f"APP: [{scenario_name}] '{scenario_obj.current_state}' 상태 루프 전에 전환 이벤트 대기 중 (is_set={scenario_obj.transition_in_progress_event.is_set()})")
await scenario_obj.transition_in_progress_event.wait() # 이벤트가 clear()되면 여기서 차단됨
# print(f"APP: [{scenario_name}] 전환 이벤트 설정됨. '{scenario_obj.current_state}' 상태로 진행")
else: # transition_in_progress_event가 없는 경우 (예: EquipScenario가 아직 업데이트되지 않은 경우)
print(f"APP: [{scenario_name}] transition_in_progress_event 없음. 직접 진행.")
if scenario_obj.stop_event.is_set(): # 대기 후 다시 중지 이벤트 확인
print(f"APP: [{scenario_name}] 전환 대기 후 중지 이벤트 감지. 종료 중.")
break
current_loop_state = scenario_obj.current_state
if current_loop_state == "normal":
print(f"APP: [{scenario_name}] NORMAL 데이터 루프 진입 ({scenario_obj.normal_path})")
await scenario_obj.execute_scenario_loop(scenario_obj.normal_path, "normal")
elif current_loop_state == "warn":
print(f"APP: [{scenario_name}] WARN 데이터 루프 진입 ({scenario_obj.warn_path})")
await scenario_obj.execute_scenario_loop(scenario_obj.warn_path, "warn")
elif current_loop_state == "stopped":
print(f"APP: [{scenario_name}] 상태가 'stopped'입니다. 관리자 작업 종료 중.")
break
else:
print(f"APP: [{scenario_name}] 알 수 없는 상태 '{current_loop_state}'. 0.1초 대기.")
await asyncio.sleep(0.1) # 알 수 없는 상태에서 무한 루프 방지
# execute_scenario_loop가 반환되면 다음 중 하나 때문일 수 있습니다:
# 1. 외부 상태 변경 (current_state != 실행 중이던 state_parameter)
# 2. stop_event 설정됨
# 3. transition_in_progress_event가 해제됨 (새 전환 시작 신호)
# 외부 루프가 다시 평가하고, await transition_in_progress_event.wait()가 #3을 처리합니다.
# print(f"APP: [{scenario_name}] '{current_loop_state}'에 대한 주 루프 종료됨. 다음 작업 확인 중.")
await asyncio.sleep(0.01) # 다른 작업(예: UI 업데이트)을 위한 약간의 양보
print(f"APP: [{scenario_name}] 관리자 작업 종료됨.")
async def change_scenario_state_task(scenario_obj, new_state):
"""
전환을 처리하고 시나리오 객체의 current_state를 업데이트합니다.
이 시나리오 객체에 대해 실행 중인 start_scenario_task가 새 상태를 선택합니다.
"""
scenario_name = scenario_obj.__class__.__name__
if hasattr(scenario_obj, 'normal_path') and scenario_obj.normal_path:
try:
scenario_name += f" ({scenario_obj.normal_path.split(r'\\')[-1]})"
except:
scenario_name += " (path error)"
previous_internal_state = scenario_obj.current_state
print(f"APP: [{scenario_name}] 상태를 '{previous_internal_state}'에서 '{new_state}'(으)로 변경 요청")
# transition_in_progress_event가 있고 설정되어 있는지 확인 (전환 중이 아님)
can_transition = True
if hasattr(scenario_obj, 'transition_in_progress_event'):
if not scenario_obj.transition_in_progress_event.is_set():
can_transition = False
print(f"APP: [{scenario_name}] 전환이 이미 진행 중이므로 '{new_state}'(으)로의 상태 변경 건너뜀.")
if not can_transition and new_state != "stop": # 중지 요청은 항상 진행되어야 함
return
if new_state == "warn":
if previous_internal_state != "warn":
print(f"APP: [{scenario_name}] 'normal_to_warn' 전환 실행 중.")
await scenario_obj.handle_state_change_to_warn() # 전환 데이터를 재생하고 이벤트를 설정/해제
scenario_obj.current_state = "warn" # 중요: 상태 업데이트
print(f"APP: [{scenario_name}] 상태가 공식적으로 'warn'으로 설정됨.")
else:
print(f"APP: [{scenario_name}] 이미 'warn' 상태이거나 해당 상태로 전환 중입니다. 조치 없음.")
elif new_state == "normal":
if previous_internal_state != "normal":
print(f"APP: [{scenario_name}] 'warn_to_normal' 전환 실행 중.")
await scenario_obj.handle_state_change_to_normal() # 전환 데이터를 재생하고 이벤트를 설정/해제
scenario_obj.current_state = "normal" # 중요: 상태 업데이트
print(f"APP: [{scenario_name}] 상태가 공식적으로 'normal'으로 설정됨.")
else:
print(f"APP: [{scenario_name}] 이미 'normal' 상태이거나 해당 상태로 전환 중입니다. 조치 없음.")
elif new_state == "stop":
print(f"APP: [{scenario_name}] 'stop' 핸들러 실행 중.")
await scenario_obj.handle_state_change_to_stop() # stop_event 및 current_state = "stopped" 설정
print(f"APP: [{scenario_name}] 'stop' 핸들러 완료됨.")
else:
print(f"APP: [{scenario_name}] 알 수 없는 new_state '{new_state}' 요청됨.")
async def run_all_scenarios_async_explicit(scenarios_and_initial_paths):
tasks = []
for sc_obj, _ in scenarios_and_initial_paths:
tasks.append(start_scenario_task(sc_obj))
await asyncio.gather(*tasks)
async def change_all_states_async_explicit(scenario_objects, new_state):
tasks = []
for sc_obj in scenario_objects:
tasks.append(change_scenario_state_task(sc_obj, new_state))
await asyncio.gather(*tasks)
st.title("시연용 시뮬레이터")
tab1, tab2 = st.tabs(["중합 공정 시나리오", "탈휘 공정 시나리오"]) # "탈휘 공정 시나리오" 탭은 현재 비어 있음
with tab1:
col1, col_spacer, col2 = st.columns([2, 0.5, 3])
with col2:
st.subheader("상태 표시")
status_placeholders = {
"zone_temp": st.empty(),
"zone_voc": st.empty(),
"": st.empty(), # 빈 공간을 위한 자리 표시자
"equip_temp": st.empty(),
"equip_humidity": st.empty(),
"equip_pressure": st.empty(),
"equip_vibration": st.empty(),
"equip_active": st.empty(),
"equip_reactive": st.empty(),
}
def update_status_display():
# 이 메서드가 존재하고 적절한 문자열을 반환하는지 확인
# scenario 객체가 get_current_value 메서드를 가지고 있다고 가정
status_placeholders["zone_temp"].write(f"공간 온도: {st.session_state.zone_scenario_temp.get_current_value()}")
status_placeholders["zone_voc"].write(f"공간 VOC: {st.session_state.zone_scenario_voc.get_current_value()}")
status_placeholders["equip_temp"].write(f"설비 온도: {st.session_state.equip_scenario_temp.get_current_value()}")
status_placeholders["equip_humidity"].write(f"설비 습도: {st.session_state.equip_scenario_humidity.get_current_value()}")
status_placeholders["equip_pressure"].write(f"설비 압력: {st.session_state.equip_scenario_pressure.get_current_value()}")
status_placeholders["equip_vibration"].write(f"설비 진동: {st.session_state.equip_scenario_vibration.get_current_value()}")
status_placeholders["equip_active"].write(f"설비 유효전류: {st.session_state.equip_scenario_active.get_current_value()}")
status_placeholders["equip_reactive"].write(f"설비 무효전류류: {st.session_state.equip_scenario_reactive.get_current_value()}")
update_status_display() # 초기 표시
message_placeholder = st.empty()
def get_all_scenario_objects_and_paths():
return [
(st.session_state.zone_scenario_temp, env_temp_normal_path),
(st.session_state.zone_scenario_voc, env_voc_normal_path),
(st.session_state.equip_scenario_temp, eqp_temp_normal_path),
(st.session_state.equip_scenario_humidity, eqp_humidity_normal_path),
(st.session_state.equip_scenario_pressure, eqp_pressure_normal_path),
(st.session_state.equip_scenario_vibration, eqp_vibration_normal_path),
(st.session_state.equip_scenario_active, eqp_active_normal_path),
(st.session_state.equip_scenario_reactive, eqp_reactive_normal_path),
]
def get_all_scenario_objects():
return [item[0] for item in get_all_scenario_objects_and_paths()]
with col1:
st.subheader("제어 버튼")
if st.button("시나리오 실행"):
if not st.session_state.scenario_running:
st.session_state.scenario_running = True
message_placeholder.info("시나리오 실행 중...")
scenarios_with_paths = get_all_scenario_objects_and_paths()
# 새 실행을 위해 모든 시나리오 객체가 재설정되었는지 확인
for sc_obj, _ in scenarios_with_paths:
sc_obj.current_state = "stopped" # start_scenario_task에 의해 normal로 설정됨
if hasattr(sc_obj, 'stop_event'):
sc_obj.stop_event.clear()
if hasattr(sc_obj, 'transition_in_progress_event'):
sc_obj.transition_in_progress_event.set() # 중요: 자유로운 상태인지 확인
if hasattr(sc_obj, '_running'): sc_obj._running = True # ZoneScenario에 있는 경우
coro_to_run = run_all_scenarios_async_explicit(scenarios_with_paths)
if st.session_state.async_loop.is_closed(): # 루프가 열려 있는지 확인
st.session_state.async_loop = asyncio.new_event_loop()
st.session_state.async_thread = threading.Thread(
target=run_async_in_thread,
args=(st.session_state.async_loop, coro_to_run),
daemon=True # 스레드를 데몬으로 만들어 주 스레드 종료 시 자동 종료되도록 함
)
st.session_state.async_thread.start()
time.sleep(0.2) # 스레드가 시작되고 상태를 업데이트할 시간을 줌
st.rerun()
else:
message_placeholder.warning("시나리오가 이미 실행 중입니다.")
if st.button("정상 -> 이상"):
if st.session_state.scenario_running:
if st.session_state.async_loop and st.session_state.async_loop.is_running():
message_placeholder.info("상태를 '정상 -> 이상'으로 변경 요청 중...")
all_scenarios = get_all_scenario_objects()
coro_for_state_change = change_all_states_async_explicit(all_scenarios, "warn")
asyncio.run_coroutine_threadsafe(coro_for_state_change, st.session_state.async_loop)
message_placeholder.success("상태 변경 요청됨 ('정상 -> 이상').")
else:
message_placeholder.error("비동기 루프가 실행 중이 아닙니다. 상태를 변경할 수 없습니다.")
else:
message_placeholder.warning("시나리오가 실행 중이지 않습니다. 먼저 실행하세요.")
if st.button("이상 -> 정상"):
if st.session_state.scenario_running:
if st.session_state.async_loop and st.session_state.async_loop.is_running():
message_placeholder.info("상태를 '이상 -> 정상'으로 변경 요청 중...")
all_scenarios = get_all_scenario_objects()
coro_for_state_change = change_all_states_async_explicit(all_scenarios, "normal")
asyncio.run_coroutine_threadsafe(coro_for_state_change, st.session_state.async_loop)
message_placeholder.success("상태 변경 요청됨 ('이상 -> 정상').")
else:
message_placeholder.error("비동기 루프가 실행 중이 아닙니다. 상태를 변경할 수 없습니다.")
else:
message_placeholder.warning("시나리오가 실행 중이지 않습니다. 먼저 실행하세요.")
if st.button("중지"):
if st.session_state.scenario_running:
message_placeholder.info("시나리오 중지 요청 중...")
all_scenarios = get_all_scenario_objects()
coro_for_stop = change_all_states_async_explicit(all_scenarios, "stop")
if st.session_state.async_loop and st.session_state.async_loop.is_running():
future = asyncio.run_coroutine_threadsafe(coro_for_stop, st.session_state.async_loop)
try:
future.result(timeout=10) # 모든 작업이 중지 신호를 처리할 때까지 기다림
message_placeholder.success("모든 시나리오 중지 신호 처리 완료.")
except TimeoutError:
message_placeholder.warning("시나리오 중지 신호 처리 시간 초과.")
except Exception as e:
message_placeholder.error(f"중지 중 비동기 작업 오류 발생: {e}")
else:
# 루프가 실행 중이 아니면 UI 일관성을 위해 수동으로 상태 설정
for sc_obj in all_scenarios:
sc_obj.current_state = "stopped"
if hasattr(sc_obj, 'stop_event'): sc_obj.stop_event.set()
message_placeholder.warning("비동기 루프가 실행 중이 아니었습니다. 상태가 강제로 중지됨으로 설정되었습니다.")
st.session_state.scenario_running = False # UI 업데이트를 중지하고 다시 시작할 수 있도록 하는 기본 플래그
# 스레드가 실제로 완료될 때까지 기다림
if st.session_state.async_thread and st.session_state.async_thread.is_alive():
print("APP: async_thread가 조인되기를 기다리는 중...")
st.session_state.async_thread.join(timeout=5) # 스레드가 종료될 시간을 줌
if st.session_state.async_thread.is_alive():
message_placeholder.warning("백그라운드 스레드가 아직 실행 중입니다. (조인 시간 초과)")
else:
message_placeholder.info("백그라운드 스레드 정상 종료됨.")
st.session_state.async_thread = None # 스레드 정리
message_placeholder.success("시나리오가 중지되었습니다.")
time.sleep(0.1) # UI가 업데이트되기 전에 rerun 허용
st.rerun() # 중지된 상태 및 버튼 사용 가능성을 반영하기 위해 rerun
else:
message_placeholder.warning("시나리오가 이미 중지되어 있습니다.")
# 시나리오가 실행 중인 경우 상태에 대한 자동 새로고침 루프
if "scenario_running" in st.session_state and st.session_state.scenario_running:
# 비동기 루프가 여전히 활성 상태이거나 스레드가 존재하는지 확인
# 이는 소프트 확인이며, 실제 제어는 scenario_running입니다.
loop_is_active = st.session_state.async_loop and st.session_state.async_loop.is_running()
thread_is_active = st.session_state.async_thread and st.session_state.async_thread.is_alive()
if loop_is_active or thread_is_active : # 둘 중 하나라도 활성이면 UI 업데이트
time.sleep(1) # 새로고침 간격
update_status_display()
try: # st.rerun()은 스크립트 실행 중이 아닐 때 호출되면 오류 발생 가능
st.rerun()
except st.errors.StreamlitAPIException as e:
if "st.rerun() can only be called when a script is running." in str(e):
print("Rerun failed as script is not actively running (likely during shutdown).")
else:
raise e # 다른 StreamlitAPIException은 다시 발생시킴
else:
# 루프/스레드가 예기치 않게 종료되었지만 scenario_running이 true인 경우 수정합니다.
# 이는 스레드에서 처리되지 않은 예외가 발생할 때 발생할 수 있습니다.
if st.session_state.scenario_running: # 경쟁 조건을 피하기 위해 다시 확인
st.warning("백그라운드 작업이 예기치 않게 종료된 것 같습니다. 상태를 '중지됨'으로 변경합니다.")
st.session_state.scenario_running = False
# UI에 대해 일관된 "중지됨" 상태로 시나리오 객체 강제 설정
for sc_obj in get_all_scenario_objects():
sc_obj.current_state = "stopped"
if hasattr(sc_obj, 'stop_event'): sc_obj.stop_event.set()
if hasattr(sc_obj, 'current_value'): sc_obj.current_value = "중지됨 (예기치 않음)"
if hasattr(sc_obj, 'transition_in_progress_event'): sc_obj.transition_in_progress_event.set()
update_status_display() # 중지됨을 표시하도록 UI 업데이트
try:
st.rerun() # 변경 사항을 반영하기 위해 rerun
except st.errors.StreamlitAPIException as e:
if "st.rerun() can only be called when a script is running." in str(e):
print("Rerun failed (unexpected shutdown) as script is not actively running.")
else:
raise e
with tab2:
col1, col_spacer, col2 = st.columns([2, 0.5, 3])
with col2:
st.subheader("상태 표시 (탈휘 공정)")
status_placeholders_tab2 = {
"zone_temp": st.empty(),
"zone_voc": st.empty(),
"zone_humidity": st.empty(),
"zone_dust": st.empty(),
"equip_temp": st.empty(),
"equip_humidity": st.empty(),
"equip_pressure": st.empty(),
"equip_vibration": st.empty(),
"equip_active": st.empty(),
"equip_reactive": st.empty(),
}
def update_status_display_tab2():
# 탈휘 공정 시나리오 상태 표시 업데이트
status_placeholders_tab2["zone_temp"].write(f"공간 온도: {st.session_state.scenario2_zone_temp.get_current_value()}")
status_placeholders_tab2["zone_voc"].write(f"공간 VOC: {st.session_state.scenario2_zone_voc.get_current_value()}")
status_placeholders_tab2["zone_humidity"].write(f"공간 습도: {st.session_state.scenario2_zone_humidity.get_current_value()}")
status_placeholders_tab2["zone_dust"].write(f"공간 먼지: {st.session_state.scenario2_zone_dust.get_current_value()}")
status_placeholders_tab2["equip_temp"].write(f"설비 온도: {st.session_state.scenario2_equip_temp.get_current_value()}")
status_placeholders_tab2["equip_humidity"].write(f"설비 습도: {st.session_state.scenario2_equip_humidity.get_current_value()}")
status_placeholders_tab2["equip_pressure"].write(f"설비 압력: {st.session_state.scenario2_equip_pressure.get_current_value()}")
status_placeholders_tab2["equip_vibration"].write(f"설비 진동: {st.session_state.scenario2_equip_vibration.get_current_value()}")
status_placeholders_tab2["equip_active"].write(f"설비 Active: {st.session_state.scenario2_equip_active.get_current_value()}")
status_placeholders_tab2["equip_reactive"].write(f"설비 Reactive: {st.session_state.scenario2_equip_reactive.get_current_value()}")
update_status_display_tab2() # 초기 상태 표시
message_placeholder_tab2 = st.empty()
def get_all_scenario2_objects_and_paths():
return [
(st.session_state.scenario2_zone_temp, scenario2_env_temp_normal_path),
(st.session_state.scenario2_zone_voc, scenario2_env_voc_normal_path),
(st.session_state.scenario2_zone_humidity, scenario2_env_humidity_normal_path),
(st.session_state.scenario2_zone_dust, scenario2_env_dust_normal_path),
(st.session_state.scenario2_equip_temp, scenario2_eqp_temp_normal_path),
(st.session_state.scenario2_equip_humidity, scenario2_eqp_humidity_normal_path),
(st.session_state.scenario2_equip_pressure, scenario2_eqp_pressure_normal_path),
(st.session_state.scenario2_equip_vibration, scenario2_eqp_vibration_normal_path),
(st.session_state.scenario2_equip_active, scenario2_eqp_active_normal_path),
(st.session_state.scenario2_equip_reactive, scenario2_eqp_reactive_normal_path),
]
def get_all_scenario2_objects():
return [item[0] for item in get_all_scenario2_objects_and_paths()]
with col1:
st.subheader("제어 버튼 (탈휘 공정)")
if st.button("시나리오 실행 (탈휘 공정)"):
if not st.session_state.scenario2_running:
st.session_state.scenario2_running = True
message_placeholder_tab2.info("탈휘 공정 시나리오 실행 중...")
scenarios_with_paths_tab2 = get_all_scenario2_objects_and_paths()
# 새 실행을 위해 모든 시나리오 객체가 재설정되었는지 확인
for sc_obj, _ in scenarios_with_paths_tab2:
sc_obj.current_state = "stopped" # start_scenario_task에 의해 normal로 설정됨
if hasattr(sc_obj, 'stop_event'):
sc_obj.stop_event.clear()
if hasattr(sc_obj, 'transition_in_progress_event'):
sc_obj.transition_in_progress_event.set() # 중요: 자유로운 상태인지 확인
if hasattr(sc_obj, '_running'):
sc_obj._running = True # ZoneScenario에 있는 경우
coro_to_run_tab2 = run_all_scenarios_async_explicit(scenarios_with_paths_tab2)
if st.session_state.async_loop.is_closed(): # 루프가 열려 있는지 확인
st.session_state.async_loop = asyncio.new_event_loop()
st.session_state.async_thread_tab2 = threading.Thread(
target=run_async_in_thread,
args=(st.session_state.async_loop, coro_to_run_tab2),
daemon=True # 스레드를 데몬으로 만들어 주 스레드 종료 시 자동 종료되도록 함
)
st.session_state.async_thread_tab2.start()
time.sleep(0.2) # 스레드가 시작되고 상태를 업데이트할 시간을 줌
st.rerun()
else:
message_placeholder_tab2.warning("탈휘 공정 시나리오가 이미 실행 중입니다.")
if st.button("정상 -> 이상 (탈휘 공정)"):
if st.session_state.scenario2_running:
if st.session_state.async_loop and st.session_state.async_loop.is_running():
message_placeholder_tab2.info("상태를 '정상 -> 이상'으로 변경 요청 중...")
all_scenarios_tab2 = get_all_scenario2_objects()
coro_for_state_change_tab2 = change_all_states_async_explicit(all_scenarios_tab2, "warn")
asyncio.run_coroutine_threadsafe(coro_for_state_change_tab2, st.session_state.async_loop)
message_placeholder_tab2.success("상태 변경 요청됨 ('정상 -> 이상').")
else:
message_placeholder_tab2.error("비동기 루프가 실행 중이 아닙니다. 상태를 변경할 수 없습니다.")
else:
message_placeholder_tab2.warning("탈휘 공정 시나리오가 실행 중이지 않습니다. 먼저 실행하세요.")
if st.button("이상 -> 정상 (탈휘 공정)"):
if st.session_state.scenario2_running:
if st.session_state.async_loop and st.session_state.async_loop.is_running():
message_placeholder_tab2.info("상태를 '이상 -> 정상'으로 변경 요청 중...")
all_scenarios_tab2 = get_all_scenario2_objects()
coro_for_state_change_tab2 = change_all_states_async_explicit(all_scenarios_tab2, "normal")
asyncio.run_coroutine_threadsafe(coro_for_state_change_tab2, st.session_state.async_loop)
message_placeholder_tab2.success("상태 변경 요청됨 ('이상 -> 정상').")
else:
message_placeholder_tab2.error("비동기 루프가 실행 중이 아닙니다. 상태를 변경할 수 없습니다.")
else:
message_placeholder_tab2.warning("탈휘 공정 시나리오가 실행 중이지 않습니다. 먼저 실행하세요.")
if st.button("중지 (탈휘 공정)"):
if st.session_state.scenario2_running:
message_placeholder_tab2.info("탈휘 공정 시나리오 중지 요청 중...")
all_scenarios_tab2 = get_all_scenario2_objects()
coro_for_stop_tab2 = change_all_states_async_explicit(all_scenarios_tab2, "stop")
if st.session_state.async_loop and st.session_state.async_loop.is_running():
future_tab2 = asyncio.run_coroutine_threadsafe(coro_for_stop_tab2, st.session_state.async_loop)
try:
future_tab2.result(timeout=10) # 모든 작업이 중지 신호를 처리할 때까지 기다림
message_placeholder_tab2.success("모든 탈휘 공정 시나리오 중지 신호 처리 완료.")
except TimeoutError:
message_placeholder_tab2.warning("탈휘 공정 시나리오 중지 신호 처리 시간 초과.")
except Exception as e:
message_placeholder_tab2.error(f"중지 중 비동기 작업 오류 발생: {e}")
else:
# 루프가 실행 중이 아니면 UI 일관성을 위해 수동으로 상태 설정
for sc_obj in all_scenarios_tab2:
sc_obj.current_state = "stopped"
if hasattr(sc_obj, 'stop_event'):
sc_obj.stop_event.set()
message_placeholder_tab2.warning("비동기 루프가 실행 중이 아니었습니다. 상태가 강제로 중지됨으로 설정되었습니다.")
st.session_state.scenario2_running = False # UI 업데이트를 중지하고 다시 시작할 수 있도록 하는 기본 플래그
# 스레드가 실제로 완료될 때까지 기다림
if st.session_state.async_thread_tab2 and st.session_state.async_thread_tab2.is_alive():
print("APP: async_thread_tab2가 조인되기를 기다리는 중...")
st.session_state.async_thread_tab2.join(timeout=5) # 스레드가 종료될 시간을 줌
if st.session_state.async_thread_tab2.is_alive():
message_placeholder_tab2.warning("백그라운드 스레드가 아직 실행 중입니다. (조인 시간 초과)")
else:
message_placeholder_tab2.info("백그라운드 스레드 정상 종료됨.")
st.session_state.async_thread_tab2 = None # 스레드 정리
message_placeholder_tab2.success("탈휘 공정 시나리오가 중지되었습니다.")
time.sleep(0.1) # UI가 업데이트되기 전에 rerun 허용
st.rerun()
else:
message_placeholder_tab2.warning("탈휘 공정 시나리오가 이미 중지되어 있습니다.")