示例#1
0
def main(args):
    tello = Tello()
    tello.connect()
    tello.streamon()
    # Create directory to save images if it doesn't exists
    if args.save_img:
        timestamp = str(time.time())
        save_dir = Path(f"{args.save_dir}") / Path(timestamp)
        save_dir.mkdir(parents=True, exist_ok=True)

    fps_delay_ms = int((1 / args.fps) * 1000)

    save_frame_count = 0
    cv2.namedWindow("tello")
    while True:

        key = cv2.waitKey(fps_delay_ms)
        if key & 0xFF == ord("q"):
            # Exit if q pressed
            cv2.destroyAllWindows()
            break

        img = tello.get_frame_read().frame
        if img is not None:

            # Show the image
            cv2.imshow("tello", img)

            # Save the images
            if args.save_img:
                cv2.imwrite(f"{str(save_dir)}/{save_frame_count:07d}.png", img)
                save_frame_count += 1
示例#2
0
文件: graph.py 项目: nspeer12/cvdrone
def data_collection(data_file='data.csv'):
    tello = Tello()
    tello.connect()
    #tello.takeoff()

    start = time.time()
    posx = []
    posy = []
    posz = []
    pitch = []
    roll = []
    yaw = []
    while time.time() - start < 10:
        state = tello.get_current_state()
        print(state)
        posx.append(float(state['agx']))
        posy.append(float(state['agy']))
        posz.append(float(state['agz']))
        pitch.append(float(state['pitch']))
        roll.append(float(state['roll']))
        yaw.append(float(state['yaw']))

    #tello.land()
    d = {
        'x': posx,
        'y': posy,
        'z': posz,
        'pitch': pitch,
        'roll': roll,
        'yaw': yaw
    }
    df = pd.DataFrame(data=d)
    df.dropna(inplace=True)
    df.to_csv('data.csv')
示例#3
0
class DroneActions:
    def __init__(self):
        self.tello = Tello()
        self.tello.connect()
        sleep(2)

    def takeoff(self):
        self.tello.takeoff()
        while self.tello.get_h() < 30:
            sleep(0.5)

    def land(self):
        self.tello.land()

    def execute(self, command):
        self.send_control_command(*command)

    def set_velocity(self, values):
        self.tello.send_rc_control(*values)

    def find_pink(self):
        self.set_velocity([0, 0, 0, 100])
        sleep(2)
        self.set_velocity([0, 0, 0, 0])

    def choreo(self):
        self.takeoff()
        self.find_pink()
        self.land()
示例#4
0
def start_tello():
    '''
    Connects to drone and sets velocities and speed to 0
    Cycles drone stream
    '''
    #makes drone and connects to it
    drone = Tello()
    drone.connect()

    #sets all drones velocity to 0
    drone.forward_backward_velocity = 0
    drone.left_right_velocity = 0
    drone.up_down_velocity = 0
    drone.yaw_velocity = 0
    drone.speed = 0

    #cycles drone stream off and on
    drone.streamoff()
    drone.streamon()

    #prints drone's battery at start
    time.sleep(5)
    print(drone.get_battery())

    return drone
示例#5
0
class DroneCamera():
    def __init__(self):
        self.drone = Tello()  # Instantiate a Tello Object
        self.drone.connect()  # Connect to the drone
        self.drone.streamoff()  # In case stream never exited before
        self.drone.streamon()  # Turn on drone camera stream
        time.sleep(5)  # Give the stream time to start up
        self.timer = 0  # Timing for printing statements

    def __del__(self):
        self.drone.streamoff()

    def get_frame(self):
        # Grab a frame and resize it
        frame_read = self.drone.get_frame_read()
        if frame_read.stopped:
            return None
        frame = cv2.resize(frame_read.frame, (360, 240))

        # Print battery status to the log every 10 seconds
        if (time.time() - self.timer > 10):
            self.timer = time.time()
            self.drone.get_battery()

        # encode OpenCV raw frame to jpeg
        ret, jpeg = cv2.imencode('.jpg', frame)
        return jpeg.tobytes()
