75 lines
2.9 KiB
Python
75 lines
2.9 KiB
Python
import time
|
|
import pymysql
|
|
import datetime
|
|
|
|
DB_CONFIG = {
|
|
'host': 'localhost',
|
|
'user': 'root',
|
|
'password': 'password',
|
|
'database': 'mmcl_db',
|
|
'autocommit': True
|
|
}
|
|
|
|
def get_db_connection():
|
|
try:
|
|
return pymysql.connect(**DB_CONFIG)
|
|
except Exception as e:
|
|
print(f"DB Connection Error: {e}")
|
|
return None
|
|
|
|
def run_agent():
|
|
print("Starting Warning Light Agent...")
|
|
while True:
|
|
conn = get_db_connection()
|
|
if not conn:
|
|
time.sleep(2)
|
|
continue
|
|
|
|
try:
|
|
with conn.cursor() as cursor:
|
|
# Target과 Current가 다른 LED 센서 찾기
|
|
sql = """SELECT sensor_no,
|
|
target_ch1_statusID, value_ch1_statusID,
|
|
target_ch2_statusID, value_ch2_statusID,
|
|
target_ch3_statusID, value_ch3_statusID
|
|
FROM sensor_info
|
|
WHERE sensor_typeid = 2
|
|
AND (
|
|
(target_ch1_statusID IS NOT NULL AND target_ch1_statusID != IFNULL(value_ch1_statusID, -1)) OR
|
|
(target_ch2_statusID IS NOT NULL AND target_ch2_statusID != IFNULL(value_ch2_statusID, -1)) OR
|
|
(target_ch3_statusID IS NOT NULL AND target_ch3_statusID != IFNULL(value_ch3_statusID, -1))
|
|
)"""
|
|
cursor.execute(sql)
|
|
tasks = cursor.fetchall()
|
|
|
|
for task in tasks:
|
|
sensor_no = task[0]
|
|
t_ch1, v_ch1 = task[1], task[2]
|
|
t_ch2, v_ch2 = task[3], task[4]
|
|
t_ch3, v_ch3 = task[5], task[6]
|
|
|
|
print(f"[Warning Light Agent] 센서 {sensor_no} 경광등 상태 변경 감지.")
|
|
print(f" -> 하드웨어 제어 중 (Green:{t_ch1}, Yellow:{t_ch2}, Red:{t_ch3})...")
|
|
time.sleep(1) # 물리적 처리 시간 모킹
|
|
|
|
# 동기화 처리
|
|
new_v1 = t_ch1 if t_ch1 is not None else v_ch1
|
|
new_v2 = t_ch2 if t_ch2 is not None else v_ch2
|
|
new_v3 = t_ch3 if t_ch3 is not None else v_ch3
|
|
|
|
update_sql = """UPDATE sensor_info
|
|
SET value_ch1_statusID = %s, value_ch2_statusID = %s, value_ch3_statusID = %s, update_time = %s
|
|
WHERE sensor_no = %s"""
|
|
cursor.execute(update_sql, (new_v1, new_v2, new_v3, datetime.datetime.now(), sensor_no))
|
|
print(f" -> 하드웨어 제어 완료 및 DB 동기화 완료: {sensor_no}")
|
|
|
|
except Exception as e:
|
|
print(f"Error: {e}")
|
|
finally:
|
|
conn.close()
|
|
|
|
time.sleep(1)
|
|
|
|
if __name__ == "__main__":
|
|
run_agent()
|