diff --git a/socket/modbus.py b/socket/modbus.py index 91e366e..8cb3c28 100644 --- a/socket/modbus.py +++ b/socket/modbus.py @@ -25,7 +25,7 @@ PPT 8페이지(일괄 읽기) 최신 매핑(사용자 제공): - 값의 합리성 체크(클램프)를 통해 가장 그럴듯한 해석을 최종 선택한다. """ -import os, asyncio, struct, base64, re, socket +import os, asyncio, struct, base64, re, socket, pymysql from datetime import datetime, timezone from typing import Dict, List, Any, Optional, Tuple @@ -48,6 +48,10 @@ TS_BUFFERS: Dict[str, deque] = {} TS_MAX = int(os.getenv("TS_MAX", "500")) # keep up to 500 samples per device TS_PERIOD_SEC = float(os.getenv("TS_PERIOD_SEC", "2.0")) # poll every 2 seconds +# db연결 +conn = pymysql.connect(host='49.238.167.71', user='helmet', password='helmet2824', db='helmet', charset='utf8') +cur = conn.cursor() + async def _poll_devices_task(): """Periodically read bulk8 (1..30) from all connected devices and store last TS_MAX samples.""" while True: @@ -513,6 +517,16 @@ def ts_get(req: TSSamplesReq): return {"ok": True, "target": key, "count": 0, "samples": []} n = min(len(dq), req.limit) samples = list(dq)[-n:] + + # db 저장 + now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + cur.execute('insert into sensor_data values (null, "{}", "{}", {}, {}, {}, {})'.format(samples[0]['key'], now, samples[0]['lock'], samples[0]['helmet'], samples[0]['uv_state'], samples[0]['fan_state'])) + conn.commit() + cur.execute('insert into env_data values (null, "{}", "{}", {}, {}, {}, {})'.format(samples[0]['key'], now, 1, 1, samples[0]['temp'], samples[0]['humi'])) + conn.commit() + cur.execute('insert into battery values (null, "{}", "{}", {}, {}, {}, {})'.format(samples[0]['key'], now, samples[0]['batt_pct'], samples[0]['pv_volt'], samples[0]['pv_curr'], samples[0]['chg_done'])) + conn.commit() + return {"ok": True, "target": key, "count": n, "samples": samples} # ----- UI ----- diff --git a/socket/requirements.txt b/socket/requirements.txt index 19453a1..5da27c4 100644 --- a/socket/requirements.txt +++ b/socket/requirements.txt @@ -1,4 +1,5 @@ fastapi +pymysql uvicorn[standard] python-multipart pymodbus>=3.5,<4 \ No newline at end of file