示例#6
0
class Config:
    def __init__(self):
        self.time_of_initialization = time.time()
        self.props = self.read_properties()

        self.use_drone = True
        self.drone_flying = False
        self.drone = None

        self.calculate_additional_props()

        if self.use_drone:
            self.connect_to_drone()
        else:
            self.cap = cv2.VideoCapture(0)

    def connect_to_drone(self):
        self.drone = Tello()
        self.drone.connect()
        self.drone.streamon()
        self.cap = self.drone.get_frame_read()
        self.drone_takeoff()
        self.drone.move_up(100)

    def drone_respond_ready(self):
        return time.time(
        ) - self.time_of_initialization > self.props["drone"]["respond_delay"]

    def frame(self):
        if self.use_drone:
            frame = self.cap.frame
        else:
            ret, frame = self.cap.read()

        return frame

    def stop_streaming(self):
        if self.use_drone:
            self.drone.streamoff()
        else:
            self.cap.release()

    def drone_emergency_stop(self):
        self.drone.emergency()
        self.drone_flying = False

    def drone_takeoff(self):
        self.drone.takeoff()
        self.drone_flying = True

    def read_properties(self):
        with open('./config/properties.json') as json_file:
            props = json.load(json_file)

        return props

    def calculate_additional_props(self):
        self.props["img"]["height"] = 300
        self.props["img"]["frame_center_x"] = self.props["img"]["width"] * 0.5
        self.props["img"]["frame_center_y"] = self.props["img"]["height"] * 0.5
def cameraCalibration(filename):
    CALI_IMG_NUM = 50
    # termination criteria for cv2.cornerSubPix
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)

    # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(8,5,0) // (x, y, 0)
    objp = np.zeros((9 * 6, 3), np.float32)
    objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)

    # Arrays to store object points and image points from all the images.
    objpoints = []  # 3d point in real world space
    imgpoints = []  # 2d points in image plane.

    drone = Tello()
    drone.connect()
    drone.streamon()
    drone.get_frame_read()
    # cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)

    # capturing img for calibration
    print('Capturing...')
    cnt = 0
    while (True):
        frame = drone.background_frame_read.frame
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)
        if ret == True:
            print(f'chessboard_{cnt}')
            cnt += 1
            if cnt > CALI_IMG_NUM:
                break
            objpoints.append(objp)

            corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1),
                                        criteria)
            imgpoints.append(corners2)

            # Draw and display the corners
            frame = cv2.drawChessboardCorners(frame, (9, 6), corners2, ret)
        cv2.imshow('chessboard', frame)
        key = cv2.waitKey(200)
    cv2.destroyAllWindows()

    # calibration
    print('calibrating...')
    ret, cameraMatrix, distCoeffs, rvecs, tvecs = cv2.calibrateCamera(
        objpoints, imgpoints, gray.shape[::-1], None, None)
    # shape[::-1] : reversed slicing
    # refine parameters
    h, w = 720, 960  # telloCam shape
    newcameramtx, roi = cv2.getOptimalNewCameraMatrix(cameraMatrix, distCoeffs,
                                                      (w, h), 0, (w, h))

    f = cv2.FileStorage(filename, cv2.FILE_STORAGE_WRITE)
    f.write("intrinsic", cameraMatrix)
    f.write("distortion", distCoeffs)
    f.write("newcameramtx", newcameramtx)
    f.release()
    print('calibration finished!!')
    exit()
def main():
    global manual_command, stop

    thread_fly = None

    tello = Tello()

    # Remove most of the log lines
    logger = logging.getLogger('djitellopy')
    logger.setLevel(logging.CRITICAL)

    tello.connect()
    try:
        tello.streamon()

        thread_fly = Thread(target=fly, args=[tello])
        thread_fly.start()

        while not stop:
            manual_command = input(
                "Pulsa una tecla de dirección o escribe un comando ('despegar','aterrizar','giro horario', 'giro antihorario', 'salir'): "
            )

    except:
        error = sys.exc_info()[0]
        print("Unexpected error:", error)
    finally:
        stop = True

        if not thread_fly is None:
            thread_fly.join()

        tello.land()
        tello.streamoff()
        tello.end()
示例#9
0
def main():
    print("now i am gonna start the mission")
    tello = Tello()
    tello.connect()
    tello.streamoff()
    tello.streamon()
    start = starting(tello)
    start.run(0)
示例#10
0
def main():
    tello = Tello()
    tello.connect()
    tello.streamoff()
    tello.streamon()
    frontend = FrontEnd(tello)

    # run frontend
    frontend.run()
