# ======================================================================
# 10회차 | 05 변형 - 지형 단면도 그리기
# ----------------------------------------------------------------------
# 지형 따라가기를 하면서 tof 와 h 를 기록하고, 착륙한 뒤 "지나온 바닥의 모양"을 그린다.
#
# 어떻게 장애물 높이를 알 수 있을까? (어림)
#   맨바닥 위에서 : h - tof = 어떤 값 A
#   상자 위에서   : tof 는 상자 높이만큼 줄어든다 -> (h - tof) 가 A 보다 커진다
#   그래서        장애물 높이 ≈ (h - tof) - A
#   * 정확하지 않을 수 있다. 줄자로 잰 상자 높이와 비교해 보는 것이 이 실험의 핵심!
#
# 결과 : terrain.csv 저장 + 그래프 (matplotlib 가 있으면)
# ======================================================================

import csv

from tello import start

tello_id = "TELLO-58C5B7"      # 내 드론 이름으로 바꾸기

TARGET = 50
GAIN = 1.5
FORWARD = 15
DURATION = 12


def clamp(v, m):
    return int(max(-m, min(m, v)))


rows = []


def run():
    takeoff()
    hover(1)
    t0 = time.time()
    while time.time() - t0 < DURATION:
        s = get_state()
        tof, h = s.get("tof", 0), s.get("h", 0)
        ud = 0
        if 10 < tof < 300:
            err = TARGET - tof
            ud = 0 if abs(err) < 5 else clamp(err * GAIN, 60)
            rows.append((round(time.time() - t0, 2), tof, h))
        if not 10 < tof < 300:
            stop()
            raise RuntimeError("아래 거리 값이 유효하지 않아 지형 추종을 중단합니다.")
        rc(0, FORWARD, ud, 0)
        time.sleep(0.1)
    stop()
    hover(1)
    land()


start(tello_id, run)

# ---- 착륙 후 : 계산하고 그리기 ----
if len(rows) < 10:
    raise SystemExit("기록이 너무 적습니다.")

base = sum(h - tof for _, tof, h in rows[:5]) / 5          # 처음 0.5초 = 맨바닥이라고 보고
ground = [(t, (h - tof) - base) for t, tof, h in rows]

with open("terrain.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.writer(f)
    w.writerow(["t", "tof", "h", "장애물 높이 어림"])
    for (t, tof, h), (_, g) in zip(rows, ground):
        w.writerow([t, tof, h, round(g, 1)])
print("terrain.csv 저장")
print(f"가장 높은 장애물 어림 : {max(g for _, g in ground):.0f}cm  <- 줄자로 잰 값과 비교!")

try:
    import matplotlib.pyplot as plt
    plt.rcParams["font.family"] = "Malgun Gothic"
    plt.rcParams["axes.unicode_minus"] = False
    ts = [t for t, _ in ground]
    plt.fill_between(ts, [g for _, g in ground], color="sienna", alpha=0.5, label="장애물 (어림)")
    plt.plot(ts, [h - base for _, _, h in rows], label="드론 높이 (h)")
    plt.xlabel("시간 (초)  (앞으로 간 거리에 비례)")
    plt.ylabel("cm")
    plt.title("지형 단면도")
    plt.legend()
    plt.grid(alpha=0.3)
    plt.show()
except ImportError:
    print("(matplotlib 가 없어서 그래프는 생략)")
