Files

514 lines
25 KiB
Python

#!/usr/bin/env python3
"""온실 제어기 (Raspberry Pi 2) — 센서를 읽고, 규칙대로 릴레이를 직접 제어하고, MQTT로 HA에 보고한다.
- 자동 제어는 파이가 직접 한다(네트워크/HA/브로커가 죽어도 온실은 계속 돈다).
- HA에는 MQTT Discovery로 센서·스위치·모드 선택이 자동 등록된다.
- 안전장치: 스프링클러 최대 가동시간·최소 간격, 센서 값이 끊기면(stale) 자동 제어는 failsafe 상태로,
프로그램 종료/크래시 시 모든 릴레이 OFF.
설정은 config.yaml. 센서/릴레이 드라이버는 DRIVERS / RelayPin 참고.
"""
import csv
import json
import math
import logging
import random
import signal
import sys
import threading
import time
from pathlib import Path
import paho.mqtt.client as mqtt
import yaml
log = logging.getLogger("greenhouse")
# ───────────────────────── 센서 드라이버 ─────────────────────────
# 드라이버는 read() -> {측정키: 값} 을 돌려준다. 실패하면 예외(그 센서는 stale 처리).
class SimSensor:
"""하드웨어 없이 시험용. 온도·습도·토양수분이 천천히 흔들린다."""
def __init__(self, cfg):
self.t = 24.0; self.h = 60.0; self.s = 40.0
def read(self):
self.t += random.uniform(-0.4, 0.4); self.h += random.uniform(-1, 1); self.s += random.uniform(-1.2, 0.6)
self.t = min(max(self.t, 5), 40); self.h = min(max(self.h, 20), 95); self.s = min(max(self.s, 5), 90)
return {"temperature": round(self.t, 1), "humidity": round(self.h, 1), "soil_moisture": round(self.s, 1)}
class DS18B20:
"""1-Wire 온도센서. config.txt에 dtoverlay=w1-gpio 필요. 커널 sysfs만 읽는다(라이브러리 불필요)."""
def __init__(self, cfg):
self.path = Path("/sys/bus/w1/devices") / cfg["address"] / "w1_slave"
def read(self):
lines = self.path.read_text().splitlines()
if not lines[0].endswith("YES"):
raise IOError("CRC 오류")
return {"temperature": round(int(lines[1].split("t=")[1]) / 1000, 1)}
class DHT22:
"""DHT22(AM2302) 온습도. adafruit-circuitpython-dht 사용(venv). 타이밍이 빡빡해 가끔 실패하므로
몇 번 재시도하고, 그래도 안 되면 예외(그 주기는 건너뛰고 직전 값 유지, 오래되면 stale)."""
def __init__(self, cfg):
import adafruit_dht, board
self.dev = adafruit_dht.DHT22(getattr(board, f"D{cfg['gpio']}"), use_pulseio=False)
def read(self):
last = None
for _ in range(6):
try:
t, h = self.dev.temperature, self.dev.humidity
if t is not None and h is not None and -40 <= t <= 80 and 0 <= h <= 100:
return {"temperature": round(t, 1), "humidity": round(h, 1)}
except RuntimeError as e: # 체크섬/타이밍 오류는 DHT에선 정상적인 일
last = e
time.sleep(2.2) # DHT22는 2초 이상 간격 필요
raise IOError(f"DHT22 읽기 실패: {last}")
class AHT20:
"""AHT20 I2C 온습도(주소 0x38). smbus2로 직접 읽는다(라이브러리 불필요). 3.3V 구동, SDA=GPIO2 SCL=GPIO3."""
def __init__(self, cfg):
self.bus = cfg.get("bus", 1); self.addr = cfg.get("address", 0x38)
@staticmethod
def _crc(data):
c = 0xFF
for b in data:
c ^= b
for _ in range(8):
c = ((c << 1) ^ 0x31) & 0xFF if c & 0x80 else (c << 1) & 0xFF
return c
def read(self):
from smbus2 import SMBus, i2c_msg
with SMBus(self.bus) as b:
if not b.read_byte_data(self.addr, 0x71) & 0x08: # 보정 안 됨 → 초기화
b.write_i2c_block_data(self.addr, 0xBE, [0x08, 0x00]); time.sleep(0.01)
b.write_i2c_block_data(self.addr, 0xAC, [0x33, 0x00]) # 측정 시작
time.sleep(0.1)
for _ in range(5):
m = i2c_msg.read(self.addr, 7); b.i2c_rdwr(m); d = list(m)
if not d[0] & 0x80:
break
time.sleep(0.02)
else:
raise IOError("AHT20 측정 중 상태 지속")
if self._crc(d[:6]) != d[6]:
raise IOError("AHT20 CRC 오류")
h = ((d[1] << 12) | (d[2] << 4) | (d[3] >> 4)) / 1048576 * 100
t = (((d[3] & 0x0F) << 16) | (d[4] << 8) | d[5]) / 1048576 * 200 - 50
if not (-40 <= t <= 85 and 0 <= h <= 100):
raise IOError(f"AHT20 범위 밖 값 t={t:.1f} h={h:.1f}")
return {"temperature": round(t, 1), "humidity": round(h, 1)}
class SHT20:
"""SHT20/SHT21/HTU21D 계열 I2C 온습도(주소 0x40). no-hold 명령 + CRC8(0x131). smbus2 직접 읽기."""
def __init__(self, cfg):
self.bus = cfg.get("bus", 1); self.addr = cfg.get("address", 0x40)
@staticmethod
def _crc(data):
c = 0
for b in data:
c ^= b
for _ in range(8):
c = ((c << 1) ^ 0x131) & 0xFF if c & 0x80 else (c << 1) & 0xFF
return c
def _meas(self, b, cmd):
from smbus2 import i2c_msg
b.write_byte(self.addr, cmd)
time.sleep(0.1) # 14bit 온도 최대 85ms, 12bit 습도 29ms
m = i2c_msg.read(self.addr, 3); b.i2c_rdwr(m); d = list(m)
if self._crc(d[:2]) != d[2]:
raise IOError("SHT20 CRC 오류")
return ((d[0] << 8) | d[1]) & 0xFFFC # 하위 2비트는 상태
def read(self):
from smbus2 import SMBus
with SMBus(self.bus) as b:
t = -46.85 + 175.72 * self._meas(b, 0xF3) / 65536
h = -6 + 125 * self._meas(b, 0xF5) / 65536
h = min(max(h, 0.0), 100.0) # 데이터시트: 보정값이 범위를 살짝 넘을 수 있음
if not -40 <= t <= 125:
raise IOError(f"SHT20 범위 밖 값 t={t:.1f}")
return {"temperature": round(t, 1), "humidity": round(h, 1)}
class AvgSensor:
"""여러 센서의 평균. of: [{type: aht20, ...}, {type: sht20, ...}]
일부가 실패하면 되는 센서만으로 평균을 내고(경고 로그), 전부 실패해야 예외.
센서끼리 크게 어긋나면(온도 3°C·습도 10%RH 초과) 고장/결로 의심으로 경고한다."""
TOL = {"temperature": 3.0, "humidity": 10.0}
def __init__(self, cfg):
self.parts = [(c["type"], DRIVERS[c["type"]](c)) for c in cfg["of"]]
self.warned = set()
def read(self):
vals, failed = [], []
for name, drv in self.parts:
try:
r = drv.read()
vals.append((name, r))
except Exception as e:
failed.append(name)
if name not in self.warned: # 매 주기 반복해서 로그를 채우지 않게 상태 변화만 남긴다
self.warned.add(name)
log.warning("평균 센서 %s 읽기 실패(이후 복구될 때까지 생략): %s", name, e)
continue
if name in self.warned:
self.warned.discard(name)
log.info("평균 센서 %s 복구", name)
if not vals:
raise IOError("평균 센서 전부 읽기 실패: " + ", ".join(failed))
out = {}
for k, tol in self.TOL.items():
xs = [(n, v[k]) for n, v in vals if k in v]
if not xs:
continue
out[k] = round(sum(x for _, x in xs) / len(xs), 1)
if len(xs) > 1 and max(x for _, x in xs) - min(x for _, x in xs) > tol:
log.warning("센서 %s 불일치: %s", k, ", ".join(f"{n}={x}" for n, x in xs))
return out
class BMP280:
"""BMP280/BME280 기압(주소 0x77 또는 0x76). smbus2 직접 읽기, 데이터시트 보정식.
pressure(hPa)와 temperature(칩 온도 — 기판 자체 발열이 섞이니 기압만 쓰는 걸 권장)를 낸다.
BME280이면 습도 칩이므로 chip id 0x60을 허용하되 기압만 읽는다."""
def __init__(self, cfg):
self.bus = cfg.get("bus", 1); self.addr = cfg.get("address", 0x77)
self.cal = None
def _load(self, b):
cid = b.read_byte_data(self.addr, 0xD0)
if cid not in (0x56, 0x57, 0x58, 0x60):
raise IOError(f"BMP280 chip id 0x{cid:02x} 아님")
import struct
c = bytes(b.read_i2c_block_data(self.addr, 0x88, 24))
self.cal = struct.unpack("<HhhHhhhhhhhh", c)
def read(self):
from smbus2 import SMBus
with SMBus(self.bus) as b:
if self.cal is None:
self._load(b)
b.write_byte_data(self.addr, 0xF4, 0x55) # 온도 x2, 기압 x16, forced 1회 측정
time.sleep(0.06)
for _ in range(10):
if not b.read_byte_data(self.addr, 0xF3) & 0x08: # measuring 비트
break
time.sleep(0.01)
d = b.read_i2c_block_data(self.addr, 0xF7, 6)
adc_p = (d[0] << 12) | (d[1] << 4) | (d[2] >> 4)
adc_t = (d[3] << 12) | (d[4] << 4) | (d[5] >> 4)
T1, T2, T3, P1, P2, P3, P4, P5, P6, P7, P8, P9 = self.cal
v1 = (adc_t / 16384.0 - T1 / 1024.0) * T2
v2 = ((adc_t / 131072.0 - T1 / 8192.0) ** 2) * T3
tfine = v1 + v2
v1 = tfine / 2.0 - 64000.0
v2 = v1 * v1 * P6 / 32768.0 + v1 * P5 * 2.0
v2 = v2 / 4.0 + P4 * 65536.0
v1 = (P3 * v1 * v1 / 524288.0 + P2 * v1) / 524288.0
v1 = (1.0 + v1 / 32768.0) * P1
if v1 == 0:
raise IOError("BMP280 보정 오류")
p = 1048576.0 - adc_p
p = (p - v2 / 4096.0) * 6250.0 / v1
v1 = P9 * p * p / 2147483648.0
v2 = p * P8 / 32768.0
p = p + (v1 + v2 + P7) / 16.0
hpa = p / 100.0
if not 300 <= hpa <= 1100:
raise IOError(f"BMP280 범위 밖 기압 {hpa:.1f}")
return {"pressure": round(hpa, 1), "temperature": round(tfine / 5120.0, 1)}
class ADS1115:
"""ADS1115 한 채널(단일 변환). smbus2로 직접 읽는다.
soil_moisture(%)는 dry_v(공기 중 전압)와 wet_v(물에 담갔을 때 전압)로 선형 환산 — 센서마다 달라 반드시 보정.
capacitive 센서는 젖을수록 전압이 내려간다(dry_v > wet_v). 저항식은 반대(젖을수록 올라감, dry_v < wet_v).
power_gpio(BCM 번호)를 주면 센서 VCC를 그 핀에 물려, 측정하는 동안만 켠다(저항식 전극 부식·전해 방지).
settle_s는 전원을 올린 뒤 값이 자리 잡을 때까지 기다리는 시간. GPIO 한 핀은 약 8mA까지만 안전하다."""
MUX = {0: 0x4000, 1: 0x5000, 2: 0x6000, 3: 0x7000}
def __init__(self, cfg):
self.bus = cfg.get("bus", 1); self.addr = cfg.get("address", 0x48); self.ch = cfg["channel"]
self.dry = cfg.get("dry_v", 2.8); self.wet = cfg.get("wet_v", 1.3)
self.settle = cfg.get("settle_s", 0.5); self.pwr = None
if cfg.get("power_gpio") is not None:
from gpiozero import OutputDevice
self.pwr = OutputDevice(cfg["power_gpio"], initial_value=False) # 평소엔 꺼 둔다
def close(self):
if self.pwr:
self.pwr.off(); self.pwr.close(); self.pwr = None
def read(self):
if self.pwr is None:
return self._read()
self.pwr.on()
try:
time.sleep(self.settle)
return self._read()
finally:
self.pwr.off() # 읽기 성공·실패와 무관하게 반드시 끈다
def _read(self):
from smbus2 import SMBus, i2c_msg
cfgword = 0x8000 | self.MUX[self.ch] | 0x0200 | 0x0100 | 0x0080 # OS=1, PGA ±4.096V, 단일, 128SPS
with SMBus(self.bus) as b:
b.write_i2c_block_data(self.addr, 0x01, [cfgword >> 8, cfgword & 0xFF])
time.sleep(0.02)
hi, lo = b.read_i2c_block_data(self.addr, 0x00, 2)
raw = (hi << 8) | lo
raw -= 65536 if raw & 0x8000 else 0
v = raw * 4.096 / 32768
pct = (v - self.dry) / (self.wet - self.dry) * 100
return {"voltage": round(v, 3), "soil_moisture": round(min(max(pct, 0), 100), 1)}
DRIVERS = {"sim": SimSensor, "ds18b20": DS18B20, "dht22": DHT22, "aht20": AHT20, "sht20": SHT20, "avg": AvgSensor, "bmp280": BMP280, "bme280": BMP280, "ads1115": ADS1115}
# ───────────────────────── 릴레이 ─────────────────────────
class RelayPin:
"""gpiozero 릴레이. active_low=True면 LOW가 ON(대부분의 릴레이 모듈). 핀이 없으면 모의(로그만)."""
def __init__(self, name, cfg):
self.name = name; self.on = False
self.dev = None
pin = cfg.get("gpio")
if pin is not None:
from gpiozero import OutputDevice
self.dev = OutputDevice(pin, active_high=not cfg.get("active_low", True), initial_value=False)
def set(self, on):
if on == self.on:
return
self.on = on
if self.dev:
self.dev.on() if on else self.dev.off()
log.info("릴레이 %s → %s", self.name, "ON" if on else "OFF")
def close(self):
self.set(False)
if self.dev:
self.dev.close()
class Actuator:
def __init__(self, name, cfg, relay):
self.name = name; self.cfg = cfg; self.relay = relay
self.mode = "auto" # auto | manual
self.manual = False
self.on_since = None; self.last_off = 0.0
def want(self, on, now):
"""안전 제한을 적용해 실제 릴레이를 움직인다."""
max_run = self.cfg.get("max_run_s"); min_gap = self.cfg.get("min_gap_s", 0)
if on and not self.relay.on and now - self.last_off < min_gap:
on = False # 최소 간격 미충족
if on and self.relay.on and max_run and now - self.on_since >= max_run:
on = False # 최대 가동 초과 → 강제 OFF
if self.mode == "manual":
self.manual = False
if on and not self.relay.on:
self.on_since = now
if not on and self.relay.on:
self.last_off = now
self.relay.set(on)
# ───────────────────────── 본체 ─────────────────────────
class Greenhouse:
def __init__(self, cfg):
self.cfg = cfg; self.stop = threading.Event()
self.values = {} # "air.temperature" → (값, 시각)
self.sensors = []
for s in cfg["sensors"]:
self.sensors.append((s["id"], DRIVERS[s["type"]](s), s))
self.acts = {n: Actuator(n, a, RelayPin(n, a)) for n, a in cfg["actuators"].items()}
m = cfg["mqtt"]; self.node = m.get("node_id", "greenhouse")
self.cl = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=self.node)
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):
log.info("MQTT 연결: %s", rc)
cl.publish(f"{self.node}/status", "online", retain=True)
cl.subscribe(f"{self.node}/+/+/set")
self.discovery()
def dev(self):
return {"identifiers": [self.node], "name": "온실", "model": "Raspberry Pi 2", "manufacturer": "homeclaw"}
def discovery(self):
d = self.dev(); av = f"{self.node}/status"
units = {"temperature": ("°C", "temperature"), "humidity": ("%", "humidity"), "soil_moisture": ("%", "moisture"), "voltage": ("V", "voltage"), "pressure": ("hPa", "pressure")}
for sid, _, s in self.sensors:
for key in s.get("measures", ["temperature"]):
unit, cls = units[key]
self.pub_cfg("sensor", f"{sid}_{key}", {
"name": f"{s.get('name', sid)} {key}", "state_topic": f"{self.node}/{sid}/{key}",
"unit_of_measurement": unit, "device_class": cls, "state_class": "measurement"}, d, av)
for n, a in self.acts.items():
nm = a.cfg.get("name", n)
self.pub_cfg("switch", n, {"name": nm, "state_topic": f"{self.node}/{n}/state",
"command_topic": f"{self.node}/{n}/switch/set", "payload_on": "ON", "payload_off": "OFF"}, d, av)
self.pub_cfg("select", f"{n}_mode", {"name": f"{nm} 모드", "options": ["auto", "manual"],
"state_topic": f"{self.node}/{n}/mode", "command_topic": f"{self.node}/{n}/mode/set"}, d, av)
def pub_cfg(self, comp, oid, payload, dev, av):
payload.update({"unique_id": f"{self.node}_{oid}", "object_id": f"{self.node}_{oid}", "device": dev,
"availability_topic": av})
self.cl.publish(f"homeassistant/{comp}/{self.node}/{oid}/config", json.dumps(payload, ensure_ascii=False), retain=True)
def on_message(self, cl, ud, msg):
_, name, kind, _ = msg.topic.split("/")
a = self.acts.get(name); val = msg.payload.decode().strip()
if not a:
return
if kind == "mode" and val in ("auto", "manual"):
a.mode = val; a.manual = a.relay.on if val == "manual" else False
log.info("%s 모드 → %s", name, val)
elif kind == "switch":
a.mode = "manual"; a.manual = (val == "ON") # 수동 조작 = 수동 모드 진입
log.info("%s 수동 %s", name, val)
self.step()
# --- 측정/제어 ---
# 평활 + 히스테리시스(2026-10-25). 10초마다 소수 첫째 자리로 보내니 실제 기온이 29.65℃ 근처면 29.6↔29.7이
# 10초마다 뒤집혀 HA 그래프가 톱니가 됐다(6시간 222개 중 180번 방향 전환 실측). 지수 평활(시간상수 tau_s)로
# 잔떨림을 누르고, 보낸 값과 deadband 이상 벌어질 때만 새 값을 보낸다. 제어도 평활값을 쓴다.
SMOOTH_DEFAULT = {"tau_s": 60, "deadband": {"temperature": 0.08, "humidity": 0.4, "pressure": 0.15,
"soil_moisture": 0.4, "voltage": 0.005}}
def smooth(self, ref, key, v, now):
cfg = {**self.SMOOTH_DEFAULT, **(self.cfg.get("smoothing") or {})}
st = self._smooth.get(ref)
if st is None or now - st["t"] > 5 * cfg["tau_s"]: # 처음이거나 오래 끊겼으면 새로 시작
st = {"ema": v, "t": now, "pub": v}
else:
a = 1 - math.exp(-(now - st["t"]) / cfg["tau_s"])
st["ema"] += a * (v - st["ema"]); st["t"] = now
band = (cfg.get("deadband") or {}).get(key, self.SMOOTH_DEFAULT["deadband"].get(key, 0))
if abs(st["ema"] - st["pub"]) >= band:
st["pub"] = st["ema"]
self._smooth[ref] = st
digits = 3 if key == "voltage" else 1
return round(st["ema"], digits + 1), round(st["pub"], digits)
def read_sensors(self):
now = time.time()
if not hasattr(self, "_smooth"):
self._smooth = {}
for sid, drv, s in self.sensors:
try:
for k, v in drv.read().items():
if k not in s.get("measures", ["temperature"]):
continue
ref = f"{sid}.{k}"
ema, pub = self.smooth(ref, k, v, now)
self.values[ref] = (ema, now)
self.cl.publish(f"{self.node}/{sid}/{k}", pub, retain=True)
except Exception as e:
log.warning("센서 %s 읽기 실패: %s", sid, e)
def log_local(self, now):
"""측정값을 파이 디스크에 1분마다 CSV로 남긴다(local_log). HA·브로커가 있는 클로서버가 자는 동안(02시~기상)에도
기록이 남아, 깨어난 뒤 클로서버가 빈 구간을 HA에 채운다(scripts/greenhouse-backfill.py). 값이 stale이면 빈 칸."""
lc = self.cfg.get("local_log")
if not lc or now - getattr(self, "_last_log", 0) < lc.get("every_s", 60):
return
self._last_log = now
try:
d = Path(lc.get("dir", "~/greenhouse/data")).expanduser(); d.mkdir(parents=True, exist_ok=True)
keys = [f"{s['id']}.{k}" for s in self.cfg["sensors"] for k in s.get("measures", ["temperature"])]
f = d / (time.strftime("%Y-%m-%d", time.localtime(now)) + ".csv")
new = not f.exists()
with f.open("a", newline="") as fh:
w = csv.writer(fh)
if new:
w.writerow(["ts", "time"] + keys + [f"{n}.state" for n in self.acts])
keep = lc.get("keep_days", 90) # 오래된 파일 정리 (하루 한 번, 새 파일 만들 때)
for old in d.glob("*.csv"):
if now - old.stat().st_mtime > keep * 86400:
old.unlink()
vals = [self.get(k, now) for k in keys]
w.writerow([int(now), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now))]
+ ["" if v is None else v for v in vals]
+ ["ON" if a.relay.on else "OFF" for a in self.acts.values()])
except Exception as e:
log.warning("로컬 기록 실패: %s", e)
def get(self, ref, now):
"""'air.temperature' 값. 오래되었으면(stale) None."""
v = self.values.get(ref)
return v[0] if v and now - v[1] <= self.cfg.get("stale_s", 60) else None
def decide(self, a, now):
"""자동 모드의 희망 상태: True/False. 센서 stale이면 failsafe 값."""
r = a.cfg.get("rule")
if not r:
return False
v = self.get(r["sensor"], now)
if v is None:
return a.cfg.get("failsafe", False)
on = a.relay.on
if "on_below" in r: # 값이 낮으면 켠다(히터·관수)
if v < r["on_below"]: on = True
elif v > r["off_above"]: on = False
else: # 값이 높으면 켠다(환풍기)
if v > r["on_above"]: on = True
elif v < r["off_below"]: on = False
hours = a.cfg.get("allowed_hours")
if on and hours and not (hours[0] <= time.localtime().tm_hour < hours[1]):
on = False
return on
def step(self):
now = time.time()
for n, a in self.acts.items():
want = a.manual if a.mode == "manual" else self.decide(a, now)
cut = a.cfg.get("cutoff") # {sensor: air.temperature, above: 35} — 모드·규칙과 무관한 하드 차단
if cut and want:
cv = self.get(cut["sensor"], now)
if cv is None or cv > cut["above"]:
want = False
if a.relay.on:
log.warning("%s 과열/센서이상 차단 (값=%s)", n, cv)
a.want(want, now)
self.cl.publish(f"{self.node}/{n}/state", "ON" if a.relay.on else "OFF", retain=True)
self.cl.publish(f"{self.node}/{n}/mode", a.mode, retain=True)
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(); self.log_local(time.time())
self.stop.wait(iv)
self.shutdown()
def shutdown(self):
for d in self.displays:
d.stop()
for _, drv, _ in self.sensors: # 센서 전원 핀 등을 반드시 꺼 둔다
getattr(drv, "close", lambda: None)()
for a in self.acts.values():
a.relay.close()
self.cl.publish(f"{self.node}/status", "offline", retain=True).wait_for_publish(2)
self.cl.loop_stop(); self.cl.disconnect()
def main():
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
cfg = yaml.safe_load(Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).with_name("config.yaml")).read_text())
gh = Greenhouse(cfg)
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, lambda *_: gh.stop.set())
gh.run()
if __name__ == "__main__":
main()