feat(pi2-greenhouse): 상태 표시 장치 추가 — 2.4" ILI9341 TFT 대시보드, 0.96" OLED
- tft.py: ILI9341 SPI 드라이버 + 320x240 대시보드(온도·습도·토양·릴레이 5칸·1시간 추세선), 바뀐 프레임만 전송 - oled.py: SSD1306/SH1106 I2C 상태 표시(smbus2+Pillow, 추가 설치 없음) - greenhouse.py: display 설정(목록)이 있을 때만 표시 스레드 시작. 표시 오류는 제어 루프에 영향 없음 - config.yaml: display 블록(TFT 기본, OLED 주석), 릴레이 짧은 이름(short) - oled_test.py / ili9341_test.py / display_demo.py: 배선 확인·시연용(MQTT·HA 전송 없음) Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
edd18a6374
commit
1a3aeaeca6
7 files changed
+678
No files matched your search
@@ -14,6 +14,20 @@ mqtt:
|
||||
interval_s: 10 # 측정·제어 주기 (DHT22 재시도 때문에 최대 ~13초 걸릴 수 있음)
|
||||
stale_s: 90 # 이 시간 넘게 센서 값이 안 오면 failsafe
|
||||
|
||||
# 표시 장치(목록). 지우면 표시 안 함. 둘 다 써도 되고 하나만 써도 된다.
|
||||
display:
|
||||
# 2.4" ILI9341 SPI TFT 320x240 — 배선(BCM): MOSI=10 SCK=11 CS=8 DC=25 RESET=5, VCC/LED=3.3V, GND
|
||||
- type: ili9341
|
||||
dc: 25
|
||||
reset: 5
|
||||
landscape: true
|
||||
interval_s: 2
|
||||
# 0.96" I2C OLED — 배선: VCC=핀1, GND=핀6, SDA=핀3, SCL=핀5 (사용하려면 주석 해제)
|
||||
# - type: ssd1306 # 가장자리가 밀리면 sh1106
|
||||
# address: 0x3c
|
||||
# flip: false
|
||||
# interval_s: 2
|
||||
|
||||
sensors:
|
||||
- id: air
|
||||
name: 온실 공기
|
||||
@@ -31,6 +45,7 @@ sensors:
|
||||
actuators:
|
||||
fan:
|
||||
name: 환풍기
|
||||
short: 환풍
|
||||
# gpio: 17 # 핀을 적으면 실제 릴레이, 없으면 가상(로그만)
|
||||
active_low: true # 대부분의 릴레이 모듈은 LOW=ON (SSR 모듈은 제품마다 달라 확인 필요)
|
||||
rule: {sensor: air.temperature, on_above: 28, off_below: 25}
|
||||
@@ -38,6 +53,7 @@ actuators:
|
||||
|
||||
sprinkler:
|
||||
name: 스프링클러
|
||||
short: 물
|
||||
# gpio: 27
|
||||
active_low: true
|
||||
rule: {sensor: soil.soil_moisture, on_below: 30, off_above: 45}
|
||||
@@ -49,6 +65,7 @@ actuators:
|
||||
# 난방 3단계(겨울 채소 기준: 얼지만 않게) — 기온이 내려갈수록 하나씩 더 켠다. 전부 센서 이상/과열(35°C) 시 강제 차단.
|
||||
lamp1:
|
||||
name: 축사등 1
|
||||
short: 등1
|
||||
# gpio: 22
|
||||
active_low: true
|
||||
rule: {sensor: air.temperature, on_below: 4, off_above: 7}
|
||||
@@ -58,6 +75,7 @@ actuators:
|
||||
cutoff: {sensor: air.temperature, above: 35}
|
||||
lamp2:
|
||||
name: 축사등 2
|
||||
short: 등2
|
||||
# gpio: 23
|
||||
active_low: true
|
||||
rule: {sensor: air.temperature, on_below: 2, off_above: 5}
|
||||
@@ -67,6 +85,7 @@ actuators:
|
||||
cutoff: {sensor: air.temperature, above: 35}
|
||||
heater:
|
||||
name: 대류 히터 500W
|
||||
short: 히터
|
||||
# gpio: 24
|
||||
active_low: true
|
||||
rule: {sensor: air.temperature, on_below: 0, off_above: 3}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""표시 장치(TFT/OLED) 시연. 서비스·MQTT 없이 모의 값만 화면에 띄운다(HA 전송 없음).
|
||||
|
||||
python3 display_demo.py [config.yaml] [초] # 기본 900초 후 종료
|
||||
"""
|
||||
import math
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
import greenhouse
|
||||
|
||||
cfg_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).with_name("config.yaml")
|
||||
duration = float(sys.argv[2]) if len(sys.argv) > 2 else 900
|
||||
gh = greenhouse.Greenhouse(yaml.safe_load(cfg_path.read_text())) # MQTT 루프를 시작하지 않는다
|
||||
for d in gh.displays:
|
||||
if hasattr(d, "hist"):
|
||||
d.hist.extend([20 + 4 * math.sin(i / 14) + i * 0.03 for i in range(90)])
|
||||
d._last_hist = time.time()
|
||||
d.start()
|
||||
t0 = time.time()
|
||||
try:
|
||||
while time.time() - t0 < duration:
|
||||
now = time.time(); k = now - t0
|
||||
gh.values["air.temperature"] = (round(24.3 + 1.5 * math.sin(k / 40), 1), now)
|
||||
gh.values["air.humidity"] = (round(61 + 6 * math.sin(k / 55)), now)
|
||||
gh.values["soil.soil_moisture"] = (round(42 + 8 * math.sin(k / 90)), now)
|
||||
gh.acts["fan"].relay.on = True
|
||||
gh.acts["lamp2"].relay.on = int(k // 20) % 2 == 0
|
||||
time.sleep(3)
|
||||
finally:
|
||||
for d in gh.displays:
|
||||
d.stop()
|
||||
d.join(3)
|
||||
@@ -148,6 +148,15 @@ class Greenhouse:
|
||||
self.cl.will_set(f"{self.node}/status", "offline", retain=True)
|
||||
self.cl.on_connect = self.on_connect; self.cl.on_message = self.on_message
|
||||
self.cl.connect_async(m["host"], m.get("port", 1883), 30)
|
||||
self.displays = [] # 선택 기능: 설정이 없으면 모듈도 안 불러온다
|
||||
dcfg = cfg.get("display") or []
|
||||
for d in ([dcfg] if isinstance(dcfg, dict) else dcfg):
|
||||
if d.get("type") == "ili9341":
|
||||
from tft import TftDisplay
|
||||
self.displays.append(TftDisplay(self, d))
|
||||
else:
|
||||
from oled import StatusDisplay
|
||||
self.displays.append(StatusDisplay(self, d))
|
||||
|
||||
# --- MQTT ---
|
||||
def on_connect(self, cl, ud, flags, rc, props=None):
|
||||
@@ -248,6 +257,8 @@ class Greenhouse:
|
||||
|
||||
def run(self):
|
||||
self.cl.loop_start()
|
||||
for d in self.displays:
|
||||
d.start()
|
||||
iv = self.cfg.get("interval_s", 10)
|
||||
while not self.stop.is_set():
|
||||
self.read_sensors(); self.step()
|
||||
@@ -255,6 +266,8 @@ class Greenhouse:
|
||||
self.shutdown()
|
||||
|
||||
def shutdown(self):
|
||||
for d in self.displays:
|
||||
d.stop()
|
||||
for a in self.acts.values():
|
||||
a.relay.close()
|
||||
self.cl.publish(f"{self.node}/status", "offline", retain=True).wait_for_publish(2)
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""2.4" ILI9341 SPI TFT(240x320) 배선 테스트. spidev + gpiozero + Pillow만 사용.
|
||||
|
||||
배선(BCM): MOSI=10 SCK=11 CS=8(CE0) DC=25 RESET=5, VCC/LED=3.3V, GND
|
||||
python3 ili9341_test.py # 단색 R,G,B,흰,검 → 텍스트 화면
|
||||
python3 ili9341_test.py --rot 0 # 세로(240x320). 기본은 가로(320x240)
|
||||
python3 ili9341_test.py --bgr # 빨강/파랑이 바뀌어 보이면
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
import spidev
|
||||
from gpiozero import OutputDevice
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
DC, RST = 25, 5
|
||||
|
||||
|
||||
class ILI9341:
|
||||
def __init__(self, rot=1, bgr=False, speed=16_000_000):
|
||||
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.rot = rot
|
||||
self.w, self.h = (320, 240) if rot else (240, 320)
|
||||
self.madctl = (0x28 if rot else 0x48) ^ (0x08 if bgr else 0) # 기본 BGR 비트 켬
|
||||
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 _window(self):
|
||||
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)
|
||||
|
||||
def _write(self, buf):
|
||||
self.dc.on()
|
||||
for i in range(0, len(buf), 4096):
|
||||
self.spi.xfer2(buf[i:i + 4096])
|
||||
|
||||
def fill(self, rgb):
|
||||
r, g, b = rgb
|
||||
v = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
|
||||
self._window()
|
||||
self._write([v >> 8, v & 0xFF] * (self.w * self.h))
|
||||
|
||||
def show(self, im):
|
||||
d = im.convert("RGB").resize((self.w, self.h)).tobytes()
|
||||
buf = bytearray(self.w * self.h * 2)
|
||||
r, g, b = d[0::3], d[1::3], d[2::3]
|
||||
for i in range(self.w * self.h):
|
||||
v = ((r[i] & 0xF8) << 8) | ((g[i] & 0xFC) << 3) | (b[i] >> 3)
|
||||
buf[2 * i] = v >> 8
|
||||
buf[2 * i + 1] = v & 0xFF
|
||||
self._window()
|
||||
self._write(list(buf))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--rot", type=int, default=1)
|
||||
ap.add_argument("--bgr", action="store_true")
|
||||
ap.add_argument("--speed", type=int, default=16_000_000)
|
||||
a = ap.parse_args()
|
||||
d = ILI9341(a.rot, a.bgr, a.speed)
|
||||
for name, c in [("RED", (255, 0, 0)), ("GREEN", (0, 255, 0)), ("BLUE", (0, 0, 255)),
|
||||
("WHITE", (255, 255, 255)), ("BLACK", (0, 0, 0))]:
|
||||
print(name, flush=True)
|
||||
d.fill(c)
|
||||
time.sleep(0.8)
|
||||
f = ImageFont.truetype("/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", 28)
|
||||
big = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 56)
|
||||
im = Image.new("RGB", (d.w, d.h), (0, 0, 0))
|
||||
g = ImageDraw.Draw(im)
|
||||
g.rectangle((0, 0, d.w - 1, d.h - 1), outline=(255, 255, 255), width=2)
|
||||
g.text((12, 10), "온실 Pi2 TFT 테스트", font=f, fill=(255, 255, 0))
|
||||
g.text((12, 70), "24.3°C", font=big, fill=(80, 220, 255))
|
||||
g.text((12, 150), "습도 61% 토양 42%", font=f, fill=(120, 255, 120))
|
||||
for i, c in enumerate([(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 255)]):
|
||||
g.rectangle((12 + i * 60, 195, 62 + i * 60, 225), fill=c)
|
||||
d.show(im)
|
||||
print("done")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,161 @@
|
||||
"""0.96" I2C OLED(SSD1306/SH1106 128x64) 상태 표시. smbus2+Pillow만 사용.
|
||||
|
||||
Oled : 저수준 드라이버(프레임 → 패널)
|
||||
render : 온실 상태를 128x64 이미지로 그린다
|
||||
StatusDisplay : 별도 스레드. 표시 오류가 제어 루프에 절대 영향을 주지 않도록 모든 예외를 삼키고 재시도한다.
|
||||
"""
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
log = logging.getLogger("greenhouse.oled")
|
||||
W, H = 128, 64
|
||||
|
||||
_FONT_DIRS = ["/usr/share/fonts/truetype/nanum/", "/usr/share/fonts/truetype/dejavu/"]
|
||||
|
||||
|
||||
def _font(names, size):
|
||||
for d in _FONT_DIRS:
|
||||
for n in names:
|
||||
try:
|
||||
return ImageFont.truetype(d + n, size)
|
||||
except OSError:
|
||||
pass
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
class Oled:
|
||||
def __init__(self, bus=1, addr=0x3C, sh1106=False, flip=False, contrast=0xCF):
|
||||
from smbus2 import SMBus
|
||||
self.b = SMBus(bus)
|
||||
self.addr = addr
|
||||
self.sh1106 = sh1106
|
||||
self.cmd(0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40,
|
||||
0x8D, 0x14, 0x20, 0x00,
|
||||
0xA0 if flip else 0xA1, 0xC0 if flip else 0xC8,
|
||||
0xDA, 0x12, 0x81, contrast & 0xFF, 0xD9, 0xF1, 0xDB, 0x40,
|
||||
0xA4, 0xA6, 0xAF)
|
||||
|
||||
def cmd(self, *c):
|
||||
for x in c:
|
||||
self.b.write_byte_data(self.addr, 0x00, x)
|
||||
|
||||
def show(self, img):
|
||||
px = img.convert("1").load()
|
||||
off = 2 if self.sh1106 else 0
|
||||
for page in range(H // 8):
|
||||
data = [sum(1 << bit for bit in range(8) if px[x, page * 8 + bit]) for x in range(W)]
|
||||
if self.sh1106:
|
||||
self.cmd(0xB0 + page, off & 0x0F, 0x10 + (off >> 4))
|
||||
else:
|
||||
self.cmd(0x21, 0, W - 1, 0x22, page, page)
|
||||
for i in range(0, W, 32):
|
||||
self.b.write_i2c_block_data(self.addr, 0x40, data[i:i + 32])
|
||||
|
||||
def off(self):
|
||||
self.cmd(0xAE)
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.b.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ───────────────────────── 화면 구성 ─────────────────────────
|
||||
_F_SMALL = _F_BIG = _F_MID = _F_TINY = None
|
||||
|
||||
|
||||
def render(gh):
|
||||
"""gh(Greenhouse)의 현재 값으로 한 화면을 그린다."""
|
||||
global _F_SMALL, _F_BIG, _F_MID, _F_TINY
|
||||
if _F_SMALL is None:
|
||||
_F_SMALL = _font(["NanumGothicBold.ttf", "DejaVuSans-Bold.ttf"], 11)
|
||||
_F_TINY = _font(["NanumGothicBold.ttf", "DejaVuSans-Bold.ttf"], 10)
|
||||
_F_MID = _font(["DejaVuSans-Bold.ttf"], 18)
|
||||
_F_BIG = _font(["DejaVuSans-Bold.ttf"], 24)
|
||||
now = time.time()
|
||||
im = Image.new("1", (W, H), 0)
|
||||
g = ImageDraw.Draw(im)
|
||||
|
||||
def val(ref, fmt):
|
||||
v = gh.get(ref, now)
|
||||
return "--" if v is None else fmt % v
|
||||
|
||||
# 헤더: 이름 · (모의 센서면 SIM) · MQTT 점 · 시각
|
||||
g.text((0, 0), "온실", font=_F_SMALL, fill=1)
|
||||
if any(type(d).__name__ == "SimSensor" for _, d, _ in gh.sensors):
|
||||
g.text((34, 0), "SIM", font=_F_SMALL, fill=1)
|
||||
g.text((W - 34, 0), time.strftime("%H:%M"), font=_F_SMALL, fill=1)
|
||||
ok = gh.cl.is_connected()
|
||||
r = (W - 42, 5, W - 38, 9)
|
||||
g.ellipse(r, fill=1) if ok else g.ellipse(r, outline=1)
|
||||
|
||||
# 온도(크게) · 습도
|
||||
g.text((0, 10), val("air.temperature", "%.1f"), font=_F_BIG, fill=1)
|
||||
tw = g.textlength(val("air.temperature", "%.1f"), font=_F_BIG)
|
||||
g.text((tw + 2, 12), "°C", font=_F_SMALL, fill=1)
|
||||
g.text((84, 12), "습도", font=_F_SMALL, fill=1)
|
||||
g.text((84, 24), val("air.humidity", "%.0f") + "%", font=_F_MID, fill=1)
|
||||
|
||||
# 토양
|
||||
g.text((0, 38), "토양 " + val("soil.soil_moisture", "%.0f") + "%", font=_F_SMALL, fill=1)
|
||||
|
||||
# 릴레이 상태 막대: 켜지면 채움(반전)
|
||||
names = list(gh.acts.items())
|
||||
if names:
|
||||
bw = W // len(names)
|
||||
for i, (n, a) in enumerate(names):
|
||||
x0 = i * bw
|
||||
label = (a.cfg.get("short") or a.cfg.get("name", n))[:2]
|
||||
box = (x0, 52, x0 + bw - 2, 63)
|
||||
if a.relay.on:
|
||||
g.rectangle(box, fill=1)
|
||||
g.text((x0 + 3, 52), label, font=_F_TINY, fill=0)
|
||||
else:
|
||||
g.rectangle(box, outline=1)
|
||||
g.text((x0 + 3, 52), label, font=_F_TINY, fill=1)
|
||||
return im
|
||||
|
||||
|
||||
class StatusDisplay(threading.Thread):
|
||||
def __init__(self, gh, cfg):
|
||||
super().__init__(daemon=True, name="oled")
|
||||
self.gh = gh
|
||||
self.cfg = cfg
|
||||
self.dev = None
|
||||
self.stop_evt = threading.Event()
|
||||
|
||||
def _open(self):
|
||||
c = self.cfg
|
||||
self.dev = Oled(c.get("bus", 1), c.get("address", 0x3C), c.get("type", "ssd1306") == "sh1106",
|
||||
c.get("flip", False), c.get("contrast", 0xCF))
|
||||
|
||||
def run(self):
|
||||
iv = self.cfg.get("interval_s", 2)
|
||||
fails = 0
|
||||
while not self.stop_evt.is_set():
|
||||
try:
|
||||
if self.dev is None:
|
||||
self._open()
|
||||
self.dev.show(render(self.gh))
|
||||
fails = 0
|
||||
except Exception as e: # 표시 장애는 제어에 영향 없음
|
||||
fails += 1
|
||||
if fails in (1, 10, 100):
|
||||
log.warning("OLED 표시 실패(%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.off()
|
||||
self.dev.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def stop(self):
|
||||
self.stop_evt.set()
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
"""0.96" I2C OLED(SSD1306/SH1106 128x64) 배선 테스트. smbus2+Pillow만 사용(추가 설치 없음).
|
||||
|
||||
python3 oled_test.py # 0x3C, SSD1306
|
||||
python3 oled_test.py --addr 0x3d # 주소가 3D인 모듈
|
||||
python3 oled_test.py --sh1106 # 가장자리 2px 밀리거나 쓰레기 줄이 보일 때
|
||||
python3 oled_test.py --flip # 180도 회전(케이스에서 거꾸로 달렸을 때)
|
||||
"""
|
||||
import argparse
|
||||
import socket
|
||||
import time
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from smbus2 import SMBus
|
||||
|
||||
W, H = 128, 64
|
||||
|
||||
|
||||
class Oled:
|
||||
def __init__(self, bus=1, addr=0x3C, sh1106=False, flip=False):
|
||||
self.b = SMBus(bus)
|
||||
self.addr = addr
|
||||
self.sh1106 = sh1106
|
||||
self.col_off = 2 if sh1106 else 0
|
||||
self.cmd(0xAE, 0xD5, 0x80, 0xA8, 0x3F, 0xD3, 0x00, 0x40,
|
||||
0x8D, 0x14, # 차지펌프 ON (3.3V 구동)
|
||||
0x20, 0x00, # 수평 주소 지정
|
||||
0xA0 if flip else 0xA1, # 세그먼트 리맵
|
||||
0xC0 if flip else 0xC8, # COM 스캔 방향
|
||||
0xDA, 0x12, 0x81, 0xCF, 0xD9, 0xF1, 0xDB, 0x40,
|
||||
0xA4, 0xA6, 0xAF)
|
||||
|
||||
def cmd(self, *c):
|
||||
for x in c:
|
||||
self.b.write_byte_data(self.addr, 0x00, x)
|
||||
|
||||
def show(self, img):
|
||||
img = img.convert("1")
|
||||
px = img.load()
|
||||
for page in range(H // 8):
|
||||
data = []
|
||||
for x in range(W):
|
||||
v = 0
|
||||
for bit in range(8):
|
||||
if px[x, page * 8 + bit]:
|
||||
v |= 1 << bit
|
||||
data.append(v)
|
||||
if self.sh1106: # SH1106은 페이지 주소 지정 방식 + 컬럼 오프셋 2
|
||||
self.cmd(0xB0 + page, 0x00 + (self.col_off & 0x0F), 0x10 + (self.col_off >> 4))
|
||||
else:
|
||||
self.cmd(0x21, 0, W - 1, 0x22, page, page)
|
||||
for i in range(0, W, 32):
|
||||
self.b.write_i2c_block_data(self.addr, 0x40, data[i:i + 32])
|
||||
|
||||
def off(self):
|
||||
self.cmd(0xAE)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--addr", default="0x3c")
|
||||
ap.add_argument("--bus", type=int, default=1)
|
||||
ap.add_argument("--sh1106", action="store_true")
|
||||
ap.add_argument("--flip", action="store_true")
|
||||
a = ap.parse_args()
|
||||
|
||||
d = Oled(a.bus, int(a.addr, 16), a.sh1106, a.flip)
|
||||
f = ImageFont.load_default()
|
||||
try:
|
||||
# 1) 전체 흰색 → 불량 픽셀/배선 확인
|
||||
d.show(Image.new("1", (W, H), 1))
|
||||
time.sleep(1.0)
|
||||
# 2) 테두리 + 텍스트: 가장자리가 잘리거나 밀리면 --sh1106 / 방향이 거꾸로면 --flip
|
||||
for n in range(1, 11):
|
||||
im = Image.new("1", (W, H), 0)
|
||||
g = ImageDraw.Draw(im)
|
||||
g.rectangle((0, 0, W - 1, H - 1), outline=1)
|
||||
g.text((6, 5), "Greenhouse Pi2", font=f, fill=1)
|
||||
g.text((6, 20), "OLED test OK", font=f, fill=1)
|
||||
g.text((6, 35), socket.gethostname() + " " + time.strftime("%H:%M:%S"), font=f, fill=1)
|
||||
g.rectangle((6, 50, 6 + n * 11, 56), fill=1)
|
||||
d.show(im)
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
pass # 마지막 화면을 그대로 둔다 (꺼려면 d.off())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,251 @@
|
||||
"""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")
|
||||
|
||||
# 헤더
|
||||
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))
|
||||
_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()
|
||||
Reference in new issue
Block a user