From 8ed1a239318a574edde98c7750650e3101686b59 Mon Sep 17 00:00:00 2001 From: kim Date: Thu, 22 Oct 2026 10:41:28 +0900 Subject: [PATCH] =?UTF-8?q?=EC=98=A8=EC=8B=A4=20=EB=B0=B1=ED=95=84:=20HA?= =?UTF-8?q?=EA=B0=80=20=EC=9E=A0=EB=93=A0=20=EC=8B=9C=EA=B0=84=EC=97=90=20?= =?UTF-8?q?'=EC=A7=81=EC=A0=84=20=EA=B0=92=20=EA=B7=B8=EB=8C=80=EB=A1=9C'?= =?UTF-8?q?=EB=A1=9C=20=EB=A7=8C=EB=93=A0=20=EC=9E=A5=EA=B8=B0=20=ED=86=B5?= =?UTF-8?q?=EA=B3=84(=EC=8B=9C=EA=B0=84=EB=B3=84=20=ED=8F=89=EA=B7=A0?= =?UTF-8?q?=C2=B7=EC=B5=9C=EC=A0=80=C2=B7=EC=B5=9C=EA=B3=A0)=EB=8F=84=20?= =?UTF-8?q?=ED=8C=8C=EC=9D=B4=20CSV=20=EA=B0=92=EC=9C=BC=EB=A1=9C=20?= =?UTF-8?q?=EB=8D=AE=EC=96=B4=EC=94=80(=EB=8C=80=EA=B8=B0=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D,=20=ED=96=89=EC=9D=B4=20=EC=83=9D=EA=B8=B4=20?= =?UTF-8?q?=EB=92=A4=EC=97=90=EB=A7=8C=20=EC=88=98=EC=A0=95)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- scripts/greenhouse-backfill.py | 40 ++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/scripts/greenhouse-backfill.py b/scripts/greenhouse-backfill.py index bf24cdf..8c694e2 100755 --- a/scripts/greenhouse-backfill.py +++ b/scripts/greenhouse-backfill.py @@ -9,15 +9,19 @@ HA와 MQTT 브로커가 있는 클로서버는 매일 02시에 자서 기상 때 정상 동작 중엔 이렇게 오래 비지 않는다). 구간 양끝 60초 안쪽은 건드리지 않는다. - 값이 직전과 같으면 넣지 않는다(HA도 바뀔 때만 기록한다). attributes는 그 엔티티의 최근 것을 재사용. - HA가 돌고 있어도 된다(WAL + busy timeout). 이미 채운 구간은 다음 실행 때 빈 구간이 아니므로 반복해도 안전. -- 10일(recorder 보관 기간) 넘은 장기 통계 그래프에는 반영되지 않는다(시간별 통계는 HA가 따로 만든다). +- 장기 통계(statistics, 시간별 평균·최저·최고 — 대시보드 한달/지난달 탭과 10일 넘은 기록이 이걸 쓴다)도 고친다. + HA는 자고 일어나면 빈 시간의 통계를 '잠들기 직전 값 그대로'(평평한 값)로 만들어 둔다. 채운 시간대를 대기 목록 + (~/.cache/greenhouse-backfill.json)에 올려 두고, HA가 그 시간 통계 행을 만든 뒤에 CSV 값으로 덮어쓴다(행 추가는 안 함 — + HA가 같은 시간 행을 나중에 넣으려다 충돌하지 않게). 사흘 넘게 행이 안 생긴 시간은 목록에서 뺀다. 사용: greenhouse-backfill.py [--apply] [--days N] (기본 dry-run, 최근 2일) """ -import csv, io, os, sqlite3, subprocess, sys, time +import csv, io, json, os, sqlite3, subprocess, sys, time from datetime import datetime, timedelta DB = os.environ.get("HA_DB", "/home/kim/homeassistant/home-assistant_v2.db") PI = os.environ.get("GREENHOUSE_PI", "kim@192.168.0.123") GAP_S = 600 +PENDING = os.path.expanduser("~/.cache/greenhouse-backfill.json") ENTITIES = { "air.temperature": "sensor.onsil_onsil_gonggi_temperature", "air.humidity": "sensor.onsil_onsil_gonggi_humidity", @@ -91,10 +95,42 @@ def main(): cur.execute("INSERT INTO states (state, attributes_id, last_changed_ts, last_reported_ts, last_updated_ts," " metadata_id) VALUES (?,?,?,?,?,?)", (v, aid, row["ts"], row["ts"], row["ts"], mid)) inserted[key] += 1 + # 장기 통계: 빈 구간에 걸친 시간(정시 시작)을 대기 목록에 올리고, 행이 있는 시간만 CSV로 덮어쓴다 + try: + pending = set(json.load(open(PENDING))) + except (OSError, ValueError): + pending = set() + now = time.time() + for a, b in gaps: + h = int(a // 3600 * 3600) + while h < b and h + 3600 <= now: + pending.add(h); h += 3600 + fixed = 0 + for h in sorted(pending): + done = True + for key, ent in ENTITIES.items(): + vals = [float(r[key]) for r in rows if h <= r["ts"] < h + 3600 and r.get(key) not in ("", None)] + sm = cur.execute("SELECT id FROM statistics_meta WHERE statistic_id=?", (ent,)).fetchone() + if not sm or len(vals) < 30: + continue + st = cur.execute("SELECT id FROM statistics WHERE metadata_id=? AND start_ts=?", (sm[0], h)).fetchone() + if not st: + done = done and now - h < 3 * 86400 # HA가 아직 안 만듦 → 다음에 다시 + continue + if APPLY: + cur.execute("UPDATE statistics SET mean=?, min=?, max=? WHERE id=?", + (round(sum(vals) / len(vals), 3), min(vals), max(vals), st[0])) + fixed += 1 + if done: + pending.discard(h) + if APPLY: + os.makedirs(os.path.dirname(PENDING), exist_ok=True) + json.dump(sorted(pending), open(PENDING, "w")) con.commit(); con.close() fmt = lambda t: datetime.fromtimestamp(t).strftime("%m-%d %H:%M") print(f"[{'INSERT' if APPLY else 'DRY-RUN'}] 빈 구간 {len(gaps)}개:", ", ".join(f"{fmt(a)}~{fmt(b)}" for a, b in gaps) or "없음") print(" " + ", ".join(f"{k} {n}건" for k, n in inserted.items())) + print(f" 장기 통계 시간별 행 {fixed}개 수정, 대기 {len(pending)}시간") if __name__ == "__main__":