|
| 1 | +import socket |
| 2 | +import threading |
| 3 | +import time |
| 4 | +from stats import Stats |
| 5 | + |
| 6 | +class Tello: |
| 7 | + def __init__(self): |
| 8 | + self.local_ip = '' |
| 9 | + self.local_port = 8889 |
| 10 | + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # socket for sending cmd |
| 11 | + self.socket.bind((self.local_ip, self.local_port)) |
| 12 | + |
| 13 | + # thread for receiving cmd ack |
| 14 | + self.receive_thread = threading.Thread(target=self._receive_thread) |
| 15 | + self.receive_thread.daemon = True |
| 16 | + self.receive_thread.start() |
| 17 | + |
| 18 | + self.tello_ip = '192.168.10.1' |
| 19 | + self.tello_port = 8889 |
| 20 | + self.tello_adderss = (self.tello_ip, self.tello_port) |
| 21 | + self.log = [] |
| 22 | + |
| 23 | + self.MAX_TIME_OUT = 15.0 |
| 24 | + |
| 25 | + def send_command(self, command): |
| 26 | + """ |
| 27 | + Send a command to the ip address. Will be blocked until |
| 28 | + the last command receives an 'OK'. |
| 29 | + If the command fails (either b/c time out or error), |
| 30 | + will try to resend the command |
| 31 | + :param command: (str) the command to send |
| 32 | + :param ip: (str) the ip of Tello |
| 33 | + :return: The latest command response |
| 34 | + """ |
| 35 | + self.log.append(Stats(command, len(self.log))) |
| 36 | + |
| 37 | + self.socket.sendto(command.encode('utf-8'), self.tello_adderss) |
| 38 | + print 'sending command: %s to %s' % (command, self.tello_ip) |
| 39 | + |
| 40 | + start = time.time() |
| 41 | + while not self.log[-1].got_response(): |
| 42 | + now = time.time() |
| 43 | + diff = now - start |
| 44 | + if diff > self.MAX_TIME_OUT: |
| 45 | + print 'Max timeout exceeded... command %s' % command |
| 46 | + # TODO: is timeout considered failure or next command still get executed |
| 47 | + # now, next one got executed |
| 48 | + return |
| 49 | + print 'Done!!! sent command: %s to %s' % (command, self.tello_ip) |
| 50 | + |
| 51 | + def _receive_thread(self): |
| 52 | + """Listen to responses from the Tello. |
| 53 | +
|
| 54 | + Runs as a thread, sets self.response to whatever the Tello last returned. |
| 55 | +
|
| 56 | + """ |
| 57 | + while True: |
| 58 | + try: |
| 59 | + self.response, ip = self.socket.recvfrom(1024) |
| 60 | + print('from %s: %s' % (ip, self.response)) |
| 61 | + |
| 62 | + self.log[-1].add_response(self.response) |
| 63 | + except socket.error, exc: |
| 64 | + print "Caught exception socket.error : %s" % exc |
| 65 | + |
| 66 | + def on_close(self): |
| 67 | + pass |
| 68 | + # for ip in self.tello_ip_list: |
| 69 | + # self.socket.sendto('land'.encode('utf-8'), (ip, 8889)) |
| 70 | + # self.socket.close() |
| 71 | + |
| 72 | + def get_log(self): |
| 73 | + return self.log |
| 74 | + |
0 commit comments