from djitellopy import Tello
import cv2
import time
import threading

atterrissage=threading.Event()
atterrissage.clear()

def vol():
    tello.takeoff()

    if not tello.is_flying:
        tello.takeoff()

    time.sleep(1)
    atterrissage.set()

   
tello = Tello()
tello.connect()

battery_level = tello.get_battery()
print(f"Battery Life Percentage: {battery_level}")

time.sleep(2)

tello.streamon()

frame_read = tello.get_frame_read()

# create a thread to run the function
thread_vol = threading.Thread(target=vol, daemon=True)
thread_vol.start()

time.sleep(2)

while True:
    # read a single image from the Tello video feed
    image = frame_read.frame

    # use opencv to write image
    if image is not None:
        cv2.imshow("VideoDrone", image)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
    
    if atterrissage.is_set():
        tello.land()
        break

# set a flag to instruct flight_pattern function to exit


time.sleep(1)

tello.streamoff()
cv2.destroyWindow('VideoDrone')
cv2.destroyAllWindows()
