# ======================================================================
# 08회차 | 11 도전 - 실시간 센서 그래프 (날지 않음)
# ----------------------------------------------------------------------
# 드론을 손으로 들고 움직이는 동안, 센서 값을 실시간 그래프로 본다. (30초)
#   위 : tof (바닥까지 거리)  -> 배 밑에 손을 대거나 드론을 들어 올려 보기
#   아래 : pitch, roll        -> 앞뒤, 좌우로 기울여 보기
# 그래프 창을 닫으면 일찍 끝난다. (matplotlib 필요)
#
# 새로 나오는 것
#   - deque(maxlen=150) : 최근 150개만 기억하는 목록 (오래된 것은 저절로 버려진다)
#   - plt.ion() + plt.pause(0.1) : 그래프를 0.1초마다 다시 그리기
# ======================================================================

import collections

import matplotlib.pyplot as plt

from tello import start

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

SECONDS = 30

plt.rcParams["font.family"] = "Malgun Gothic"
plt.rcParams["axes.unicode_minus"] = False


def run():
    plt.ion()
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
    ts = collections.deque(maxlen=150)
    tofs = collections.deque(maxlen=150)
    pitches = collections.deque(maxlen=150)
    rolls = collections.deque(maxlen=150)

    line_tof, = ax1.plot([], [], label="tof (cm)")
    line_p, = ax2.plot([], [], label="pitch (°)")
    line_r, = ax2.plot([], [], label="roll (°)")
    ax1.legend(loc="upper left")
    ax2.legend(loc="upper left")
    ax1.grid(alpha=0.3)
    ax2.grid(alpha=0.3)
    ax2.set_xlabel("시간 (초)")
    fig.suptitle("드론을 들고 움직여 보세요")

    t0 = time.time()
    while time.time() - t0 < SECONDS and plt.fignum_exists(fig.number):
        s = get_state()
        ts.append(time.time() - t0)
        tofs.append(s.get("tof", 0))
        pitches.append(s.get("pitch", 0))
        rolls.append(s.get("roll", 0))

        line_tof.set_data(ts, tofs)
        line_p.set_data(ts, pitches)
        line_r.set_data(ts, rolls)
        for ax in (ax1, ax2):
            ax.relim()
            ax.autoscale_view()
        plt.pause(0.1)

    plt.ioff()
    print("끝! 그래프 창을 닫으면 프로그램이 끝납니다.")
    plt.show()


start(tello_id, run)
