# ======================================================================
# 08회차 | 10 기록 - 그래프 그리기 (드론 없이)
# ----------------------------------------------------------------------
# 09번 파일이 만든 flight_log.csv 를 읽어서 그래프로 그린다.
# 드론, tello.py 둘 다 필요 없다. (matplotlib 필요 : 명령 프롬프트에서 pip install matplotlib)
#
# 그래프 보는 법
#   위   : h(이륙 기준 높이)와 tof(바닥까지 거리). 이륙, up 50, down 50, 착륙이 보이나?
#          줄자로 잰 50cm 와 그래프의 높이 차이를 비교해 보기
#   가운데 : pitch, roll (기울기). 언제 크게 흔들렸나?
#   아래 : yaw (머리 방향). cw(180) 때 얼마나 바뀌었나?
#
# 그림은 flight_graph.png 로도 저장된다. (보고서, 발표에 쓰기)
# ======================================================================

import csv

import matplotlib.pyplot as plt

LOG_FILE = "flight_log.csv"

plt.rcParams["font.family"] = "Malgun Gothic"     # 한글 글꼴 (Windows)
plt.rcParams["axes.unicode_minus"] = False        # 마이너스 기호 깨짐 방지


def to_float(v):
    try:
        return float(v)
    except (TypeError, ValueError):
        return None


cols = {}
with open(LOG_FILE, encoding="utf-8-sig") as f:
    for row in csv.DictReader(f):
        for k, v in row.items():
            cols.setdefault(k, []).append(to_float(v))

t = cols["t"]
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(9, 8), sharex=True)

ax1.plot(t, cols["h"], label="h (이륙 기준 높이)")
ax1.plot(t, cols["tof"], label="tof (바닥까지 거리)")
ax1.set_ylabel("cm")
ax1.legend()
ax1.grid(alpha=0.3)

ax2.plot(t, cols["pitch"], label="pitch (앞뒤 기울기)")
ax2.plot(t, cols["roll"], label="roll (좌우 기울기)")
ax2.set_ylabel("°")
ax2.legend()
ax2.grid(alpha=0.3)

ax3.plot(t, cols["yaw"], label="yaw (머리 방향)", color="purple")
ax3.set_ylabel("°")
ax3.set_xlabel("시간 (초)")
ax3.legend()
ax3.grid(alpha=0.3)

fig.suptitle("비행 기록")
fig.tight_layout()
fig.savefig("flight_graph.png", dpi=120)
print("flight_graph.png 저장")
plt.show()
