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()
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 connectToDrone(): global tello tello = Tello() tello.connect() tello.can_send_rc_control = False tello.yaw_velocity = 0 time.sleep(2)
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 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'')
def start(): qt = QtWidgets.QApplication() app = App(Tello()) app.setMinimumWidth(300) app.show() Thread(target=app.connect_tello).start() qt.exec_()
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()
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): 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)
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")
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)
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
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 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()
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 __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
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')
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)
if len(sys.argv) != 3: print("Please run : python main.py ip.txt cmd.txt") sys.exit(0) #start_time = str(datetime.now()) #read command file file_name1 = sys.argv[1] f_ip = open(file_name1, "r") ip_list = f_ip.readlines() file_name2 = sys.argv[2] f_cmd = open(file_name2, "r") commands = f_cmd.readlines() tello = Tello(ip_list) 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) ''' logging log = tello.get_log() out = open('log/' + start_time + '.txt', 'w') for stat in log:
# For certificate based connection myMQTTClient = AWSIoTMQTTClient('device001') # 適当な値でOK myMQTTClient.configureEndpoint( 'a1qhwdmvn9jp9z-ats.iot.ap-northeast-1.amazonaws.com', 8883) # 管理画面で確認 myMQTTClient.configureCredentials( 'rootCA.pem', 'fef0460c44-private.pem.key', 'fef0460c44-certificate.pem.crt') #各種証明書(公開してはならない) myMQTTClient.configureOfflinePublishQueueing( -1) # Infinite offline Publish queueing myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec myMQTTClient.connect() tello = Tello() # Telloインスタンスを作成 tello.send_command('command') # SDKモードを開始 def customCallback(client, userdata, message): payload = message.payload print('Received a new message: ') print(payload) print('from topic: ') print(message.topic) print('--------------\n\n') # command = payload[0] dic = ast.literal_eval(payload) tello.send_command(dic['message'])
from tello import Tello import time local_ip = '192.168.10.3' local_port = 8889 imperial = False drone = Tello(local_ip, local_port, imperial) drone.takeoff() time.sleep(7) drone.set_speed(2) time.sleep(1) drone.move_down(3) time.sleep(5) drone.move_forward(10) time.sleep(10) drone.rotate_cw(180) time.sleep(5) drone.move_forward(10) time.sleep(10) drone.land() print("Hokey Pokey complete! :)") print('Flight time: %s' % drone.get_flight_time())
#-*- coding: utf-8 -*- ''' 2019 4.21 작성자 한국교원대학교 컴퓨터교육과 전형기 map 기능 테스트 ''' from tello import Tello #tello 모듈로 부터 Tello를 불러온다. import sys from datetime import datetime import time # 시간 관련 모듈 tello = Tello() # tello 객체를 생성한다. tello모듈에 객체의 명세가 기록되어 있다. ''' Tello class 에서 제공하는 함수 sendCmd(command) : 명령 보내기 get_log() : 로그 받기 ''' #명령의 시작과 이륙 tello.sendCmd("command") tello.sendCmd("takeoff") time.sleep(1) #맵인식켜기 : mon tello.sendCmd("mon") #맵 인식방향 설정 : tello.sendCmd("mdirection 0") time.sleep(0.5) #맵 기반 좌표 설정 : go x y z v m # x y z s m은 각각 x좌표 y좌표 z좌표 속도 맵 번호다.
Executes a series of Tello commands from a flight script """ from tello import Tello import sys from datetime import datetime import time start_time = str(datetime.now()) file_name = sys.argv[1] with open(file_name, "r") as f: commands = f.readlines() with Tello() as tello: for command in commands: command = command.strip() if command.startswith('#'): continue if command: if command.find('delay') != -1: sec = float(command.partition('delay')[2]) print 'delay %s ...' % sec time.sleep(sec) else: tello.send_command(command) print("Completed.") # log = tello.get_log()
from tello import Tello from tkinter import * root=Tk() x = 1 local_ip = '192.168.10.2' local_port = 8889 imperial = False tello = Tello(local_ip, local_port, imperial) tello.takeoff() tello.set_speed(5) def stop(event): tello.land() def left(event): tello.move_left(x) def right(event): tello.move_right(x) def forward(event): tello.move_forward(x) def backward(event): tello.move_backward(x) def up(event): tello.rotate_cw(30) def down(event): tello.rotate_ccw(30) frame=Frame(root,width=300,height=250) frame.bind('<Down>',backward) frame.bind('<Left>',left) frame.bind('<Right>',right) frame.bind('<Up>',forward) frame.bind('<1>',up)
from pynput import keyboard from tello import Tello import time import numpy as np import cv2 vx = 0 vy = 0 vz = 0 rot = 0 vel = 30 tello = Tello('', 9005) def on_press(key): global vx, vy, vz, rot, vel, tello #print(key) try: if key.char == 'w': vz = vel elif key.char == 's': vz = -vel elif key.char == 'a': rot = -vel elif key.char == 'd': rot = vel elif key.char == 'p': print("p") except AttributeError: if key == keyboard.Key.up: vx = vel
def __init__(self, local_ip, local_port): self.drone = Tello(local_ip, local_port)
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"
from tello import Tello import re import math import threading IMAGE_WIDTH=960 IMAGE_HEIGHT=720 rospy.init_node("listener", anonymous=True) image_pubulish=rospy.Publisher('/camera/image_raw',Image,queue_size=1) IMU_pubulish=rospy.Publisher('/Imu/imu_raw',Imu,queue_size=20) drone=Tello() def eularToQuaternion( yaw, roll, pitch): X = yaw/180*math.pi Y = roll/180*math.pi Z = pitch/180*math.pi x = math.cos(Y/2)*math.sin(X/2)*math.cos(Z/2)+math.sin(Y/2)*math.cos(X/2)*math.sin(Z/2) y = math.sin(Y/2)*math.cos(X/2)*math.cos(Z/2)-math.cos(Y/2)*math.sin(X/2)*math.sin(Z/2) z = math.cos(Y/2)*math.cos(X/2)*math.sin(Z/2)-math.sin(Y/2)*math.sin(X/2)*math.cos(Z/2) w = math.cos(Y/2)*math.cos(X/2)*math.cos(Z/2)+math.sin(Y/2)*math.sin(X/2)*math.sin(Z/2) quat = [x,y,z,w] return quat def publish_image(): if drone.is_new_frame_ready(): frame = drone.get_last_frame() #gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
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)
# we found compatibility problem between Tkinter,PIL and Macos,and it will # sometimes result the very long preriod of the "ImageTk.PhotoImage" function, # so for Macos,we start a new thread to execute the _updateGUIImage function. if system =="Windows" or system =="Linux": tello._updateGUIImage(image) else: thread_tmp = threading.Thread(target=tello._updateGUIImage,args=(image,)) thread_tmp.start() time.sleep(0.03) except RuntimeError, e: print("[INFO] caught a RuntimeError") if __name__=="__main__": #tello = Tello('192.168.10.2', 8889) tello = Tello('192.168.10.2', 80) tello.send_command("command") thread = threading.Thread(target=videoLoop, args=(tello)) thread.start() input_cmd = "" while True: print("a-起飛(takeoff)") print("b-降落(land)") print("c-向上飛行50公分(up 50)") print("d-向下飛行50公分(down 50)") print("e-向左飛行50公分(left 50)") print("f-向右飛行50公分(right 50)") print("g-向前飛行50公分(forward 50)") print("h-向後飛行50公分(back 50)")