示例#11
0
def run(CommandsQueue):

    move_distance = 30
    idle_sleep = 2  #sec
    video_ready_sleep = 7  #sec
    is_airborn = False
    global is_active

    tello = Tello()
    tello.connect()
    tello.set_speed(10)

    droneVid = threading.Thread(target=drone_video, args=(tello, ))
    droneVid.start()
    time.sleep(video_ready_sleep)

    while is_active:

        #execute next command from the que
        if not CommandsQueue.empty():
            command = CommandsQueue.get()
            timeStamp = str(datetime.datetime.now())
            print('Command for Drone: ' + str(command[0]) + ' at time ' +
                  timeStamp)

            if command[0] == Commands.up:
                if is_airborn:
                    tello.move_up(move_distance)
                else:
                    tello.takeoff()
                    is_airborn = True
            # elif command[0] == Commands.idle:
            #     time.sleep(idle_sleep)
            elif command[0] == Commands.up and is_airborn == True:
                tello.move_up(move_distance)
            elif command[0] == Commands.down and is_airborn == True:
                tello.move_down(move_distance)
            elif command[0] == Commands.forward and is_airborn == True:
                tello.move_forward(move_distance)
            elif command[0] == Commands.back and is_airborn == True:
                tello.move_back(move_distance)
            elif command[0] == Commands.left and is_airborn == True:
                tello.move_left(move_distance)
            elif command[0] == Commands.right and is_airborn == True:
                tello.move_right(move_distance)
            elif command[0] == Commands.flip and is_airborn == True:
                tello.flip_back()
            elif command[0] == Commands.stop:
                is_active = False
                break
        # else:
        #     time.sleep(idle_sleep)

    tello.land()
    is_airborn = False
    droneVid.join()
    tello.end()
示例#12
0
def main():
    print("now i am gonna start the mission")
    tello = Tello()
    tello.offset = 60
    tello.connect()
    tello.streamoff()
    tello.streamon()
    start = hoohah(tello)
    start.run()
示例#13
0
def initializeTello():
    myDrone = Tello()
    myDrone.connect()
    myDrone.for_back_velocity = 0
    myDrone.up_down_velocity = 0
    myDrone.speed = 0
    myDrone.left_right_velocity = 0
    myDrone.yaw_velocity = 0
    myDrone.streamoff()
    myDrone.stream_on
    return myDrone
示例#14
0
def new_drone() -> Tello:
    drone = Tello()
    drone.connect()
    drone.for_back_velocity = 0
    drone.left_right_velocity = 0
    drone.up_down_velocity = 0
    drone.yaw_velocity = 0
    drone.speed = 0
    drone.streamoff()
    drone.streamon()
    return drone
示例#15
0
def initializeTello():
    tccdrone = Tello()
    tccdrone.connect()
    tccdrone.for_back_velocity = 0
    tccdrone.left_right_velocity = 0
    tccdrone.up_down_velocity = 0
    tccdrone.yaw_velocity = 0
    tccdrone.speed = 0
    print(tccdrone.get_battery())
    tccdrone.streamoff()
    tccdrone.streamon()
    return tccdrone
示例#16
0
def initializeTello():
    JwTello = Tello()
    JwTello.connect()
    JwTello.for_back_velocity = 0
    JwTello.left_right_velocity = 0
    JwTello.up_down_velocity = 0
    JwTello.yaw_velocity = 0
    JwTello.speed = 0
    print(JwTello.get_battery())
    JwTello.streamoff()
    JwTello.streamon()
    return JwTello
 def initialize(self):
     myDrone = Tello()
     myDrone.connect()
     myDrone.for_back_velocity = 0
     myDrone.left_right_velocity = 0
     myDrone.up_down_velocity = 0
     myDrone.yaw_velocity = 0
     myDrone.speed = 0
     print(myDrone.get_battery())
     myDrone.streamoff()
     myDrone.streamon()
     return myDrone
示例#18
0
def initializeDrone():
    drone = Tello()
    drone.connect()
    drone.for_back_velocity = 0
    drone.left_right_velocity = 0
    drone.up_down_velocity = 0
    drone.yaw_velocity = 0
    drone.speed = 0
    print(drone.get_battery())
    drone.streamoff()
    drone.streamon()
    return drone
