Beispiel #1
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Tello video stream")
        self.screen = pygame.display.set_mode([960, 720])

        # Drone velocities between -100~100
        self.for_back_velocity = 0
        self.left_right_velocity = 0
        self.up_down_velocity = 0
        self.yaw_velocity = 0
        self.speed = 10

        self.tello = Tello()
        self.send_rc_control = False
        pygame.time.set_timer(pygame.USEREVENT + 1, 1000 // FPS)

        self.personTracker = PersonTracker()

        self.Px, self.Ix, self.Dx = 0.10, 0, -0  #D gain should be negative.
        self.Py, self.Iy, self.Dy = 0.1, 0, -0
        self.Pz, self.Iz, self.Dz = 0.25, 0, -0.001

        self.prev_err_x, self.prev_err_y, self.prev_err_z = None, None, None
        self.accum_err_x, self.accum_err_y, self.accum_err_z = 0, 0, 0
        self.found_person = False
        self.manual = True

        self.iter = 0
def main():
    clearScreen = os.system('cls' if os.name == 'nt' else 'clear')

    def on_press(key):
        #print('{0} pressed'.format(key))
        if key == Key.shift_l or key == Key.shift_r:
            run(tello)

    def on_release(key):
        #print('{0} release'.format(key))
        if key == Key.shift_l or key == Key.shift_r:
            #listen(robot)
            pass

    try:
        tello = Tello()
        tello.send_command('command')
        print("\n準備ができたら <SHIFT> キーを押してください")
        if wait_for_shift:
            with Listener(on_press=on_press,
                          on_release=on_release) as listener:
                listener.join()
        else:
            while 1:
                run(tello)
    except SystemExit as e:
        print('exception = "%s"' % e)
        exit()
Beispiel #3
0
    def do_POST(self):
        ctype, pdict = cgi.parse_header(self.headers['content-type'])

        # convert pdict[boundary] to bytes
        pdict['boundary'] = pdict['boundary'].encode("utf-8")
        pdict['CONTENT-LENGTH'] = 10000

        if ctype == 'multipart/form-data':
            fields = cgi.parse_multipart(self.rfile, pdict)
        else:
            # only form-data is accepted
            fields = {}

        steps = parse_form_data(fields)

        tello = Tello()
        if tello.can_fly:
            tello.execute(steps)
            response_code = 200
        else:
            response_code = 400

        # Send the "message" field back as the response.
        self.send_response(response_code)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(b'')
Beispiel #4
0
    def __init__(self):
        self.tello = Tello()
        self.tello.sendCmd("streamon")  #스트리밍 모드
        pygame.init()
        pygame.display.set_caption("KNUE Drone Stream")
        self.screen = pygame.display.set_mode([960, 720])
        pygame.time.set_timer(USEREVENT + 1, 50)

        self.font = pygame.font.Font("freesansbold.ttf", 14)
    def __init__(self):
        self.tello = Tello()
        #drone = tello.Tello('', 8889)
        self.tello_ui = TelloUI(self.tello, "./img/")
        # start the Tkinter
        #print("before main loop")
        # self.thread = threading.Thread(target=self.start_main_loop())
        # self.thread.start()

        print("after tello_ui initialization")
Beispiel #6
0
def start():
    print('started')
    """
    Starts sending commands to Tello.
    :param file_name: File name where commands are located.
    :return: None.
    """
    start_time = str(datetime.now())

    #with open(file_name, 'r') as f:
    #commands = f.readlines()

    commands = [
        "command", "battery?", "takeoff", "delay 2", "left 25", "right 25",
        "command", "delay 2", "down 50", "delay 2", "land", "battery?"
    ]

    tello = Tello()
    for command in commands:
        #print("running thru commands")
        #if command != '' and command != '\n':
        #command = command.rstrip()

        #if there is a delay command
        if command.find('delay') != -1:
            sec = float(command.partition('delay')[2])
            print(f'delay {sec}')
            time.sleep(sec)
            pass
        else:
            #if command == "streamon" or command == "streamoff":
            #tello.send_command(command, "cam")
            if 2 == 1:
                print("oh???")

            else:
                tello.send_command(command)
                #tello.send_command(command, "general")
                #print("asking for response")
                #response = tello.get_response()
                #print("Here is the drone response")
                #print(response)

    with open(f'log.{start_time}.txt', 'w') as out:
        log = tello.get_log()

        for stat in log:
            stat.print_stats()
            s = stat.return_stats()
            out.write(s)
Beispiel #7
0
    def __init__(self):
        # Init pygame
        pygame.init()

        # Init Tello object that interacts with the Tello drone
        self.tello = Tello()

        # Drone velocities between -100~100
        self.for_back_velocity = 0
        self.left_right_velocity = 0
        self.up_down_velocity = 0
        self.yaw_velocity = 0
        self.speed = 10
        self.faceFound = False
        self.send_rc_control = True
Beispiel #8
0
def start():
    qt = QtWidgets.QApplication()
    app = App(Tello())
    app.setMinimumWidth(300)
    app.show()
    Thread(target=app.connect_tello).start()
    qt.exec_()
Beispiel #9
0
    def _receive_thread(self):
        """ Listen continually to responses from the Tello - should run in its own thread.

            This method includes capturing and saving each Tello the first time it responds.
            If it is a known Tello, the response will be matched against the Tello's log, always recording the response
            against the last log entry as commands sent to each Tello are strictly sequential.
            Responses are also tested for success or failure, and if relevant an alternative command may be sent
            immediately on error.
        """

        while not self.terminate_comms:
            try:
                # Get responses from all Tellos - this line blocks until a message is received - and reformat values
                response, ip = self.control_socket.recvfrom(1024)
                response = response.decode().strip()
                ip = str(ip[0])

                # Capture Tellos when they respond for the first time
                if response.lower() == 'ok' and ip not in [
                        tello.ip for tello in self.tellos
                ]:
                    print('[Tello Search]Found Tello on IP %s' % ip)
                    self.tellos.append(Tello(ip))
                    continue

                # Get the current log entry for this Tello
                tello = self._get_tello(ip)
                log_entry = tello.log_entry()

                # Determine if the response was ok / error (or reading a value)
                send_on_error = False
                if log_entry.command_type in ['Control', 'Set']:
                    if response == 'ok':
                        log_entry.success = True
                    else:
                        log_entry.success = False
                        if log_entry.on_error is not None:
                            # If this command wasn't successful, and there's an on_error entry, flag to send it later.
                            send_on_error = True
                elif log_entry.command_type == 'Read':
                    # Assume Read commands are always successful... not aware they can return anything else!?
                    log_entry.success = True
                else:
                    print('[Response %s]Invalid command_type: %s' %
                          (ip, log_entry.command_type))
                # Save .response *after* .success, as elsewhere we use .response as a check to move on - avoids race
                # conditions across the other running threads, which might otherwise try to use .success before saved.
                log_entry.response = response
                print('[Response %s]Received: %s' % (ip, response))
                # If required, queue the alternative command - assume same command type as the original.
                if send_on_error:
                    tello.add_to_command_queue(log_entry.on_error,
                                               log_entry.command_type, None)
                    print('[Command  %s]Queuing alternative cmd: %s' %
                          (ip, log_entry.on_error))

            except socket.error as exc:
                if not self.terminate_comms:
                    # Report socket errors, but only if we've not told it to terminate_comms.
                    print('[Socket Error]Exception socket.error : %s' % exc)
 def __init__(self,
              game,
              x,
              y,
              left,
              right,
              up,
              down,
              fly,
              land,
              stand_img,
              right_img,
              left_img,
              speedup=1):
     self.groups = game.all_sprites
     pg.sprite.Sprite.__init__(self, self.groups)
     self.z = 0
     self.stand_img = stand_img
     self.right_img = right_img
     self.left_img = left_img
     self.game = game
     self.image = self.stand_img
     self.rect = self.image.get_rect()
     self.radius = self.rect.width / 2 * .85
     self.rect.center = (x, y)
     self.speedx = 0
     self.speedy = 0
     self.mode = "Manual"
     self.left = left
     self.right = right
     self.up = up
     self.down = down
     self.fly = fly
     self.land = land
     self.speedup = speedup
     self.current_checkpoint = 0
     self.flying = False
     self.current_angle = 0
     self.next_distance = 0
     self.next_angle = 0
     self.target_next_route = None
     self.route = DRONE_ROUTES[0]
     self.tello = Tello()
     self.tello.send("command")
     self.tello.send("streamon")
     self.current_command = "command"
     self.completed = 0
 def __init__(self, height, width):
     """Start loading"""
     namedWindow("drone")
     self.paper = imread("./resources/Tello.png")
     self.height = height
     self.width = width
     self.fv = FaceVector(height, width)
     self.tello = Tello()
     # Drone velocities between -100~100
     self.for_back_velocity = 20
     self.left_right_velocity = 20
     self.up_down_velocity = 20
     self.yaw_velocity = 20
     self.speed = 20
     self.send_rc_control = False
     self.should_stop = False
     self.mode = "keyboard"
Beispiel #12
0
    def __init__(self):
        # Setup drone topics (commands and telemetry)
        rospy.Subscriber('cmd_vel', Twist, self.__send_cmd)
        rospy.Subscriber('cmd_action', String, self.__action)
        self.pub_tel = rospy.Publisher('telemetry', telemetry, queue_size=1)

        # set drone ip and port from launch file
        self.drone_ip = rospy.get_param('drone_ip', "192.168.0.1")
        self.drone_port = rospy.get_param('drone_port', 8889)
        self.drone_timeout = rospy.get_param('drone_timeout', 5.0)

        # Initialize low-level drone driver located in tello.py
        # Tellopy library is used for simplicity
        self.d = Tello(self.drone_ip, self.drone_port, self.drone_timeout)

        self.connected = False
        self.in_flight = False
Beispiel #13
0
def main():
    vx = 0
    vy = 0
    vz = 0
    rot = 0
    vel = 30
    RED_MIN = np.array([0, 0, 90], np.uint8)
    RED_MAX = np.array([50, 255, 150], np.uint8)

    tello = Tello('', 9005)
    time.sleep(2)
    print(tello.get_battery())
    #tello.takeoff()

    while (True):
        frame = tello.get_image()
        #print("height = {}, width = {}".format(frame.shape[0], frame.shape[1]))
        #720x960
        center, area, img = get_object(frame, RED_MIN, RED_MAX)
        print(tello.get_battery())

        # Display the resulting frame
        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        cv2.imshow('frame', img)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release all
    tello.close()
    cv2.destroyAllWindows()
Beispiel #14
0
 def __init__(self):
     super(MainWindow, self).__init__()
     self.setWindowTitle("Tello Scan")
     self.tello_obj = Tello('', 8889)
     self.control_widget = TelloControllerWidget(self.tello_obj)
     self.path_widget = PathPlanningWidget()
     self.path_widget.signal_trajectory_point.connect(self.start_trajectory)
     self.set_layout()
     self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
Beispiel #15
0
    def __init__(self, tello: Tello):
        QtWidgets.QVBoxLayout.__init__(self)
        self.tello = tello
        self.video = Video(tello)
        self.sweep = Sweep(tello)

        # buttons
        self.addWidget(Button("Take Off", tello.takeoff))
        self.addWidget(Button("Land", tello.land))
        self.addWidget(Button("Stream Video", self.video.start))
        self.addWidget(Button("Perimeter sweep", self.sweep.start))
        self.addWidget(Button("Manual override", self.sweep.pause))
        self.addWidget(
            Button("Forward", lambda: tello.move_forward(self.distance)))
        self.addWidget(Button("Back", lambda: tello.move_back(self.distance)))
        self.addWidget(Button("Left", lambda: tello.move_left(self.distance)))
        self.addWidget(Button("Right",
                              lambda: tello.move_right(self.distance)))

        # style
        self.setSpacing(20)
def connectToDrone():
    global tello
    tello = Tello()
    tello.connect()
    tello.can_send_rc_control = False
    tello.yaw_velocity = 0
    time.sleep(2)
Beispiel #17
0
def main(mode='host'):
    global e
    global t
    if mode == 'host':
        e = RMS1('192.168.2.1')
        t = Tello('192.168.10.1')
    else:
        robot_ip = robotlistener()
        if robot_ip == '':
            print('no robot connected to network')
        else:
            e = RMS1(robot_ip)

    if e is not None and t is not None: 
        if e.connect() and t.connect(): 
            v = TelloRMVideoClient(e,t)
            v.start()
            while v.stopApp == False:
                time.sleep(2)
        else:
            print('no RM online or no Tello online')
    else:
        print('no RM online or no Tello online')
Beispiel #18
0
    if not intro():
        print("Exiting HelloTello...")
        sys.exit()

    # setup cascade and text for stream
    cas_lst = ci.cascade_finder()
    print("Now, choose what Tello will track.\nAvailable libraries:")
    for cascade in cas_lst:
        print(cascade)
    cascade_dir = "cascades/" + ci.usr_choice(cas_lst)
    font = cv2.FONT_HERSHEY_SIMPLEX
    bottom_left_corner = (10, 710)
    cascade = cv2.CascadeClassifier(cascade_dir)

    # initialize Tello and video stream
    t = Tello()
    time.sleep(1)
    initialize()

    # loop controls once drone is connected
    while running:

        # detect face and find coordinates if exists
        frame_read = t.get_frame_read()
        frame = cv2.cvtColor(frame_read.frame, cv2.COLOR_BGR2RGB)
        frameRet = frame_read.frame
        face_center_coords = facedetect(frameRet, cascade, MANUAL_MODE)

        # velocity printout
        if S == 30:
            text = "Speed: Low"
def telloControllerThread():
    tello = Tello('', 8889)
    north = 0
    west = 0
    south = 0
    east = 0
    landing = False
    while not receiving:
        pass
    try:
        tello.takeoff()
    except Exception:
        print("error occured taking off")
    while True:
        print("height")
        print(tello.get_height())
        if tello.get_height() < 1 and not landing:
            resp = tello.move_up(0.2)
            print("response for moving up")
            print(resp)
        if north < 1:
            print("moving forward")
            resp = tello.move_forward(0.2)
            print("response for moving forward")
            print(resp)
            north = north + 0.2
        elif west < 1:
            print("moving left")
            resp = tello.move_left(0.2)
            print("response for moving left")
            print(resp)
            west = west + 0.2
        elif south < 1:
            print("moving backward")
            resp = tello.move_backward(0.2)
            print("response for moving backward")
            print(resp)
            south = south + 0.2
        elif east < 1:
            print("moving right")
            resp = tello.move_right(0.2)
            print("response for moving east")
            print(resp)
            east = east + 0.2
        else:
            landing = True
            tello.land()
Beispiel #20
0
from tello import Tello
from datetime import datetime
import time

start_time = str(datetime.now())

commands = ["battery?", "delay 5", "height?"]

print("Tello booting up...")
tello = Tello()
time.sleep(2)
tello.send_command("command")
time.sleep(2)

for command in commands:
    if command != '' and command != '\n':
        command = command.rstrip()

        if command.find('delay') != -1:
            sec = float(command.partition('delay')[2])
            tello.hold(sec)
            pass
        else:
            tello.send_command(command)

# print all logs at end of program
# log = tello.get_log()
#
# for stat in log:
#     stat.print_stats()
Beispiel #21
0
        axis_data, button_data, hat_data = self.get_initial_datas()

        last_state = None

        while 1:
            axis_data, button_data, hat_data, last_state = self.iterate(
                axis_data, button_data, hat_data, last_state)

            if test_mode:
                break


if __name__ == '__main__':
    from scheduler import Scheduler

    t = Tello()

    s = Scheduler(period=DEBOUNCE_PERIOD)
    s.start()
    s.set_iteration_callback(t.send)

    c = Controller()
    c.set_state_change_callback(s.set_state)

    try:
        c.loop()
    except KeyboardInterrupt:
        pass

    t.shutdown()
Beispiel #22
0
from tello import Tello
import sys
from datetime import datetime
import time
import serial
commandsList = []
start_time = str(datetime.now())
ser = serial.Serial('COM10', 9600)
time.sleep(2)
#file_name = sys.argv[1]
#f = open(file_name, "r")
#commands = f.readlines()
tello = Tello()
tello.send_command("command")
tello.send_command("takeoff")
for x in range(0, 10):
    receivedCommand = ser.readline()
    string = receivedCommand.decode()
    string = string.rstrip()
    commandsList.append(string)
    print(string)
    tello.send_command(commandsList[-1])
    if string == "land":
        break
tello.send_command("land")
'''
for command in commands:
   if command != '' and command != '\n':
       command = command.rstrip()
       if command.find('delay') != -1:
           sec = float(command.partition('delay')[2])
class FaceTracker:
    """Constants"""
    FB_S = 15  # FWD/BWD Speed of the drone
    LR_S = 25  # LFT/RGHT Speed of the drone
    UD_S = 25
    CW_S = 25  # CW/CCW Speed of the drone
    FPS = 20  # Frames per second of the pygame window display

    def __init__(self, height, width):
        """Start loading"""
        namedWindow("drone")
        self.paper = imread("./resources/Tello.png")
        self.height = height
        self.width = width
        self.fv = FaceVector(height, width)
        self.tello = Tello()
        # Drone velocities between -100~100
        self.for_back_velocity = 20
        self.left_right_velocity = 20
        self.up_down_velocity = 20
        self.yaw_velocity = 20
        self.speed = 20
        self.send_rc_control = False
        self.should_stop = False
        self.mode = "keyboard"

    def run(self, show=False, debug=False):
        """Connecting block"""
        if not self.tello.connect():
            return
        print("Connected")
        if not self.tello.set_speed(self.speed):
            return
        print("Speeds set")

        """Stream start block"""
        if not self.tello.streamoff():
            return
        if not self.tello.streamon():
            return
        cap = self.tello.server.get_video_capture()
        print("Stream started")

        """Main loop"""
        while not self.should_stop:
            vec = None
            """Frame reading block"""
            if self.mode == "tracking" or show or debug:
                try:
                    r, frame = cap.read()
                except ValueError:
                    continue
                if r:
                    """Creating target directions vector"""
                    if self.mode == "tracking" or debug:
                        vec, frame = self.fv.direction_vector_3d_with_returning_image(frame)
                    """Frame plotting(requires from argument: bool:SHOW)"""
                    if show or debug:
                        frame = self.fv.text_addition(frame, vec)
                        imshow("drone", frame)
            if (not show) and (not debug):
                imshow("drone", self.paper)
            key = waitKey(5) & 0xff

            """Keyboard commands getting"""
            self.check_key(key)

            if self.mode == "tracking":
                """Driving block"""
                if vec is None:
                    vec = [0, 0, 0]
                print(vec)

                """Setting velocities depending from directions vector VEC"""
                if vec[0] != 0 or vec[1] != 0:
                    """Moving in 2D space at first"""
                    # set left/right velocity
                    self.left_right_velocity = -self.LR_S * vec[0]
                    # set up/down velocity
                    self.up_down_velocity = self.UD_S * vec[1]
                    # set forward/backward velocity
                else:
                    """Then moving forward/backward"""
                    self.for_back_velocity = self.FB_S * vec[2]
                    # set yaw clockwise velocity
                    self.yaw_velocity = self.CW_S * 0
                """Send move commands"""
                self.update()

            sleep(1 / self.FPS)
        self.tello.end()

    def update(self):
        """ Update routine. Send velocities to Tello."""
        if self.send_rc_control:
            self.tello.move_with_velocities(self.left_right_velocity, self.for_back_velocity,
                                            self.up_down_velocity, self.yaw_velocity)

    def check_key(self, key):
        """
        Moves Tello through the keyboard keys.
            - T / G : Takeoff / Land(Ground).
            - W / S : Up / Down.
            - A / D : CW / CCW.
            - I / K : Forward / Backward.
            - J / L : Left / Right.
            - SPACE : Start / Stop face tracking.
            - Q : Quit.
        """

        if key == ord('q'):  # stop
            self.should_stop = True
        elif key == ord('t'):  # takeoff
            print("Flying")
            self.tello.takeoff()
            self.send_rc_control = True
        elif key == ord('g'):  # land
            print("Landing")
            self.tello.land()
            self.send_rc_control = False
        elif key == ord('i'):  # forward
            self.tello.forward(50)
        elif key == ord('k'):  # backward
            self.tello.back(50)
        elif key == ord('j'):  # left
            self.tello.left(50)
        elif key == ord('l'):  # right
            self.tello.right(50)
        elif key == ord('w'):  # up
            self.tello.up(50)
        elif key == ord('s'):  # down
            self.tello.down(50)
        elif key == ord('a'):  # cw
            self.tello.rotate_cw(30)
        elif key == ord('d'):  # ccw
            self.tello.rotate_ccw(30)
        elif key == ord(' '):  # change mode
            self.change_mode()

    """Realise mode changing event"""
    def change_mode(self):
        if self.mode == "tracking":
            self.mode = "keyboard"
            self.tello.stop()
        elif self.mode == "keyboard":
            self.mode = "tracking"
Beispiel #24
0
class Interface:
    def __init__(self):
        self.tello = Tello()
        self.tello.sendCmd("streamon")  #스트리밍 모드
        pygame.init()
        pygame.display.set_caption("KNUE Drone Stream")
        self.screen = pygame.display.set_mode([960, 720])
        pygame.time.set_timer(USEREVENT + 1, 50)

        self.font = pygame.font.Font("freesansbold.ttf", 14)

    def make_text(self, font, text, color, bgcolor, top, left, position=0):
        surf = font.render(text, False, color, bgcolor)
        rect = surf.get_rect()
        if position:
            rect.center = (left, top)
        else:
            rect.topleft = (left, top)
        self.screen.blit(surf, rect)
        return rect

    def run(self):
        '''
        프레임을 업데이트 하고 이벤트를 처리한다.
        '''
        frame_read = self.tello.get_frame_read()
        time.sleep(1)
        exitEvent = False
        previousCounter = 0
        while not exitEvent:
            #이벤트 검사
            for event in pygame.event.get():
                if event.type == USEREVENT + 1:
                    pass
                elif event.type == KEYDOWN:
                    keys = pygame.key.get_pressed()
                    self.keyDown(keys)
                elif event.type == KEYUP:
                    self.keyUp(keys)
            if frame_read.stopped:
                frame_read.stop()
                break
            nowCounter = frame_read.frameCounter
            if nowCounter > previousCounter:
                self.screen.fill([0, 0, 0])  # 스크린 칠하기(검정)
                frame = cv2.cvtColor(frame_read.frame,
                                     cv2.COLOR_BGR2RGB)  # 읽어온프레임의 색 형식 바꾸기
                frame = np.rot90(frame)  # 90도 회전
                frame = np.flipud(frame)  # 위아래 전환
                face = pygame.surfarray.make_surface(frame)  # 화면 형식에 맞게 전환하고
                self.screen.blit(face, (0, 0))  # 탐색필요
                self.frame_rect = self.make_text(
                    self.font, "frameCount : " + str(nowCounter), blue, None,
                    20, 10)
                self.bat_rect = self.make_text(
                    self.font, "batteryState : " + str(self.tello.battery),
                    green, None, 40, 10)
                self.wifi_rect = self.make_text(
                    self.font, "wifiState : " + str(self.tello.wifi), green,
                    None, 60, 10)
                pygame.display.update()
                previousCounter = frame_read.frameCounter  # 화면갱신
            pygame.display.update()
            time.sleep(1 / FPS)

    def keyDown(self, key):
        if key[pygame.K_HOME]:
            self.tello.state = "takeoff"
        if key[pygame.K_END]:
            self.tello.sendCmd("land")
            self.tello.state = "land"
        if key[pygame.K_UP]:
            self.tello.speed_ud = 50
            print("key up")
        if key[pygame.K_DOWN]:
            self.tello.speed_ud = -50
            print("key down")
        if key[pygame.K_LEFT]:
            self.tello.speed_yaw = -50
            print("key left")
        if key[pygame.K_RIGHT]:
            self.tello.speed_yaw = 50
            print("key right")
        if key[pygame.K_w]:
            self.tello.speed_fb = 50
            print("key foward")
        if key[pygame.K_s]:
            self.tello.speed_fb = -50
            print("key back")
        if key[pygame.K_a]:
            self.tello.speed_lr = -50
        if key[pygame.K_d]:
            self.tello.speed_lr = 50

    def keyUp(self, key):
        if key[pygame.K_UP]:
            self.tello.speed_ud = 0
        if key[pygame.K_DOWN]:
            self.tello.speed_ud = 0
        if key[pygame.K_LEFT]:
            self.tello.speed_yaw = 0
        if key[pygame.K_RIGHT]:
            self.tello.speed_yaw = 0
        if key[pygame.K_w]:
            self.tello.speed_fb = 0
        if key[pygame.K_s]:
            self.tello.speed_fb = 0
        if key[pygame.K_a]:
            self.tello.speed_lr = 0
        if key[pygame.K_d]:
            self.tello.speed_lr = 0

    def speedNormalize(self, value, cmd, multiply):
        """
        이 함수는 키 눌림에 따라 하여 반환
        반영되는 속도는 최고 속도를 초과하지 않음
        """
        if abs(value + cmd * multiply) < self.tello.max_speed:
            value = value + cmd * multiply
        else:
            value = self.tello.max_speed * (abs(value) / value)
        return value
Beispiel #25
0
from tello import Tello
import time
import sys

wait_time = 5  # Wait time after each command
Lowest_battery = 5  # If the battery is equal to this or lower than the program will not run
local_ip = ['192.168.10.2', '192.168.10.3']
# local_ip = ['192.168.10.10', '192.168.10.19']  # Test ip's for debugging while the drone is charging
local_port = 8889
imperial = False  # MPH to KMH further info in tello.py
i = 0
while True:
    try:
        tello = Tello(local_ip[i], local_port, imperial, wait_time + 1)
    except OSError:
        i = i + 1
        if i == 2:
            break
        else:
            print(local_ip[i], "Is wrong ip")
try:
    Current_battery = tello.get_battery()
except NameError:
    sys.exit("No ip found")
if Current_battery >= Lowest_battery:
    print("Battery is fine")
    tello.takeoff()
    time.sleep(wait_time)  # delay for 1 seconds
    tello.flip('b')
    time.sleep(wait_time)  # delay for 1 seconds
    tello.rotate_cw(180)
Beispiel #26
0
from tello import Tello
from datetime import datetime
import time

start_time = str(datetime.now().strftime('%d%m%Y%H%M%S'))
print("Time: " + start_time)

file_name: str = './command.txt'

print(file_name)
f = open(file_name, "r")
commands = f.readlines()

tello = Tello()
for command in commands:
    if command != '' and command != '\n':
        command = command.rstrip()

        if command.find('delay') != -1:
            sec = float(command.partition('delay')[2])
            print('delay %s' % sec)
            time.sleep(sec)
            pass
        else:
            tello.send_command(command)

log = tello.get_log()

out = open('log/log_' + start_time + '.txt', 'x')
for stat in log:
    stat.print_stats()
class Drone(pg.sprite.Sprite):
    def __init__(self,
                 game,
                 x,
                 y,
                 left,
                 right,
                 up,
                 down,
                 fly,
                 land,
                 stand_img,
                 right_img,
                 left_img,
                 speedup=1):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.z = 0
        self.stand_img = stand_img
        self.right_img = right_img
        self.left_img = left_img
        self.game = game
        self.image = self.stand_img
        self.rect = self.image.get_rect()
        self.radius = self.rect.width / 2 * .85
        self.rect.center = (x, y)
        self.speedx = 0
        self.speedy = 0
        self.mode = "Manual"
        self.left = left
        self.right = right
        self.up = up
        self.down = down
        self.fly = fly
        self.land = land
        self.speedup = speedup
        self.current_checkpoint = 0
        self.flying = False
        self.current_angle = 0
        self.next_distance = 0
        self.next_angle = 0
        self.target_next_route = None
        self.route = DRONE_ROUTES[0]
        self.tello = Tello()
        self.tello.send("command")
        self.tello.send("streamon")
        self.current_command = "command"
        self.completed = 0

    def update(self):
        # toggle flying
        keys = pg.key.get_pressed()
        if keys[self.fly]:
            if not self.flying:
                self.flying = True
                self.tello.send("takeoff")
                self.current_command = "takeoff"
        elif keys[self.land]:
            if self.flying:
                self.flying = False
                self.tello.send("land")
                self.current_command = "land"
        # do not move if not flying
        if not self.flying:
            return
        # toggle mode
        if self.mode == "Automatic":
            self.update_automatic()
        else:
            self.update_manual()

    def update_manual(self):
        self.image = self.stand_img
        self.rect = self.rect
        self.radius = self.rect.width / 2 * .85
        self.speedx = 0
        self.speedy = 0
        # get current checkpoint route
        self.route = self.target_next_route
        if not self.route:
            return
        # check distance to x
        if self.route[0] < self.rect.x:
            # if at the left side, move left
            self.speedx -= DRONE_SPEED * self.speedup
            self.image = self.left_img
        elif self.route[0] > self.rect.x:
            # if at the right side, move right
            self.speedx += DRONE_SPEED * self.speedup
            self.image = self.right_img
        # check distance to y
        if self.route[1] < self.rect.y:
            # if at the top side, move up
            self.speedy -= DRONE_SPEED * self.speedup
        elif self.route[1] > self.rect.y:
            # if at the bottom side, move down
            self.speedy += DRONE_SPEED * self.speedup
        # lower speed a bit for diagonal movement
        if self.speedx != 0 and self.speedy != 0:
            self.speedx *= 0.7071
            self.speedy *= 0.7071
        # move drone
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        # position correction
        if self.speedx < 0 and self.rect.x < self.route[0]:
            self.rect.x = self.route[0]
        if self.speedx > 0 and self.rect.x > self.route[0]:
            self.rect.x = self.route[0]
        if self.speedy < 0 and self.rect.y < self.route[1]:
            self.rect.y = self.route[1]
        if self.speedy > 0 and self.rect.y > self.route[1]:
            self.rect.y = self.route[1]
        # reset route if reached
        if self.rect.x == self.route[0] and self.rect.y == self.route[1]:
            self.route = None
            self.target_next_route = None
        # position correction for boundary
        if self.rect.left < 50:
            self.rect.left = 50
        if self.rect.right > 380:
            self.rect.right = 380
        if self.rect.top < 50:
            self.rect.top = 50
        if self.rect.bottom > 350:
            self.rect.bottom = 350

    def update_automatic(self):
        self.image = self.stand_img
        self.rect = self.rect
        self.radius = self.rect.width / 2 * .85
        self.speedx = 0
        self.speedy = 0
        # get current checkpoint route
        self.route = DRONE_ROUTES[self.current_checkpoint]
        # check distance to x
        if self.route[0] < self.rect.x:
            # if at the left side, move left
            self.speedx -= DRONE_SPEED * self.speedup
            self.image = self.left_img
        elif self.route[0] > self.rect.x:
            # if at the right side, move right
            self.speedx += DRONE_SPEED * self.speedup
            self.image = self.right_img
        # check distance to y
        if self.route[1] < self.rect.y:
            # if at the top side, move up
            self.speedy -= DRONE_SPEED * self.speedup
        elif self.route[1] > self.rect.y:
            # if at the bottom side, move down
            self.speedy += DRONE_SPEED * self.speedup
        # lower speed a bit for diagonal movement
        if self.speedx != 0 and self.speedy != 0:
            self.speedx *= 0.7071
            self.speedy *= 0.7071
        # move drone
        self.rect.x += self.speedx
        self.rect.y += self.speedy
        # position correction
        if self.speedx < 0 and self.rect.x < self.route[0]:
            self.rect.x = self.route[0]
        if self.speedx > 0 and self.rect.x > self.route[0]:
            self.rect.x = self.route[0]
        if self.speedy < 0 and self.rect.y < self.route[1]:
            self.rect.y = self.route[1]
        if self.speedy > 0 and self.rect.y > self.route[1]:
            self.rect.y = self.route[1]
        # update checkpoint and command if reached
        if self.rect.x == self.route[0] and self.rect.y == self.route[1]:
            self.current_checkpoint += 1
            # round robin
            if self.current_checkpoint >= len(DRONE_ROUTES):
                self.current_checkpoint = 0
                self.completed += 1
            self.route = DRONE_ROUTES[self.current_checkpoint]
            # update command
            self.current_command, self.current_angle = calculate_command(
                self.current_angle, self.rect.x, self.rect.y, self.route[0],
                self.route[1])
            self.tello.send(self.current_command)
Beispiel #28
0
from keyCommand import KeyCommand
from pynput import keyboard
from datetime import datetime


def on_keypress(key):
    command = KeyCommand.get_command(key)

    if command != False or "":
        print("Key: ")
        tello.send_command(command)


start_time = str(datetime.now().strftime('%d%m%Y%H%M%S'))
print("Time: " + start_time)

tello = Tello()
tello.send_command('command')

with keyboard.Listener(on_press=on_keypress) as listener:
    listener.join()

listener.start()

log = tello.get_log()

out = open('log/log_' + start_time + '.txt', 'x')
for stat in log:
    stat.print_stats()
    out_str = stat.return_stats()
    out.write(out_str)
from tello import Tello
import sys
from datetime import datetime
import time
import TelloPro

tello = Tello()

command_lst = []
command_lst.append(TelloPro.get_instance('takeoff', -1))

command_lst.append(TelloPro.get_instance('up', 50))
command_lst.append(TelloPro.get_instance('down', 50))

for i in range(4):
    command_lst.append(TelloPro.get_instance('flip', i))

command_lst.append(TelloPro.get_instance('right', 50))
command_lst.append(TelloPro.get_instance('left', 50))
command_lst.append(TelloPro.get_instance('forward', 50))
command_lst.append(TelloPro.get_instance('back', 50))
command_lst.append(TelloPro.get_instance('cw', 50))
command_lst.append(TelloPro.get_instance('ccw', 50))

command_lst.append(TelloPro.get_instance('land', -1))

for command in command_lst:
    tello.send_command_instance(command)
Beispiel #30
0
# docs https://www.ryzerobotics.com/tello/downloads

# something of note: if no commands are sent for 15 seconds the drone will land.
# we will need some sort of "keep-alive" ping. something like get battery level
# would be good since we'll want to keep tabs on that anyway

from tello import Tello

tello = Tello()

print('\r\n\r\nTello Python3 Demo.\r\n')

print(
    'Tello: command takeoff land flip forward back left right \r\n       up down cw ccw speed speed?\r\n'
)

print('end -- quit demo.\r\n')

# start SDK mode
tello.start_up()


def move_square():
    tello.move("forward", 20)
    # tello.go_forward(20)
    # tello.go_right(20)
    # tello.go_backward(20)


while True: