온실 백필: HA가 잠든 시간에 '직전 값 그대로'로 만든 장기 통계(시간별 평균·최저·최고)도 파이 CSV 값으로 덮어씀(대기 목록, 행이 생긴 뒤에만 수정)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Opus 5.5 committed 2026-10-22 10:41:28 +09:00
1 parent 8ae79c884b
commit 8ed1a23931
1 file changed
+38 -2
+38 -2
View File
@@ -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__":