示例#19
0
def main():
    print("ahahah")
    tello = Tello()
    tello.connect()
    tello.streamoff()
    tello.streamon()
    frontend = FrontEnd(tello)
    print("noooo")

    frontend.run(1, 0, tello.get_yaw())  #left,up

    print("found the end of the code")
示例#20
0
def main():
    print("now i am gonna start the mission")
    tello = Tello()
    tello.connect()
    try:
        tello.takeoff()
    except:
        pass
    tello.streamoff()
    tello.streamon()
    start = starting(tello)
    a, b, c = start.run(tello.get_yaw())
    print("UP is {} and right is {}".format(a, b))
示例#21
0
def initTello():
    tello = Tello()
    tello.connect()
    tello.for_back_velocity = 0
    tello.left_right_velocity = 0
    tello.up_down_velocity = 0
    tello.yaw_velocity = 0
    tello.speed = 0
    print(tello.get_battery())
    # tello.streamoff()
    tello.streamon()
    tello.takeoff()
    return tello
示例#22
0
def intializeTello():
    # CONNECT TO TELLO
    myDrone = Tello()
    myDrone.connect()
    myDrone.for_back_velocity = 0
    myDrone.left_right_velocity = 0
    myDrone.up_down_velocity = 0
    myDrone.yaw_velocity = 0
    myDrone.speed = 0
    # print(myDrone.get_battery())
    myDrone.streamoff()
    myDrone.streamon()
    return myDrone
示例#23
0
def main():
    tello = Tello()
    tello.connect()
    tello.streamoff()
    tello.streamon()
    frontend = FrontEnd(tello)
    right = 0
    while(right<2):
        right = frontend.run(right)
        print("right is now hsdawqbvqwuja : {}".format(right))
        frontend.clear()

    print("found the end of the code")
    tello.land()
    tello.end()
示例#24
0
def run():
    tello = Tello()
    counter = 0

    if not tello.connect():
        print("Tello not connected")
        return
    # In case streaming is on. This happens when we quit this program without the escape key.
    if not tello.streamoff():
        print("Could not stop video stream")
        return
    if not tello.streamon():
        print("Could not start video stream")
        return
    frame_read = tello.get_frame_read()

    while (True):
        # Our operations on the frame come here
        frame = frame_read.frame
        time.sleep(10)

        cv2.imwrite('frame-{}.png'.format(counter), frame_read.frame)
        counter += 1
        # Display the resulting frame
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cv2.destroyAllWindows()
class TelloProxy(AdapterThing):
    '''
    对象内部可能出现意外错误,重置积木(重启整个插件)
    self.thing = Tello() 由于是udp 所以与wifi的通断 不影响, self.thing总是可用
    '''
    def __init__(self, node_instance):
        super().__init__(thing_name="Tello",
                         node_instance=node_instance)

    def list(self, timeout=5) -> list:
        if not self.thing:
            self.thing = Tello()
        self.thing.RESPONSE_TIMEOUT = timeout
        logger.debug(f"self.thing: {self.thing}")
        try:
            # if True:  # self.thing.connect():  # RESPONSE_TIMEOUT 7 ,判断是否可连接
            # logger.debug(f"self.thing.connect(): {self.thing.connect()}")
            self.thing.connect() #  返回True有问题,如果没有飞机,就会except
            return ["192.168.10.1"]
        except Exception as e:  # timeout
            # self.thing.connect() except
            logger.debug(f'error: {str(e)}')
            self.node_instance.pub_notification(str(e),
                                                type="ERROR")
            return []

    def connect(self, ip, timeout=5):
        # 修改 self.thing
        if not self.thing:
            self.thing = Tello()
        is_connected = self.thing.connect()  # 幂等操作 ,udp
        self.is_connected = is_connected
        return True

    def status(self, **kwargs) -> bool:
        # check status
        # query thing status, 与设备通信,检查 is_connected 状态,修改它
        return self.thing.connect()  # 超时7秒

    def disconnect(self):
        self.is_connected = False
        try:
            if self.thing:
                self.thing.clientSocket.close()  # 断开,允许本地其他client(如python client)
        except Exception:
            pass
        self.thing = None
