Files
kimandClaude Sonnet 5.5 1c9f266114 feat(pi2-greenhouse): AHT20 온습도 + BMP280 기압 센서 추가, 화면에 기압 표시
- DHT22를 AHT20(I2C 0x38)으로 교체. DHT22 읽기 재시도(~13초)가 종료 제한 10초를
  넘겨 SIGKILL로 끝나던 문제도 함께 해소
- BMP280/BME280(0x77) 드라이버 추가(smbus2, 데이터시트 보정식), 기압 hPa를 HA에 디스커버리
- TFT 헤더·OLED 토양 줄에 기압 표시
- config.yaml을 실제 배포 상태(센서 연결)로 갱신

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 20:03:29 +09:00

255 lines
10 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""2.4" ILI9341 SPI TFT(320x240 가로) 온실 대시보드. spidev + gpiozero + Pillow + numpy.
배선(BCM): MOSI=10 SCK=11 CS=8(CE0) DC=25 RESET=5, VCC/LED=3.3V, GND
ILI9341 : 저수준 드라이버
render : 온실 상태를 320x240 이미지로 그린다
TftDisplay: 별도 스레드. 표시 오류는 전부 삼키고 재시도 — 제어 루프에 영향 없음.
"""
import logging
import threading
import time
from collections import deque
import numpy as np
from PIL import Image, ImageDraw, ImageFont
log = logging.getLogger("greenhouse.tft")
W, H = 320, 240
class ILI9341:
def __init__(self, dc=25, rst=5, rot=1, bgr=False, speed=16_000_000):
import spidev
from gpiozero import OutputDevice
self.dc = OutputDevice(dc)
self.rst = OutputDevice(rst, initial_value=True)
self.spi = spidev.SpiDev()
self.spi.open(0, 0)
self.spi.max_speed_hz = speed
self.spi.mode = 0
self.w, self.h = (320, 240) if rot else (240, 320)
self.madctl = (0x28 if rot else 0x48) ^ (0x08 if bgr else 0)
self._init()
def _cmd(self, c, data=()):
self.dc.off()
self.spi.xfer2([c])
if data:
self.dc.on()
self.spi.xfer2(list(data))
def _init(self):
self.rst.on(); time.sleep(0.05); self.rst.off(); time.sleep(0.05); self.rst.on(); time.sleep(0.15)
self._cmd(0x01); time.sleep(0.15)
for c, d in [(0xCF, (0x00, 0xC1, 0x30)), (0xED, (0x64, 0x03, 0x12, 0x81)), (0xE8, (0x85, 0x00, 0x78)),
(0xCB, (0x39, 0x2C, 0x00, 0x34, 0x02)), (0xF7, (0x20,)), (0xEA, (0x00, 0x00)),
(0xC0, (0x23,)), (0xC1, (0x10,)), (0xC5, (0x3E, 0x28)), (0xC7, (0x86,)),
(0x36, (self.madctl,)), (0x3A, (0x55,)), (0xB1, (0x00, 0x18)), (0xB6, (0x08, 0x82, 0x27)),
(0xF2, (0x00,)), (0x26, (0x01,)),
(0xE0, (0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, 0x4E, 0xF1, 0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00)),
(0xE1, (0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, 0x31, 0xC1, 0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F))]:
self._cmd(c, d)
self._cmd(0x11); time.sleep(0.12)
self._cmd(0x29); time.sleep(0.05)
def show(self, im):
a = np.asarray(im.convert("RGB").resize((self.w, self.h)), dtype=np.uint16)
v = ((a[..., 0] & 0xF8) << 8) | ((a[..., 1] & 0xFC) << 3) | (a[..., 2] >> 3)
buf = np.empty(v.shape + (2,), dtype=np.uint8)
buf[..., 0] = v >> 8
buf[..., 1] = v & 0xFF
data = buf.tobytes()
w, h = self.w, self.h
self._cmd(0x2A, (0, 0, (w - 1) >> 8, (w - 1) & 0xFF))
self._cmd(0x2B, (0, 0, (h - 1) >> 8, (h - 1) & 0xFF))
self._cmd(0x2C)
self.dc.on()
for i in range(0, len(data), 4096):
self.spi.writebytes2(data[i:i + 4096])
def fill(self, rgb):
self.show(Image.new("RGB", (self.w, self.h), rgb))
def off(self):
self._cmd(0x28) # 표시 끔(백라이트는 3.3V 직결이라 켜져 있음)
def close(self):
for o in (self.spi, self.dc, self.rst):
try:
o.close()
except Exception:
pass
# ───────────────────────── 화면 ─────────────────────────
BG, CARD, TRACK = (11, 15, 24), (23, 31, 46), (40, 50, 70)
TXT, MUTED = (240, 244, 250), (135, 148, 170)
ACCENT = {"fan": (80, 210, 255), "sprinkler": (90, 150, 255), "lamp1": (255, 190, 60),
"lamp2": (255, 190, 60), "heater": (255, 100, 80)}
_NANUM = ["/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]
_DEJAVU = ["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]
_fonts = {}
def font(kind, size):
k = (kind, size)
if k not in _fonts:
for p in (_NANUM if kind == "ko" else _DEJAVU):
try:
_fonts[k] = ImageFont.truetype(p, size)
break
except OSError:
pass
else:
_fonts[k] = ImageFont.load_default()
return _fonts[k]
def temp_color(t):
if t is None: return MUTED
if t <= 0: return (110, 150, 255)
if t < 10: return (90, 210, 255)
if t <= 27: return (110, 230, 140)
if t <= 33: return (255, 190, 60)
return (255, 90, 80)
def soil_color(s):
if s is None: return MUTED
if s < 30: return (255, 170, 60)
if s <= 60: return (110, 230, 140)
return (90, 160, 255)
def _right(g, x, y, text, f, fill):
g.text((x - g.textlength(text, font=f), y), text, font=f, fill=fill)
def render(gh, hist):
now = time.time()
im = Image.new("RGB", (W, H), BG)
g = ImageDraw.Draw(im)
def v(ref):
return gh.get(ref, now)
t, hu, so = v("air.temperature"), v("air.humidity"), v("soil.soil_moisture")
pr = v("baro.pressure")
# 헤더
g.text((12, 6), "온실", font=font("ko", 18), fill=TXT)
x = 12 + 40
if any(type(d).__name__ == "SimSensor" for _, d, _ in gh.sensors):
g.rounded_rectangle((x, 8, x + 38, 26), radius=6, fill=(90, 70, 20))
g.text((x + 6, 9), "SIM", font=font("en", 12), fill=(255, 200, 80))
if any(sid == "baro" for sid, _, _ in gh.sensors):
g.text((112, 10), "--" if pr is None else "%.0f hPa" % pr, font=font("en", 15), fill=MUTED)
_right(g, W - 12, 5, time.strftime("%H:%M"), font("en", 20), TXT)
ok = gh.cl.is_connected()
g.ellipse((W - 92, 11, W - 82, 21), fill=(110, 230, 140) if ok else None, outline=(110, 230, 140) if ok else (255, 90, 80), width=2)
# 온도 카드
g.rounded_rectangle((8, 34, 158, 134), radius=12, fill=CARD)
g.text((20, 40), "온도", font=font("ko", 13), fill=MUTED)
tc = temp_color(t)
ts = "--" if t is None else "%.1f" % t
fn = font("en", 44)
g.text((18, 56), ts, font=fn, fill=tc)
g.text((18 + g.textlength(ts, font=fn) + 4, 62), "°C", font=font("en", 18), fill=MUTED)
pts = [p for p in hist if p is not None]
if len(pts) >= 3: # 스파크라인(최근 약 1시간)
lo, hi = min(pts), max(pts)
span = max(hi - lo, 1.0)
x0, x1, y0, y1 = 20, 146, 108, 128
xy = [(x0 + (x1 - x0) * i / (len(pts) - 1), y1 - (y1 - y0) * (p - lo) / span) for i, p in enumerate(pts)]
g.line(xy, fill=tc, width=2)
g.ellipse((xy[-1][0] - 3, xy[-1][1] - 3, xy[-1][0] + 3, xy[-1][1] + 3), fill=tc)
# 습도 카드
g.rounded_rectangle((162, 34, 312, 134), radius=12, fill=CARD)
g.text((174, 40), "습도", font=font("ko", 13), fill=MUTED)
hs = "--" if hu is None else "%.0f" % hu
g.text((172, 56), hs, font=fn, fill=(90, 190, 255))
g.text((172 + g.textlength(hs, font=fn) + 4, 62), "%", font=font("en", 18), fill=MUTED)
g.rounded_rectangle((174, 112, 300, 122), radius=5, fill=TRACK)
if hu is not None and hu > 0:
g.rounded_rectangle((174, 112, 174 + max(10, int(126 * min(hu, 100) / 100)), 122), radius=5, fill=(90, 190, 255))
# 토양 카드
g.rounded_rectangle((8, 140, 312, 182), radius=12, fill=CARD)
g.text((20, 151), "토양 수분", font=font("ko", 14), fill=MUTED)
sc = soil_color(so)
g.rounded_rectangle((110, 154, 250, 168), radius=7, fill=TRACK)
if so is not None and so > 0:
g.rounded_rectangle((110, 154, 110 + max(14, int(140 * min(so, 100) / 100)), 168), radius=7, fill=sc)
_right(g, 300, 146, "--" if so is None else "%.0f%%" % so, font("en", 22), sc if so is not None else MUTED)
# 릴레이 5칸
acts = list(gh.acts.items())
if acts:
n = len(acts)
gap = 6
bw = (304 - gap * (n - 1)) // n
for i, (name, a) in enumerate(acts):
x0 = 8 + i * (bw + gap)
on = a.relay.on
col = ACCENT.get(name, (110, 230, 140))
g.rounded_rectangle((x0, 190, x0 + bw, 232), radius=10, fill=col if on else CARD)
label = (a.cfg.get("short") or a.cfg.get("name", name))[:3]
f = font("ko", 14)
fg = (12, 16, 24) if on else MUTED
g.text((x0 + (bw - g.textlength(label, font=f)) / 2, 197), label, font=f, fill=fg)
st = "ON" if on else "OFF"
f2 = font("en", 11)
g.text((x0 + (bw - g.textlength(st, font=f2)) / 2, 216), st, font=f2, fill=fg)
return im
class TftDisplay(threading.Thread):
def __init__(self, gh, cfg):
super().__init__(daemon=True, name="tft")
self.gh, self.cfg = gh, cfg
self.dev = None
self.hist = deque(maxlen=120) # 30초 간격 × 120 = 1시간
self._last_hist = 0.0
self._last_frame = None
self.stop_evt = threading.Event()
def run(self):
iv = self.cfg.get("interval_s", 2)
c = self.cfg
fails = 0
while not self.stop_evt.is_set():
try:
now = time.time()
if now - self._last_hist >= c.get("trend_interval_s", 30):
self._last_hist = now
self.hist.append(self.gh.get("air.temperature", now))
if self.dev is None:
self.dev = ILI9341(c.get("dc", 25), c.get("reset", 5), 1 if c.get("landscape", True) else 0,
c.get("bgr", False), c.get("speed_hz", 16_000_000))
self._last_frame = None
im = render(self.gh, list(self.hist))
raw = im.tobytes()
if raw != self._last_frame: # 바뀐 프레임만 전송
self.dev.show(im)
self._last_frame = raw
fails = 0
except Exception as e: # 표시 장애는 제어에 영향 없음
fails += 1
if fails in (1, 10, 100):
log.warning("TFT 표시 실패(%d회): %s", fails, e)
if self.dev:
self.dev.close()
self.dev = None
self.stop_evt.wait(iv if fails == 0 else min(30, iv * (1 + fails)))
try:
if self.dev:
self.dev.fill((0, 0, 0))
self.dev.close()
except Exception:
pass
def stop(self):
self.stop_evt.set()