class TelloProxy(AdapterThing):
    '''
    该类的主要职责是实现与 Scratch UI 的兼容性
    '''
    def __init__(self, node_instance):
        super().__init__(thing_name="Tello", node_instance=node_instance)

    def list(self, timeout=5) -> list:
        # 必须实现
        # scratch scan 会触发这个函数,返回值将进入 Scratch 扫描到的设备列表中。
        if not self.thing:
            self.thing = Tello()
        self.thing.RESPONSE_TIMEOUT = timeout
        logger.debug(f"self.thing: {self.thing}")
        try:
            self.thing.connect()  # 返回True有问题,如果没有飞机,就会except
            return ["192.168.10.1"]
        except Exception as e:
            logger.debug(f'error: {str(e)}')
            self.node_instance.pub_notification(str(e), type="ERROR")
            return []

    def connect(self, ip, timeout=5):
        # 必须实现
        # 用户在 scratch 界面点击连接时,会触发该函数
        if not self.thing:
            self.thing = Tello()
        is_connected = self.thing.connect()  # 幂等操作 ,udp
        self.is_connected = is_connected
        return True

    def status(self):
        # 必须实现
        # return self.thing.connect()
        pass

    def disconnect(self):
        # 必须实现
        # Scratch 断开设备
        self.is_connected = False
        try:
            if self.thing:
                self.thing.clientSocket.close()
        except Exception:
            pass
        self.thing = None
示例#27
0
def initializeTello():
    # METHOD: CONNECT TO TELLO

    myDrone = Tello()  # Create a Tello object
    myDrone.connect()  # Connect PC to Tello ()
    # Set all velocity and speed of drone to 0
    myDrone.for_back_velocity = 0
    myDrone.left_right_velocity = 0
    myDrone.up_down_velocity = 0
    myDrone.yaw_velocity = 0
    myDrone.speed = 0

    print(myDrone.get_battery())  # Print out percentage of battery
    myDrone.streamoff()  # Turn off video stream of drone
    myDrone.streamon()  # Turn on video stream of drone
    print("battery: ", myDrone.get_battery())
    return myDrone
示例#28
0
def main():
    tello = Tello()
    tello.connect()

    print(f"battery level: {tello.get_battery()}")
    print(f"temp: {tello.get_temperature()}")
    tello.takeoff()
    tello.move_left(50)
    tello.move_right(50)
    tello.rotate_clockwise(360)

    print(f"Waiting for 1 secs")
    time.sleep(1)
    tello.flip_left()

    tello.land()
    tello.end()
示例#29
0
class Drone(object):
    def __init__(self):
        self.drone = None
        self.drone_speed = 25
        self.connect_drone()

    def __del__(self):
        global tello_conn
        print("tello destroyed")
        self.disconnect_drone()
        tello_conn.close()

    def begin_scan(self):
        i = 18
        sleep(1)
        while i != 0:
            self.drone.rotate_clockwise(21)
            sleep(2)
            self.drone.move_up(23)
            sleep(3)
            self.drone.move_down(23)
            i -= 1
            sleep(3)

    def stream_image_to_pipe(self):
        camera = picamera.PiCamera()
        camera.resolution = (640, 480)
        output_path = vars(ap.parse_args())['output']
        filename = os.path.join(output_path, 'outpy.h264')
        print('Save video to: ', filename)
        camera.start_recording(filename)
        while True:
            camera.wait_recording(1)
        camera.stop_recording()
        print("Created video file")

    def connect_drone(self):
        self.drone = Tello()
        if not self.drone.connect():
            raise RuntimeError("drone not connected")
        self.drone.streamon()

    def disconnect_drone(self):
        self.drone.streamoff()
        self.drone = None

    def scan(self, triangulation_type):
        self.drone.takeoff()
        sleep(3)
        Thread(target=self.stream_image_to_pipe, daemon=True).start()
        self.begin_scan(triangulation_type)
        print("battery after scan:" + self.drone.get_battery())
        self.drone.land()
        sleep(3)
示例#30
0
def main():
    # CONNECT TO TELLO
    me = Tello()
    me.connect()
    me.for_back_velocity = 0
    me.left_right_velocity = 0
    me.up_down_velocity = 0
    me.yaw_velocity = 0
    me.speed = 0

    print(me.get_battery())

    me.streamoff()
    me.streamon()
    ########################

    me.takeoff()
    flyCurve(me, 160, 50)
    time.sleep(5)
    me.land()