diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 51c659ec4..85a3636f2 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -752,7 +752,7 @@ def _send(self): overrides = [0] * 8 for k, v in self.iteritems(): overrides[int(k) - 1] = v - self._vehicle._master.mav.rc_channels_override_send(0, 0, *overrides) + self._vehicle._master.send_rc_overrides(overrides) class Channels(dict): @@ -975,6 +975,8 @@ def global_relative_frame(self): return LocationGlobalRelative(self._lat, self._lon, self._relative_alt) +from dronekit.mavlink import MAVSystem + class Vehicle(HasObservers): """ The main vehicle API. @@ -1013,11 +1015,12 @@ class Vehicle(HasObservers): to the project! """ - def __init__(self, handler): + def __init__(self, xhandler, target_system=None, target_component=1): super(Vehicle, self).__init__() - self._handler = handler - self._master = handler.master + self._handler = MAVSystem(xhandler, target_system=target_system, target_component=target_component) + self._master = self._handler + self._close_mav_on_disconnect = True # Cache all updated attributes for wait_ready. # By default, we presume all "commands" are loaded. @@ -1033,7 +1036,7 @@ def listener(_, name, value): # Attaches message listeners. self._message_listeners = dict() - @handler.forward_message + @self._handler.forward_message def listener(_, msg): self.notify_message_listeners(msg.get_type(), msg) @@ -1255,8 +1258,7 @@ def listener(self, name, msg): def listener(self, name, msg): if self._wp_uploaded != None: wp = self._wploader.wp(msg.seq) - handler.fix_targets(wp) - self._master.mav.send(wp) + self._master.send_wp(wp) self._wp_uploaded[msg.seq] = True # TODO: Waypoint loop listeners @@ -1275,7 +1277,7 @@ def listener(self, name, msg): self._params_duration = start_duration self._parameters = Parameters(self) - @handler.forward_loop + @xhandler.forward_loop def listener(_): # Check the time duration for last "new" params exceeds watchdog. if not self._params_start: @@ -1322,51 +1324,34 @@ def listener(self, name, msg): import traceback traceback.print_exc() - # Heartbeats. - - self._heartbeat_started = False - self._heartbeat_lastsent = 0 - self._heartbeat_lastreceived = 0 - self._heartbeat_timeout = False - self._heartbeat_warning = 5 self._heartbeat_error = 30 - self._heartbeat_system = None + self._heartbeat_lastreceived = 0 + self._heartbeat_timeout = False - @handler.forward_loop + @xhandler.forward_loop def listener(_): - # Send 1 heartbeat per second - if monotonic.monotonic() - self._heartbeat_lastsent > 1: - self._master.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, - mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) - self._heartbeat_lastsent = monotonic.monotonic() - - # Timeouts. - if self._heartbeat_started: - if self._heartbeat_error and self._heartbeat_error > 0 and monotonic.monotonic( - ) - self._heartbeat_lastreceived > self._heartbeat_error: - raise APIException('No heartbeat in %s seconds, aborting.' % - self._heartbeat_error) - elif monotonic.monotonic() - self._heartbeat_lastreceived > self._heartbeat_warning: - if self._heartbeat_timeout == False: - errprinter('>>> Link timeout, no heartbeat in last %s seconds' % - self._heartbeat_warning) - self._heartbeat_timeout = True + delta = monotonic.monotonic() - self._heartbeat_lastreceived + if self._heartbeat_error and self._heartbeat_error > 0 and delta > self._heartbeat_error: + raise APIException('No heartbeat in %s seconds, aborting.' % + self._heartbeat_error) + elif delta > self._heartbeat_warning: + if self._heartbeat_timeout == False: + errprinter('>>> Link timeout, no heartbeat in last %s seconds' % + self._heartbeat_warning) + self._heartbeat_timeout = True @self.on_message(['HEARTBEAT']) def listener(self, name, msg): - # ignore groundstations - if msg.type == mavutil.mavlink.MAV_TYPE_GCS: - return - self._heartbeat_system = msg.get_srcSystem() self._heartbeat_lastreceived = monotonic.monotonic() +# print("heartbeat from (%d)" % (msg.get_srcSystem())) if self._heartbeat_timeout: errprinter('>>> ...link restored.') - self._heartbeat_timeout = False + self._heartbeat_timeout = False self._last_heartbeat = None - @handler.forward_loop + @xhandler.forward_loop def listener(_): if self._heartbeat_lastreceived: self._last_heartbeat = monotonic.monotonic() - self._heartbeat_lastreceived @@ -2045,14 +2030,9 @@ def simple_goto(self, location, airspeed=None, groundspeed=None): :param groundspeed: Target groundspeed in m/s (optional). ''' if isinstance(location, LocationGlobalRelative): - frame = mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT alt = location.alt elif isinstance(location, LocationGlobal): - # This should be the proper code: - # frame = mavutil.mavlink.MAV_FRAME_GLOBAL - # However, APM discards information about the relative frame - # and treats any alt value as relative. So we compensate here. - frame = mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT + # currently the vehicle's goto only handles relative positions if not self.home_location: self.commands.download() self.commands.wait_ready() @@ -2060,10 +2040,7 @@ def simple_goto(self, location, airspeed=None, groundspeed=None): else: raise APIException('Expecting location to be LocationGlobal or LocationGlobalRelative.') - self._master.mav.mission_item_send(0, 0, 0, frame, - mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, 0, 0, - 0, 0, 0, location.lat, location.lon, - alt) + self._handler.simple_goto(location.lat, location.lon, alt, relative=True) if airspeed != None: self.airspeed = airspeed @@ -2139,15 +2116,13 @@ def initialize(self, rate=4, heartbeat_timeout=30): # Poll for first heartbeat. # If heartbeat times out, this will interrupt. - while self._handler._alive: + while self._handler.alive(): time.sleep(.1) if self._heartbeat_lastreceived != start: break - if not self._handler._alive: - raise APIException('Timeout in initializing connection.') - # Register target_system now. - self._handler.target_system = self._heartbeat_system + if not self._handler.alive(): + raise APIException('Timeout in initializing connection.') # Wait until board has booted. while True: @@ -2157,8 +2132,7 @@ def initialize(self, rate=4, heartbeat_timeout=30): # Initialize data stream. if rate != None: - self._master.mav.request_data_stream_send(0, 0, mavutil.mavlink.MAV_DATA_STREAM_ALL, - rate, 1) + self._master.request_data_stream(rate) self.add_message_listener('HEARTBEAT', self.send_capabilties_request) @@ -2237,6 +2211,18 @@ def wait_ready(self, *types, **kwargs): return True + def waypoint_count_send(self,count): + self._master.waypoint_count_send(count) + + def set_close_mav_on_disconnect(self, value): + self._close_mav_on_disconnect = value + + def close_mav_on_disconnect(self): + return self._close_mav_on_disconnect + + def disconnect(self): + if self.close_mav_on_disconnect(): + self._handler.conn.close() class Gimbal(object): """ @@ -2747,7 +2733,7 @@ def upload(self): self._vehicle._master.waypoint_clear_all_send() if self._vehicle._wploader.count() > 0: self._vehicle._wp_uploaded = [False] * self._vehicle._wploader.count() - self._vehicle._master.waypoint_count_send(self._vehicle._wploader.count()) + self._vehicle.waypoint_count_send(self._vehicle._wploader.count()) while False in self._vehicle._wp_uploaded: time.sleep(0.1) self._vehicle._wp_uploaded = None @@ -2812,7 +2798,10 @@ def connect(ip, baud=115200, heartbeat_timeout=30, source_system=255, - use_native=False): + target_system=1, + target_component=1, + use_native=False, + handler=None): """ Returns a :py:class:`Vehicle` object connected to the address specified by string parameter ``ip``. Connection string parameters (``ip``) for different targets are listed in the :ref:`getting started guide `. @@ -2845,9 +2834,10 @@ def connect(ip, This can be any sub-class of ``Vehicle`` (and defaults to ``Vehicle``). :param int rate: Data stream refresh rate. The default is 4Hz (4 updates per second). :param int baud: The baud rate for the connection. The default is 115200. - :param int heartbeat_timeout: Connection timeout value in seconds (default is 30s). - If a heartbeat is not detected within this time an exception will be raised. - :param int source_system: The MAVLink ID of the :py:class:`Vehicle` object returned by this method (by default 255). + :param int heartbeat_timeout: Connection timeout value in seconds (default is 30s). + If a heartbeat is not detected within this time an exception will be raised. + :param int source_system: The MAVLink ID of the :py:class:`Vehicle` object returned by this method (by default 255). When commands are sent to the vehicle, this is used as the source ID. + :param int target_system: The MAVLink ID of the vehicle this Vehicle object represents. When commands are sent to the vehicle, this SHOULD be used as the target id. Incoming messages from the connection are filtered according to this value, with "0" indicating no filtering and None indicating total filtering. Broadcast messages (those with a source system of 0) are only filtered if target_id is None :param bool use_native: Use precompiled MAVLink parser. .. note:: @@ -2867,8 +2857,14 @@ def connect(ip, if not vehicle_class: vehicle_class = Vehicle - handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native) - vehicle = vehicle_class(handler) + if isinstance(ip,mavlink.MAVConnection): + handler = ip + else: + handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native) + + vehicle = vehicle_class(handler, target_system=target_system, target_component=target_component) + + vehicle.set_close_mav_on_disconnect(not isinstance(ip,mavlink.MAVConnection)) if status_printer: diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index 7cff501df..bb1b419f2 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -13,6 +13,7 @@ from pymavlink import mavutil, mavwp from queue import Queue, Empty from threading import Thread +import traceback import types if platform.system() == 'Windows': @@ -37,6 +38,96 @@ def read(self): errprinter('writer should not have had a read request') os._exit(43) +class MAVSystem(mavutil.mavsource): + def __init__(self, conn, target_system=None, target_component=1): + + if target_system is None: + # replace this with some sort of search function + target_system = 1 + + super(MAVSystem,self).__init__(conn.master, target_system, target_component) + + self.conn = conn + self._message_listeners = [] + + # at the moment we only use mavsource for sending messages to + # the correct place. Listening is currently done directly on + # the upstream connection object: + @conn.forward_message + def listener(_, msg): + if msg.get_srcSystem() == self.system_id: + self.notify_message_listeners(msg) + + def remove_message_listener(self, name, fn): + """ + Removes a message listener (that was previously added using :py:func:`add_message_listener`). + + See :ref:`mavlink_messages` for more information. + + :param String name: The name of the message for which the listener is to be removed (or '*' to remove an 'all messages' observer). + :param fn: The listener callback function to remove. + + """ + name = str(name) + if name in self._message_listeners: + if fn in self._message_listeners[name]: + self._message_listeners[name].remove(fn) + if len(self._message_listeners[name]) == 0: + del self._message_listeners[name] + + def notify_message_listeners(self, msg): + for fn in self._message_listeners: + try: + fn(self, msg) + except Exception as e: + errprinter('>>> Exception in message handler for %s' % + msg.get_type()) + errprinter('>>> ' + str(e)) + + def start(self): + self.conn.start() + + def alive(self): + # should we check we've received a hearbeat from the system here? + return self.conn._alive + + def request_data_stream(self, rate): + self.mav.request_data_stream_send(self.target_system, + self.target_component, + mavutil.mavlink.MAV_DATA_STREAM_ALL, + rate, 1) + def forward_message(self, fn): + """ + Decorator for message inputs. + """ + self._message_listeners.append(fn) + + + # APM discards information about the relative frame and treats any + # alt value as relative. So we require relative positions for the + # time being + def simple_goto(self, lat, lon, alt, relative=False): + if relative != True: + raise APIException('relative positions required') + + self.mav.mission_item_send(self.target_system, + self.target_component, + 0, + mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, + mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, 0, 0, + 0, 0, 0, lat, lon, + alt) + + def fix_targets(self, message): + """Set correct target IDs for our vehicle""" + if hasattr(message, 'target_system'): + message.target_system = self.target_system + if hasattr(message, 'target_component'): + message.target_component = self.target_component + + def pipe(self, out): + '''Pipe *all* messages coming across vehicle connection into out. This is deprecated in favour of calling pipe() on the connection itself''' + return self.conn.pipe(out) class mavudpin_multi(mavutil.mavfile): '''a UDP mavlink socket''' @@ -121,7 +212,8 @@ def stop_threads(self): self.mavlink_thread_out.join() self.mavlink_thread_out = None - def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_native=False): + def __init__(self, ip, baud=115200, source_system=255, use_native=False): + self.master = mavutil.mavlink_connection(ip, baud=baud, source_system=source_system) if ip.startswith("udpin:"): self.master = mavudpin_multi(ip[6:], input=True, baud=baud, source_system=source_system) else: @@ -135,18 +227,6 @@ def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_nati srcSystem=self.master.source_system, use_native=use_native) - # Monkey-patch MAVLink object for fix_targets. - sendfn = self.master.mav.send - - def newsendfn(mavmsg, *args, **kwargs): - self.fix_targets(mavmsg) - return sendfn(mavmsg, *args, **kwargs) - - self.master.mav.send = newsendfn - - # Targets - self.target_system = target_system - # Listeners. self.loop_listeners = [] self.message_listeners = [] @@ -164,6 +244,10 @@ def onexit(): atexit.register(onexit) + # Heartbeats. + self._heartbeat_lastsent = 0 + + def mavlink_thread_out(): # Huge try catch in case we see http://bugs.python.org/issue1856 try: @@ -208,11 +292,15 @@ def mavlink_thread_in(): # Loop listeners. for fn in self.loop_listeners: + self.send_heartbeat() fn(self) while self._accept_input: + if not self._alive: + break try: msg = self.master.recv_msg() +# print("msg=%s" % (str(msg))) except socket.error as error: # If connection reset (closed), stop polling. if error.errno == ECONNABORTED: @@ -222,7 +310,7 @@ def mavlink_thread_in(): # TODO this should be more rigorous. How to avoid # invalid MAVLink prefix '73' # invalid MAVLink prefix '13' - # errprinter('mav recv error:', e) + errprinter('mav recv error:', e) msg = None if not msg: break @@ -237,7 +325,7 @@ def mavlink_thread_in(): errprinter('>>> ' + str(e)) except APIException as e: - errprinter('>>> ' + str(e)) + errprinter('>>> APIException (' + str(e.message) + ")") self._alive = False self.master.close() self._death_error = e @@ -251,6 +339,8 @@ def mavlink_thread_in(): self._alive = False self.master.close() self._death_error = e + errprinter('>>> Exception (' + str(e.message) + ")") + traceback.print_exc() t = Thread(target=mavlink_thread_in) t.daemon = True @@ -260,6 +350,14 @@ def mavlink_thread_in(): t.daemon = True self.mavlink_thread_out = t + def send_heartbeat(self): + # Send 1 heartbeat per second + if time.time() - self._heartbeat_lastsent > 1: +# print ("sending heartbeat %s" % str(self)) + self.master.mav.heartbeat_send(mavutil.mavlink.MAV_TYPE_GCS, + mavutil.mavlink.MAV_AUTOPILOT_INVALID, 0, 0, 0) + self._heartbeat_lastsent = time.time() + def reset(self): self.out_queue = Queue() if hasattr(self.master, 'reset'): @@ -271,11 +369,6 @@ def reset(self): pass self.master = mavutil.mavlink_connection(self.master.address) - def fix_targets(self, message): - """Set correct target IDs for our vehicle""" - if hasattr(message, 'target_system'): - message.target_system = self.target_system - def forward_loop(self, fn): """ Decorator for event loop. @@ -302,8 +395,8 @@ def close(self): self.stop_threads() self.master.close() + # pipe all messages on this connection into target def pipe(self, target): - target.target_system = self.target_system # vehicle -> self -> target @self.forward_message @@ -321,7 +414,6 @@ def callback(_, msg): @target.forward_message def callback(_, msg): msg = copy.copy(msg) - target.fix_targets(msg) try: self.out_queue.put(msg.pack(self.master.mav)) except: diff --git a/dronekit/test/sitl/test_mavlink.py b/dronekit/test/sitl/test_mavlink.py index 972c8ac8b..adfb55152 100644 --- a/dronekit/test/sitl/test_mavlink.py +++ b/dronekit/test/sitl/test_mavlink.py @@ -24,5 +24,6 @@ def callback(*args): i = 20 while not result['success'] and i > 0: time.sleep(1) + i -= 1 assert result['success'] diff --git a/examples/avoidance/README.md b/examples/avoidance/README.md new file mode 100644 index 000000000..aa683732f --- /dev/null +++ b/examples/avoidance/README.md @@ -0,0 +1,78 @@ +These are some (hopefully short-lived) intructions on how to get this avoidance example running in dronekit-python. These instructions assume you are running under Linux, but with minimal modification should run on other operating systems. + +Please note that these instructions will significantly change your environment. Unless you are quite familiar with how your build environment is put together you may wish to do this in a separate stand-alone environment. + +1. Run peterbarker's _source-system-filtering branch_ of dronekit-python + + Given that this README file exists within that branch, this should not be too much of a problem. + + The branch can be cloned from https://github.com/peterbarker/dronekit-python + ``` + DRONEKIT_TOP=$HOME # e.g. + cd $DRONEKIT_TOP/dronekit-python + git remote add peterbarker https://github.com/peterbarker/dronekit-python + git fetch peterbarker + git checkout peterbarker/source-system-filtering + python setup.py build install --user --force + ``` + +2. Run a version of pymavlink which contains source system filtering: + + ``` + ARDUPILOT_HOME=$HOME/ardupilot # e.g. + cd $ARDUPILOT_HOME/modules/mavlink/pymavlink + git remote add peterbarker https://github.com/peterbarker/pymavlink + git fetch peterbarker + git checkout peterbarker/mavsource + python setup.py build install --user --force + ``` + + Note that in the above shell code we are re-using a pymavlink + repository present in a buildable ArduPilot repository. You can + instead clone the pymavlink tree directly. + +3. Run peterbarker's avoidance MAVProxy branch + + ``` + MAVPROXY_HOME=$HOME/ardupilot # e.g. + cd $MAVPROXY_HOME + git remote add peterbarker https://github.com/peterbarker/MAVProxy + git fetch peterbarker + git checkout avoidance + python setup.py build install --user --force + ``` + +4. Connect a GCS to port 3456 + + This varies by GCS. With *MAVProxy* you might run this: + ``` + mavproxy.py --master udpin:localhost:3456 + module load avoidance + ``` + + With *GQGroundControl* you might try this: + ``` + - run qgroundcontrol + - Hamburger -> Comm Links + - Add (near the bottom of the screen) + - Type: UDP + - Listening port 3456 + ``` + +5. Run the avoidance sample program: + ``` + DRONEKIT_TOP=$HOME # e.g. + ARDUPILOT_HOME=$HOME/ardupilot + export PYTHONPATH=$DRONEKIT_TOP/dronekit-python + cd $DRONEKIT_TOP/dronekit-python/examples/avoidance + # this assumes you are compiling your own ArduPilot binary: + python avoidance.py --binary $ARDUPILOT_HOME/build/sitl-debug/bin/arducopter-quad --resolution=PERPENDICULAR --defaults=$ARDUPILOT_HOME/Tools/autotest/copter_params.parm --extra-connection=udpout:localhost:3456 + + ``` +6. What you should see: + - two quadcopters should both enter guided mode + - both should rise to 5m + - one of the copters will start to head north + - a second quadcopter will start to head north-north-west + - the second quadcopter will approach too closely to the first quadcopter and take a perpendicular course to the first quadcopter + diff --git a/examples/avoidance/avoidance-manytests-plane.py b/examples/avoidance/avoidance-manytests-plane.py new file mode 100644 index 000000000..22d7d1456 --- /dev/null +++ b/examples/avoidance/avoidance-manytests-plane.py @@ -0,0 +1,769 @@ +from __future__ import print_function + +""" +avoidance.py: Demonstrate autopilot collision avoidance functionality + +Full documentation is provided at http://python.dronekit.io/examples/avoidance.html +""" + +from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command +import time +import math +from pymavlink import mavutil +import threading + +import dronekit +import mavlink_hub +import sys + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates autopilot automatic avoidance functionality.') +parser.add_argument('--extra-connection', + help="extra MAVLink connections to make.") +parser.add_argument('--test', + help="test to run") +parser.add_argument('--binary', + help="path to autopilot binary to use") +parser.add_argument('--defaults', + help="path to autopilot defaults file to use") +parser.add_argument('--resolution', choices=["TCAS", "RTL", "PERPENDICULAR"], + help="Specify resolution behaviour for conflict", + default="PERPENDICULAR") +args = parser.parse_args() + +# example of a binary path: $HOME/rc/ardupilot/build/sitl-debug/bin/arducopter-quad +# example of a defaults path: $HOME/rc/ardupilot/Tools/autotest/copter_params.parm + +model = "plane" + +sitls = [] + +hub_thread = None +target_systems = [] + +hub_connection_strings = [] + +# units for lat/lon are multiples of ~11 metres from -35.363261 149.165230 +tests = [ + { #0 + "vehicle_info": [ + { + "lat": 0, + "lon": -2, + "alt": 10, + "target-lat": 10, + "target-lon": -2, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #1 + "vehicle_info": [ + { + "lat": 0, + "lon": 2, + "alt": 10, + "target-lat": 10, + "target-lon": 2, + "target-alt": 10, + "expected-heading": 90, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #2 horizontal movement, avoidance LTR, above threat + "vehicle_info": [ + { + "lat": 1, + "lon": 0, + "alt": 10, + "target-lat": 1, + "target-lon": 10, + "target-alt": 10, + "expected-heading": 0, + }, + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + } + ] + }, + { #3 horizontal movement, avoiding aircraft LTR, below threat + "vehicle_info": [ + { + "lat": -1, + "lon": 0, + "alt": 10, + "target-lat": -1, + "target-lon": 10, + "target-alt": 10, + "expected-heading": 180, + }, + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + } + ] + }, + { #4 horizontal movement, avoiding aircraft RTL, below threat + "vehicle_info": [ + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 360, + }, + { + "lat": -1, + "lon": 0, + "alt": 10, + "target-lat": -1, + "target-lon": 10, + "target-alt": 10, + "expected-heading": 90, + }, + ] + }, + + + { #5 threat moves vertically S, we move ENE towards it + "vehicle_info": [ + { + "lat": 0, + "lon": -12, + "alt": 10, + "target-lat": 3, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #6 threat moves vertically S, we move ESE towards it + "vehicle_info": [ + { + "lat": 12, + "lon": -12, + "alt": 10, + "target-lat": 9, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ] + }, + { #7 threat moves N, we move NW towards it + "vehicle_info": [ + { + "lat": 3, + "lon": 12, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 90, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 30, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ], + }, + { #8 threat moves N, we move NE towards it + "vehicle_info": [ + { + "lat": 3, + "lon": -12, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 22, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ], + }, + { #9 threat moves E, we move NNE + "vehicle_info": [ + { + "lat": -8, + "lon": 6, + "alt": 10, + "target-lat": 0, + "target-lon": 12, + "target-alt": 10, + "expected-heading": 180, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 22, + "target-alt": 10, + "expected-heading": 90, + } + ], + }, + + + { #10 threate moves NE, we move SE + "vehicle_info": [ + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 309, + }, + { + "lat": -6, + "lon": -6, + "alt": 10, + "target-lat": 6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 39, + } + ], + }, + { #11 threat moves SE, we move NE + "vehicle_info": [ + { + "lat": -6, + "lon": -6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 230, + }, + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": -6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 140, + } + ], + }, + { #12 threat moves SW, we move SE + "vehicle_info": [ + { + "lat": 6, + "lon": 6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 50, + }, + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": -6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 140, + } + ], + }, +] + + + +# ready data for many dronekit-sitl processes +simulation_count = 2 +for i in range(0,simulation_count): + print("Creating simulator (SITL) %d" % (i,)) + from dronekit_sitl import SITL + breakpoints = [] +# breakpoints = ["GCS_Common.cpp:1031"] +# breakpoints = ["GCS_MAVLINK::handle_mission_item"] +# breakpoints = ["GCS_MAVLINK::handle_mission_count"] +# breakpoints = ["Plane::auto_takeoff_check"] + sitl = SITL(instance=i, path=args.binary, defaults_filepath=args.defaults, gdb=True, valgrind=False, gdb_breakpoints=breakpoints) +# sitl.download('copter', '3.3', verbose=True) + sitls.append(sitl) + hub_connection_strings.append(sitl.connection_string()) + +def load_mission(vehicle): + # load a simple mission so we can take off + cmds = vehicle.commands + + print(" Clear any existing commands") + cmds.clear() + + def check_mission_commands(conn, name , m): +# print("Got message: %s" % (str(m),)) + if m.type != 0: + print("Error uploading mission item: %d" % (m.type)) + + def supply_mission_command(conn, name , m): + print("Got request for mission item: %s" % (str(m),)) + + vehicle.add_message_listener('MISSION_ACK', check_mission_commands) + vehicle.add_message_listener('MISSION_REQUEST', supply_mission_command) + + loc = vehicle.location.global_relative_frame +# cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, 0, 10)) # ignored! + cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, loc.lat+1, loc.lon, 10)) # ignored + + cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, loc.lat, loc.lon, 10)) + cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 0, 0, 0, 0, 0, 0, loc.lat+0.01, loc.lon, 10)) + cmds.add(Command( 0, 0, 0, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, mavutil.mavlink.MAV_CMD_NAV_LOITER_UNLIM, 0, 0, 0, 0, 0, 0, loc.lat+0.01, loc.lon, 10)) + + print(" Upload new commands to vehicle") + cmds.upload() + + +mav_lock = threading.Lock() # FIXME; move locking into MAVSystem + + +# start the SITLs one at a time, giving each a unique SYSID_THISMAV +def set_params_target(i, new_sysid, connection_string): + lat = -35.363261 + lon = 149.165230 + sitl_args = ['--model', model, '--home=%s,%s,584,353' % (lat,lon,) ] + print("%d: Launching SITL (%s)" % (i,str(sitl_args))) + sitls[i].launch(sitl_args, await_ready=True, verbose=True, speedup=10,) + print("%d: Connecting to its vehicle 1" % (i,)) + mav_lock.acquire() + vehicle = dronekit.connect(connection_string, wait_ready=True, target_system=1) + mav_lock.release() + + load_mission(vehicle) + + # set avoidance behaviour to RTL: + if i == 0: + print("%d: Setting avoidance parameters" % (i,)) + + # enable ADSB: + vehicle.parameters["ADSB_ENABLE"] = 1 + # enable avoidance: + vehicle.parameters["AVD_ENABLE"] = 1 + + # set the warn radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_DIST_XY"] = 30 + vehicle.parameters["AVD_W_DIST_Z"] = 20 + # set the warn horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_TIME"] = 10 + + # set the fail radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_DIST_XY"] = 20 + vehicle.parameters["AVD_F_DIST_Z"] = 10 + # set the time horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_TIME"] = 10 + + vehicle.parameters["AVD_W_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_REPORT + vehicle.parameters["AVD_W_RCVRY"] = 1 + vehicle.parameters["AVD_F_RCVRY"] = 1 + if args.resolution == "RTL": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_RTL + elif args.resolution == "PERPENDICULAR": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_MOVE_PERPENDICULAR + elif args.resolution == "TCAS": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_TCAS + + value_tuples = [ [ "ARMING_CHECK", 511 ], + [ "SYSID_THISMAV", new_sysid ], + [ "TKOFF_THR_MINACC", 0.0 ], + [ "TKOFF_THR_MINSPD", 0.0 ], + ] + for value_tuple in value_tuples: + name = value_tuple[0] + value = value_tuple[1] + print("Name: %s Value: %f" % (name, value,)) + while vehicle.parameters[name] != value: + print("Setting %s to %f" % (name, value,)) + vehicle.parameters[name] = value + time.sleep(0.1) + + print("%d: Allowing time for parameter write" % (i,)) + time.sleep(2) + print("%d: Stop" % (i,)) + sitls[i].stop() + vehicle.disconnect() + + +set_params_threads = [] +for i in range(0,len(sitls)): + new_sysid = len(sitls)-i+1 + set_params_threads.append(threading.Thread(target=set_params_target, + args=(i,new_sysid, hub_connection_strings[i]))) + set_params_threads[-1].start() + target_systems.append(new_sysid) +# mav.remove_message_listener(vehicle) + time.sleep(1) # mavlink not thread safe... + +for thread in set_params_threads: + print("Waiting for thread...") + thread.join() + +print("Sleeping a little to let SITLs go away...") +time.sleep(2) + +# create another connection so a GCS can be connected for visualisation +if args.extra_connection: + hub_connection_strings.append(args.extra_connection) + +# dronekit-python (us!) port: +connection_string = "udpout:localhost:2345" +hub_connection_strings.append("udpin:localhost:2345") + +hub_should_quit = False + + +def mavlink_hub_target(): + print("Hub thread starting") + hub = mavlink_hub.MAVLinkHub(hub_connection_strings) + hub.init() + while not hub_should_quit: + hub.loop() + print("Hub quitting") + hub.connection_maintenance_target_should_live = False + +print("Starting mavlink_hub thread") +hub_thread = threading.Thread(target=mavlink_hub_target) +hub_thread.start() + +# Create a MAVLink connection: +print("Attempting connect to hub (%s)" % (connection_string,)) +mav = dronekit.mavlink.MAVConnection(connection_string) +print("Connected") + +vehicles = [None] * len(target_systems) +# Connect to the Vehicle +def vehicle_connect_target(mav, id, offset): + vehicle = dronekit.connect(mav, wait_ready=True, target_system=id) + vehicles[offset] = vehicle + +def dump_vehicle_state(vehicle): + print(" Autopilot Firmware version: %s" % vehicle.version) + print(" Major version number: %s" % vehicle.version.major) + print(" Minor version number: %s" % vehicle.version.minor) + print(" Patch version number: %s" % vehicle.version.patch) + print(" Release type: %s" % vehicle.version.release_type()) + print(" Release version: %s" % vehicle.version.release_version()) + print(" Stable release?: %s" % vehicle.version.is_stable()) + + +def print_collision_message(conn, name , m): + print("Got collision message: %s" % (str(m),)) + + +def arm_and_takeoff(vehicle, aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + + print("Basic pre-arm checks") + # Don't try to arm until autopilot is ready + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + print("Taking off!") + # Confirm vehicle armed before attempting to take off + while not vehicle.armed: + print("Arming motors") + mav_lock.acquire() + vehicle.armed = True + mav_lock.release() + time.sleep(0.5) + + # set mode to auto + while vehicle.mode != 'AUTO': + print("Setting mode AUTO") + mav_lock.acquire() + vehicle.mode = VehicleMode("AUTO") + mav_lock.release() + time.sleep(0.5) + + global takeoff_complete + # wait for the vehicle to finish takeoff: + takeoff_complete = False + def wait_for_takeoff(conn, name, m): + global takeoff_complete + print("Got message: %s" % (str(m),)) + if m.text.find("Takeoff complete") != -1: + print("Found it") + takeoff_complete = True + + vehicle.add_message_listener('STATUSTEXT', wait_for_takeoff) + print("Waiting for takeoff-complete") + while not takeoff_complete: + time.sleep(0.1) + + print("Takeoff is complete") + +# sleep so we can see the change in map +def watch_things_for_a_while(duration=30): + start = time.time() + + while time.time() - start < duration: + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f Alt=%f MODE=%s Hdg=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon, vehicle.location.global_relative_frame.alt, str(vehicle.mode), vehicle.heading)) + time.sleep(1) + +def vehicle_launcher_target(i): + arm_and_takeoff(vehicles[i], 5) + +def launch_all_vehicles(altitudes): + launcher_threads = [] + for i in range(0,len(vehicles)): + print("Launching Vehicle %d:" % (target_systems[i],)) + launcher_threads.append(threading.Thread(target=vehicle_launcher_target, + args=(i,))) + launcher_threads[-1].start() + for thread in launcher_threads: + print("Waiting for launcher thread...") + thread.join() + +# speed = 5 +# for i in range(0,len(vehicles)): +# print("Set default/target airspeed to %d on vehicle %d (%s)" % (target_systems[i],speed, str(target_systems[i]))) +# vehicles[i].airspeed = speed + + while True: + all_done = True + for i in range(0, len(vehicles)): + v_location = vehicles[i].location.global_relative_frame + print("%d alt: %f" % (i, v_location.alt)) + if v_location.alt < altitudes[i]-2: + v_location.alt = altitudes[i] + vehicles[i].simple_goto(v_location) + all_done = False + if all_done: + break + time.sleep(1) + +def relative_lat(increment): + return -35.363261 + 0.0001 * increment + +def relative_lon(increment): + return 149.165230 + 0.0001 * increment + +class TestFailedException(Exception): + pass + +def do_gotos(locations): + print("do gotos!") + for vehicle in vehicles: + print("Setting vehicle to mode guided") + while not vehicle.mode == "GUIDED": + vehicle.mode = VehicleMode("GUIDED") + time.sleep(0.1) + for i in range(0,len(vehicles)): + lat = locations[i]["target-lat"] + lon = locations[i]["target-lon"] + alt = locations[i]["target-alt"] + point = LocationGlobalRelative(lat, lon, alt) + vehicles[i].simple_goto(point) + +def do_test(test): + print("Launching SITLs") + for i in range(0,len(sitls)): + sitl = sitls[i] + lat = relative_lat(test["vehicle_info"][i]["lat"]) + lon = relative_lon(test["vehicle_info"][i]["lon"]) + sitl_args = ['--model', model, '--home=%s,%s,584,353' % (lat,lon,) ] + sitl.launch(sitl_args, await_ready=True, restart=True, use_saved_data=True, wd=sitl.wd, verbose=True, speedup=2) + + offset = 0 + connect_threads = [] + for id in target_systems: + print('Connecting to vehicle with system ID (%d)' % id) + connect_threads.append(threading.Thread(target=vehicle_connect_target, + args=(mav,id,offset))) + connect_threads[-1].start() + offset += 1 + time.sleep(2) # mav is not thread safe?! + + for thread in connect_threads: + print("Waiting for connect thread...") + thread.join() + + for vehicle in vehicles: + dump_vehicle_state(vehicle) + + vehicles[0].add_message_listener('COLLISION', print_collision_message) + + altitudes = [] + for i in range(0,len(vehicles)): + altitudes.append(test["vehicle_info"][i]["alt"]) + + launch_all_vehicles(altitudes) + + print("Starting gotos") + locations = [ + { + "target-lat": -35.363261 + 0.01, + "target-lon": 149.165230, + "target-alt": 40, + }, + { + "target-lat": -35.363261 - 0.01, + "target-lon": 149.165230, + "target-alt": 40, + } + ] + + do_gotos(locations) + + global at_goto_location_count + at_goto_location_count = 0 + def increment_at_location(conn, name, m): + global at_goto_location_count + print("at location") + at_goto_location_count += 1 + + vehicles[0].add_message_listener('MISSION_ITEM_REACHED', increment_at_location) + vehicles[1].add_message_listener('MISSION_ITEM_REACHED', increment_at_location) + while at_goto_location_count != 2: + time.sleep(0.1) + vehicles[0].remove_message_listener('MISSION_ITEM_REACHED', increment_at_location) + vehicles[1].remove_message_listener('MISSION_ITEM_REACHED', increment_at_location) + + print("Both ready") + + vehicles_at_correct_heading_timer = 0 + loop_start_time = time.time() + success = None + while success is None: + + all_correct = True + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f Alt=%f MODE=%s Hdg=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon, vehicle.location.global_relative_frame.alt, str(vehicle.mode), vehicle.heading)) + expected = test["vehicle_info"][i]["expected-heading"] + if vehicles[i].heading > expected: + delta = vehicles[i].heading - expected + else: + delta = expected - vehicles[i].heading + if delta > 180: + if vehicles[i].heading > 180: + delta = 360 - vehicles[i].heading + expected + else: + delta = 360 - expected + vehicles[i].heading + print("Expecting vehicle %d at heading=%f actual=%f delta=%f" % (i, expected, vehicles[i].heading, delta)) + if delta > 3: + all_correct = False + if all_correct: + if vehicles_at_correct_heading_timer != 0: + if time.time() - vehicles_at_correct_heading_timer > 5: + success = True + else: + time.sleep(1) + else: + # start the timer + vehicles_at_correct_heading_timer = time.time() + time.sleep(1) + else: + vehicles_at_correct_heading_timer = 0 + time.sleep(1) + timeout = 30 + if time.time() - loop_start_time > timeout: + success = False + + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + vehicle.disconnect() + sitls[i].stop() + + if not success: + print("Test failed") + raise TestFailedException("Test failed") + + print("Success") + +if args.test is not None: + try: + do_test(tests[int(args.test)]) + except TestFailedException as e: + print("Test {} Failed: {}".format(int(args.test), str(e))) +else: + count=0 + for test in tests: + print("Doing test #%d" % (count,)) + try: + do_test(test) + except TestFailedException as e: + print("Test {} Failed: {}".format(count, str(e))) + break + count += 1 + +print("All done") + +if hub_thread is not None: + hub_should_quit = True + hub_thread.join() diff --git a/examples/avoidance/avoidance-manytests.py b/examples/avoidance/avoidance-manytests.py new file mode 100644 index 000000000..c437613d4 --- /dev/null +++ b/examples/avoidance/avoidance-manytests.py @@ -0,0 +1,823 @@ +from __future__ import print_function + +""" +avoidance.py: Demonstrate autopilot collision avoidance functionality + +Full documentation is provided at http://python.dronekit.io/examples/avoidance.html +""" + +from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command +import time +import math +from pymavlink import mavutil +import threading + +import dronekit +import mavlink_hub +import sys + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates autopilot automatic avoidance functionality.') +parser.add_argument('--extra-connection', + help="extra MAVLink connections to make.") +parser.add_argument('--test', + help="test to run") +parser.add_argument('--binary', + help="path to autopilot binary to use") +parser.add_argument('--defaults', + help="path to autopilot defaults file to use") +parser.add_argument('--resolution', choices=["TCAS", "RTL", "PERPENDICULAR"], + help="Specify resolution behaviour for conflict", + default="PERPENDICULAR") +args = parser.parse_args() + +# example of a binary path: $HOME/rc/ardupilot/build/sitl-debug/bin/arducopter-quad +# example of a defaults path: $HOME/rc/ardupilot/Tools/autotest/copter_params.parm + + +sitls = [] + +hub_thread = None +target_systems = [] + +hub_connection_strings = [] + +# units for lat/lon are multiples of ~11 metres from -35.363261 149.165230 +tests = [ + { #0 + "vehicle_info": [ + { + "lat": 0, + "lon": -2, + "alt": 10, + "target-lat": 10, + "target-lon": -2, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #1 + "vehicle_info": [ + { + "lat": 0, + "lon": 2, + "alt": 10, + "target-lat": 10, + "target-lon": 2, + "target-alt": 10, + "expected-heading": 90, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #2 horizontal movement, avoidance LTR, above threat + "vehicle_info": [ + { + "lat": 1, + "lon": 0, + "alt": 10, + "target-lat": 1, + "target-lon": 10, + "target-alt": 10, + "expected-heading": 0, + }, + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + } + ] + }, + { #3 horizontal movement, avoiding aircraft LTR, below threat + "vehicle_info": [ + { + "lat": -1, + "lon": 0, + "alt": 10, + "target-lat": -1, + "target-lon": 10, + "target-alt": 10, + "expected-heading": 180, + }, + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + } + ] + }, + { #4 horizontal movement, avoiding aircraft RTL, below threat + "vehicle_info": [ + { + "lat": 0, + "lon": 12, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 360, + }, + { + "lat": -1, + "lon": 0, + "alt": 10, + "target-lat": -1, + "target-lon": 20, + "target-alt": 10, + "expected-heading": 90, + }, + ] + }, + + + { #5 threat moves vertically S, we move ENE towards it + "vehicle_info": [ + { + "lat": 0, + "lon": -12, + "alt": 10, + "target-lat": 3, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 180, + } + ] + }, + { #6 threat moves vertically S, we move ESE towards it + "vehicle_info": [ + { + "lat": 12, + "lon": -12, + "alt": 10, + "target-lat": 9, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ] + }, + { #7 threat moves N, we move NW towards it + "vehicle_info": [ + { + "lat": 3, + "lon": 12, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 90, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 30, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ], + }, + { #8 threat moves N, we move NE towards it + "vehicle_info": [ + { + "lat": 3, + "lon": -12, + "alt": 10, + "target-lat": 12, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 270, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 22, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 0, + } + ], + }, + { #9 threat moves E, we move NNE + "vehicle_info": [ + { + "lat": -8, + "lon": 6, + "alt": 10, + "target-lat": 0, + "target-lon": 12, + "target-alt": 10, + "expected-heading": 180, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 12, + "target-alt": 10, + "expected-heading": 90, + } + ], + }, + + + { #10 threate moves NE, we move SE + "vehicle_info": [ + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 309, + }, + { + "lat": -6, + "lon": -6, + "alt": 10, + "target-lat": 6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 39, + } + ], + }, + { #11 threat moves SE, we move NE + "vehicle_info": [ + { + "lat": -6, + "lon": -6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 230, + }, + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": -6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 140, + } + ], + }, + { #12 threat moves SW, we move SE + "vehicle_info": [ + { + "lat": 6, + "lon": 6, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 50, + }, + { + "lat": 6, + "lon": -6, + "alt": 10, + "target-lat": -6, + "target-lon": 6, + "target-alt": 10, + "expected-heading": 140, + } + ], + }, + + + { #13 threat is stationery, we move SE, BELOW 3D-avoid height + "vehicle_info": [ + { + "lat": 1, + "lon": 6, + "alt": 10, + "target-lat": 1, + "target-lon": -6, + "target-alt": 10, + "expected-heading": 73, + }, + { + "lat": 0, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + "expected-heading": 307, # this is kind of random + } + ], + }, + + { #14 threat is stationery, we move SE, ABOVE 3D-avoid height + "vehicle_info": [ + { + "lat": 1, + "lon": 15, + "alt": 50, + "target-lat": 1, + "target-lon": -6, + "target-alt": 60, + "expected-heading": 72, + }, + { + "lat": 0, + "lon": -0.001, + "alt": 60, + "target-lat": 0, + "target-lon": 0, + "target-alt": 50, + "expected-heading": 90, + } + ], + }, +] + + + +# ready data for many dronekit-sitl processes +simulation_count = 2 +for i in range(0,simulation_count): + print("Creating simulator (SITL) %d" % (i,)) + from dronekit_sitl import SITL + sitl = SITL(instance=i, path=args.binary, defaults_filepath=args.defaults, gdb=True) +# sitl.download('copter', '3.3', verbose=True) + sitls.append(sitl) + hub_connection_strings.append(sitl.connection_string()) + +# start the SITLs one at a time, giving each a unique SYSID_THISMAV +def set_params_target(i, new_sysid, connection_string): + lat = -35.363261 + lon = 149.165230 + sitl_args = ['--model', 'quad', '--home=%s,%s,584,353' % (lat,lon,) ] + print("%d: Launching SITL (%s)" % (i,str(sitl_args))) + sitls[i].launch(sitl_args, await_ready=True, verbose=True, speedup=50,) + print("Sleeping a little here") + time.sleep(5) + print("%d: Connecting to its vehicle 1" % (i,)) + vehicle = dronekit.connect(connection_string, wait_ready=True, target_system=1, heartbeat_timeout=60) + while vehicle.parameters["SYSID_THISMAV"] != new_sysid: + print("%d: Resetting its SYID_THISMAV to %d" % (i, new_sysid,)) + vehicle.parameters["SYSID_THISMAV"] = new_sysid + time.sleep(0.1) + + # set avoidance behaviour to RTL: + if i == 0: + print("%d: Setting avoidance parameters" % (i,)) + + # enable ADSB: + vehicle.parameters["ADSB_ENABLE"] = 1 + # enable avoidance: + vehicle.parameters["AVD_ENABLE"] = 1 + + # set the warn radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_DIST_XY"] = 30 + vehicle.parameters["AVD_W_DIST_Z"] = 20 + # set the warn horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_TIME"] = 10 + + # set the fail radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_DIST_XY"] = 20 + vehicle.parameters["AVD_F_DIST_Z"] = 10 + # set the time horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_TIME"] = 10 + + vehicle.parameters["AVD_W_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_REPORT + vehicle.parameters["AVD_W_RCVRY"] = 1 + vehicle.parameters["AVD_F_RCVRY"] = 1 + if args.resolution == "RTL": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_RTL + elif args.resolution == "PERPENDICULAR": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_MOVE_PERPENDICULAR + elif args.resolution == "TCAS": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_TCAS + + print("%d: Allowing time for parameter write" % (i,)) + time.sleep(2) + vehicle.disconnect() + + print("%d: Stop" % (i,)) + sitls[i].stop() + +set_params_threads = [] +for i in range(0,len(sitls)): + new_sysid = len(sitls)-i+1 + set_params_threads.append(threading.Thread(target=set_params_target, + args=(i,new_sysid, hub_connection_strings[i]))) + set_params_threads[-1].start() + target_systems.append(new_sysid) +# mav.remove_message_listener(vehicle) + time.sleep(1) # mavlink not thread safe... + +for thread in set_params_threads: + print("Waiting for thread...") + thread.join() + +print("Sleeping a little to let SITLs go away...") +time.sleep(2) + + +# create another connection so a GCS can be connected for visualisation +if args.extra_connection: + hub_connection_strings.append(args.extra_connection) + +# dronekit-python (us!) port: +connection_string = "udpout:localhost:2345" +hub_connection_strings.append("udpin:localhost:2345") + +hub_should_quit = False + + +def mavlink_hub_target(): + print("Hub thread starting") + hub = mavlink_hub.MAVLinkHub(hub_connection_strings) + hub.init() + while not hub_should_quit: + hub.loop() + print("Hub quitting") + hub.connection_maintenance_target_should_live = False + +print("Starting mavlink_hub thread") +hub_thread = threading.Thread(target=mavlink_hub_target) +hub_thread.start() + +# Create a MAVLink connection: +print("Attempting connect to hub (%s)" % (connection_string,)) +mav = dronekit.mavlink.MAVConnection(connection_string) +print("Connected") + +vehicles = [None] * len(target_systems) +# Connect to the Vehicle +def vehicle_connect_target(mav, id, offset): + vehicle = dronekit.connect(mav, wait_ready=True, target_system=id) + vehicles[offset] = vehicle + +def dump_vehicle_state(vehicle): + print(" Autopilot Firmware version: %s" % vehicle.version) + print(" Major version number: %s" % vehicle.version.major) + print(" Minor version number: %s" % vehicle.version.minor) + print(" Patch version number: %s" % vehicle.version.patch) + print(" Release type: %s" % vehicle.version.release_type()) + print(" Release version: %s" % vehicle.version.release_version()) + print(" Stable release?: %s" % vehicle.version.is_stable()) + + +def print_collision_message(conn, name , m): + print("Got collision message: %s" % (str(m),)) + +mav_lock = threading.Lock() # FIXME; move locking into MAVSystem + +def arm_and_takeoff(vehicle, aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + + print("Basic pre-arm checks") + # Don't try to arm until autopilot is ready + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + # Copter should arm in GUIDED mode + while vehicle.mode != 'GUIDED': + print("Setting mode GUIDED") + mav_lock.acquire() + vehicle.mode = VehicleMode("GUIDED") + mav_lock.release() + time.sleep(0.5) + + # Confirm vehicle armed before attempting to take off + while not vehicle.armed: + print("Arming motors") + mav_lock.acquire() + vehicle.armed = True + mav_lock.release() + time.sleep(0.5) + + print("Taking off!") + mav_lock.acquire() + vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude + mav_lock.release() + + # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command + # after Vehicle.simple_takeoff will execute immediately). + while True: + print(" Mode: %s Altitude: %f" % (str(vehicle.mode), vehicle.location.global_relative_frame.alt,)) + #Break and return from function just below target altitude. + if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: + print("Reached target altitude") + break + time.sleep(1) + +# sleep so we can see the change in map +def watch_things_for_a_while(duration=30): + start = time.time() + + while time.time() - start < duration: + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f Alt=%f MODE=%s Hdg=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon, vehicle.location.global_relative_frame.alt, str(vehicle.mode), vehicle.heading)) + time.sleep(1) + +def vehicle_launcher_target(i): + arm_and_takeoff(vehicles[i], 5) + +def launch_all_vehicles(altitudes): + launcher_threads = [] + for i in range(0,len(vehicles)): + print("Launching Vehicle %d:" % (target_systems[i],)) + launcher_threads.append(threading.Thread(target=vehicle_launcher_target, + args=(i,))) + launcher_threads[-1].start() + for thread in launcher_threads: + print("Waiting for launcher thread...") + thread.join() + +# speed = 5 +# for i in range(0,len(vehicles)): +# print("Set default/target airspeed to %d on vehicle %d (%s)" % (target_systems[i],speed, str(target_systems[i]))) +# vehicles[i].airspeed = speed + + while True: + all_done = True + for i in range(0, len(vehicles)): + v_location = vehicles[i].location.global_relative_frame + print("%d alt: %f" % (i, v_location.alt)) + if v_location.alt < altitudes[i]-2: + v_location.alt = altitudes[i] + vehicles[i].simple_goto(v_location) + all_done = False + if all_done: + break + time.sleep(1) + +def relative_lat(increment): + return -35.363261 + 0.0001 * increment + +def relative_lon(increment): + return 149.165230 + 0.0001 * increment + +class TestFailedException(Exception): + pass + + +def heading_delta(a, b): + if a > b: + delta = a - b + else: + delta = b - a + if delta > 180: + if a > 180: + delta = 360 - a + b + else: + delta = 360 - b + a + return delta + +def do_vehicle_connects(): + offset = 0 + connect_threads = [] + for id in target_systems: + print('Connecting to vehicle with system ID (%d)' % id) + connect_threads.append(threading.Thread(target=vehicle_connect_target, + args=(mav,id,offset))) + connect_threads[-1].start() + offset += 1 + time.sleep(2) # mav is not thread safe?! + + for thread in connect_threads: + print("Waiting for connect thread...") + thread.join() + + for vehicle in vehicles: + dump_vehicle_state(vehicle) + +def position_vehicles(positions): + print("Launching SITLs") + for i in range(0,len(sitls)): + sitl = sitls[i] + position = positions[i] + lat = position["lat"] + lon = position["lon"] + sitl_args = ['--model', 'quad', '--home=%s,%s,584,353' % (lat,lon,) ] + sitl.launch(sitl_args, await_ready=True, restart=True, use_saved_data=True, wd=sitl.wd, verbose=True, speedup=2) + + do_vehicle_connects() + + altitudes = [] + for i in range(0,len(vehicles)): + altitudes.append(positions[i]["alt"]) + + launch_all_vehicles(altitudes) + + print("Starting gotos") + + for i in range(0,len(vehicles)): + position = positions[i] + lat = position["target-lat"] + lon = position["target-lon"] + alt = position["target-alt"] + print("vehicle %d: doing simple_goto (%s %s %s" % (target_systems[i],lat, lon, alt)) + point = LocationGlobalRelative(lat, lon, alt) + vehicles[i].simple_goto(point) + + +def do_heading_test(test): + + positions = [] + for i in range(0,len(sitls)): + positions.append({ "lat": relative_lat(test["vehicle_info"][i]["lat"]), + "lon": relative_lon(test["vehicle_info"][i]["lon"]), + "alt": test["vehicle_info"][i]["alt"], + "target-lat": relative_lat(test["vehicle_info"][i]["target-lat"]), + "target-lon": relative_lon(test["vehicle_info"][i]["target-lon"]), + "target-alt": test["vehicle_info"][i]["target-alt"], + }) + position_vehicles(positions) + + vehicles[0].add_message_listener('COLLISION', print_collision_message) + + vehicles_at_correct_heading_timer = 0 + loop_start_time = time.time() + success = None + while success is None: + all_correct = True + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f Alt=%f MODE=%s Hdg=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon, vehicle.location.global_relative_frame.alt, str(vehicle.mode), vehicle.heading)) + expected = test["vehicle_info"][i]["expected-heading"] + delta = heading_delta(expected, vehicles[i].heading) + + print("Expecting vehicle %d at heading=%f actual=%f delta=%f" % (i, expected, vehicles[i].heading, delta)) + if delta > 3: + all_correct = False + if all_correct: + if vehicles_at_correct_heading_timer != 0: + if time.time() - vehicles_at_correct_heading_timer > 5: + success = True + else: + time.sleep(1) + else: + # start the timer + vehicles_at_correct_heading_timer = time.time() + time.sleep(1) + else: + vehicles_at_correct_heading_timer = 0 + time.sleep(1) + timeout = 30 + if time.time() - loop_start_time > timeout: + success = False + + vehicles[0].remove_message_listener('COLLISION', print_collision_message) + + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + vehicle.disconnect() + sitls[i].stop() + + if not success: + print("Test failed") + raise TestFailedException("Test failed") + + print("Success") + +def do_disable_test(): + + vehicle_info = [ + { + "lat": 0, + "lon": -2, + "alt": 10, + "target-lat": 10, + "target-lon": -2, + "target-alt": 10, + }, + { + "lat": 12, + "lon": 0, + "alt": 10, + "target-lat": 0, + "target-lon": 0, + "target-alt": 10, + } + ] + + positions = [] + for i in range(0,len(sitls)): + positions.append({ "lat": relative_lat(vehicle_info[i]["lat"]), + "lon": relative_lon(vehicle_info[i]["lon"]), + "alt": vehicle_info[i]["alt"], + "target-lat": relative_lat(vehicle_info[i]["target-lat"]), + "target-lon": relative_lon(vehicle_info[i]["target-lon"]), + "target-alt": vehicle_info[i]["target-alt"], + }) + + global success + success = True + def mode_watcher(conn, name , m): + global success + if vehicles[0].mode != "GUIDED": + print("mode is not GUIDED: %s" % (str(vehicles[0].mode))); + success = False; + + position_vehicles(positions) + + vehicles[0].add_message_listener('HEARTBEAT', mode_watcher) + + # turn off avoidance (vehicle is already flying!) + vehicles[0].parameters['CH8_OPT'] = 38 + vehicles[0].channels.overrides[8] = 30 + + # just wait + start = time.time() + while success == True and time.time() - start < 30: + time.sleep(1) + + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + vehicle.disconnect() + sitls[i].stop() + + if not success: + print("Test failed") + raise TestFailedException("Test failed") + + print("Success") + + +if False: + + do_disable_test() + +else: + if args.test is not None: + try: + do_heading_test(tests[int(args.test)]) + except TestFailedException as e: + print("Test {} Failed: {}".format(int(args.test), str(e))) + else: + count=0 + for test in tests: + print("Doing test #%d" % (count,)) + try: + do_heading_test(test) + except TestFailedException as e: + print("Test {} Failed: {}".format(count, str(e))) + break + count += 1 + +print("All done") + +if hub_thread is not None: + hub_should_quit = True + hub_thread.join() diff --git a/examples/avoidance/avoidance.py b/examples/avoidance/avoidance.py new file mode 100644 index 000000000..9df6fa5ba --- /dev/null +++ b/examples/avoidance/avoidance.py @@ -0,0 +1,354 @@ +from __future__ import print_function + +""" +avoidance.py: Demonstrate autopilot collision avoidance functionality + +Full documentation is provided at http://python.dronekit.io/examples/avoidance.html +""" + +from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command +import time +import math +from pymavlink import mavutil +import threading + +import dronekit +import mavlink_hub + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates autopilot automatic avoidance functionality.') +parser.add_argument('--extra-connection', + help="extra MAVLink connections to make.") +parser.add_argument('--binary', + help="path to autopilot binary to use") +parser.add_argument('--defaults', + help="path to autopilot defaults file to use") +parser.add_argument('--resolution', choices=["TCAS", "RTL", "PERPENDICULAR"], + help="Specify resolution behaviour for conflict", + default="PERPENDICULAR") +args = parser.parse_args() + +# example of a binary path: $HOME/rc/ardupilot/build/sitl-debug/bin/arducopter-quad +# example of a defaults path: $HOME/rc/ardupilot/Tools/autotest/copter_params.parm + + +sitls = [] + +hub_thread = None +target_systems = [] + +hub_connection_strings = [] + +vehicle_setup = [{}, {}] +vehicle_setup[0] = { + "lat": -35.363261, + "lon": 149.165230, + "target-lat": -35.363261 + 0.00064, + "target-lon": 149.165230, +} +vehicle_setup[1] = { + "lat": vehicle_setup[0]["lat"] + 0.00064, + "lon": vehicle_setup[0]["lon"] + 0.00032, +# "target-lat": -35.363261 + 1.25*0.00120, + "target-lat": -35.363261 + -1.25*0.00120, + # "target-lat": -35.363261 + 0.00032, + "target-lon": 149.165230 - 0.5*0.00128, +} + + + +# ready data for many dronekit-sitl processes +simulation_count = 2 +for i in range(0,simulation_count): + print("Creating simulator (SITL) %d" % (i,)) + from dronekit_sitl import SITL + sitl = SITL(instance=i, path=args.binary, defaults_filepath=args.defaults, gdb=True) +# sitl.download('copter', '3.3', verbose=True) + lat = -35.363261 + i*0.00128 + lat = vehicle_setup[i]["lat"] + lon = vehicle_setup[i]["lon"] + sitl_args = ['--model', 'quad', '--home=%s,%s,584,353' % (lat,lon,) ] + sitls.append([sitl, sitl_args]) + hub_connection_strings.append(sitl.connection_string()) + +# start the SITLs one at a time, giving each a unique SYSID_THISMAV +def change_sysid_target(i, new_sysid, connection_string): + print("%d: Launching SITL (%s)" % (i,str(sitls[i][1]))) + sitls[i][0].launch(sitls[i][1], await_ready=True, verbose=True, speedup=50,) + print("%d: Connecting to its vehicle 1" % (i,)) + vehicle = dronekit.connect(connection_string, wait_ready=True, target_system=1) + while vehicle.parameters["SYSID_THISMAV"] != new_sysid: + print("%d: Resetting its SYID_THISMAV to %d" % (i, new_sysid,)) + vehicle.parameters["SYSID_THISMAV"] = new_sysid + time.sleep(0.1) + + # set avoidance behaviour to RTL: + if i == 0: + + # enable ADSB: + vehicle.parameters["ADSB_ENABLE"] = 1 + # enable avoidance: + vehicle.parameters["AVD_ENABLE"] = 1 + + # set the warn radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_DIST_XY"] = 30 + vehicle.parameters["AVD_W_DIST_Z"] = 20 + # set the warn horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_W_TIME"] = 10 + + # set the fail radius down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_DIST_XY"] = 20 + vehicle.parameters["AVD_F_DIST_Z"] = 10 + # set the time horizon down to let us see everything on a reasonable scale: + vehicle.parameters["AVD_F_TIME"] = 10 + + vehicle.parameters["AVD_W_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_REPORT + vehicle.parameters["AVD_W_RCVRY"] = 1 + vehicle.parameters["AVD_F_RCVRY"] = 1 + if args.resolution == "RTL": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_RTL + elif args.resolution == "PERPENDICULAR": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_MOVE_PERPENDICULAR + elif args.resolution == "TCAS": + vehicle.parameters["AVD_F_ACTION"] = mavutil.mavlink.MAV_COLLISION_ACTION_TCAS + + print("%d: Allowing time for parameter write" % (i,)) + time.sleep(2) + print("%d: Stop" % (i,)) + sitls[i][0].stop() + vehicle.disconnect() + +change_sysid_threads = [] +for i in range(0,len(sitls)): + new_sysid = len(sitls)-i+1 + change_sysid_threads.append(threading.Thread(target=change_sysid_target, + args=(i,new_sysid, hub_connection_strings[i]))) + change_sysid_threads[-1].start() + target_systems.append(new_sysid) +# mav.remove_message_listener(vehicle) + time.sleep(1) # mavlink not thread safe... + +for thread in change_sysid_threads: + print("Waiting for thread...") + thread.join() + +print("Sleeping a little to let SITLs go away...") +time.sleep(2) +print("Launching SITLs") +for i in range(0,len(sitls)): + sitl = sitls[i][0] + sitl_args = sitls[i][1] + sitl.launch(sitl_args, await_ready=True, restart=True, use_saved_data=True, wd=sitl.wd, verbose=True) + +# create another connection so a GCS can be connected for visualisation +if args.extra_connection: + hub_connection_strings.append(args.extra_connection) + +# dronekit-python (us!) port: +connection_string = "udpout:localhost:2345" +hub_connection_strings.append("udpin:localhost:2345") + +hub_should_quit = False +def mavlink_hub_target(): + print("Hub thread starting") + hub = mavlink_hub.MAVLinkHub(hub_connection_strings) + hub.init() + while not hub_should_quit: + hub.loop() + print("Hub quitting") + hub.connection_maintenance_target_should_live = False + +print("Starting mavlink_hub thread") +hub_thread = threading.Thread(target=mavlink_hub_target) +hub_thread.start() + +# Create a MAVLink connection: +print("Attempting connect to (%s)" % (connection_string,)) +mav = dronekit.mavlink.MAVConnection(connection_string) +print("Connected") + +vehicles = [None] * len(target_systems) +# Connect to the Vehicle +def vehicle_connect_target(mav, id, offset): + vehicle = dronekit.connect(mav, wait_ready=True, target_system=id) + vehicles[offset] = vehicle + +offset = 0 +connect_threads = [] +for id in target_systems: + print('Connecting to vehicle with system ID (%d)' % id) + connect_threads.append(threading.Thread(target=vehicle_connect_target, + args=(mav,id,offset))) + connect_threads[-1].start() + offset += 1 + time.sleep(2) # mav is not thread safe?! + +for thread in connect_threads: + print("Waiting for connect thread...") + thread.join() + +def dump_vehicle_state(vehicle): + print(" Autopilot Firmware version: %s" % vehicle.version) + print(" Major version number: %s" % vehicle.version.major) + print(" Minor version number: %s" % vehicle.version.minor) + print(" Patch version number: %s" % vehicle.version.patch) + print(" Release type: %s" % vehicle.version.release_type()) + print(" Release version: %s" % vehicle.version.release_version()) + print(" Stable release?: %s" % vehicle.version.is_stable()) + + +for vehicle in vehicles: + dump_vehicle_state(vehicle) + +def print_collision_message(conn, name , m): + print("Got collision message: %s" % (str(m),)) + +vehicles[0].add_message_listener('COLLISION', print_collision_message) + +mav_lock = threading.Lock() # FIXME; move locking into MAVSystem + +def arm_and_takeoff(vehicle, aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + + print("Basic pre-arm checks") + # Don't try to arm until autopilot is ready + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + # Copter should arm in GUIDED mode + while vehicle.mode != 'GUIDED': + print("Setting mode GUIDED") + mav_lock.acquire() + vehicle.mode = VehicleMode("GUIDED") + mav_lock.release() + time.sleep(0.5) + + # Confirm vehicle armed before attempting to take off + while not vehicle.armed: + print("Arming motors") + mav_lock.acquire() + vehicle.armed = True + mav_lock.release() + time.sleep(0.5) + + print("Taking off!") + mav_lock.acquire() + vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude + mav_lock.release() + + # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command + # after Vehicle.simple_takeoff will execute immediately). + while True: + print(" Mode: %s Altitude: %f" % (str(vehicle.mode), vehicle.location.global_relative_frame.alt,)) + #Break and return from function just below target altitude. + if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: + print("Reached target altitude") + break + time.sleep(1) + +# sleep so we can see the change in map +def watch_things_for_a_while(duration=30): + start = time.time() + + while time.time() - start < duration: + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f Alt=%f MODE=%s Hdg=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon, vehicle.location.global_relative_frame.alt, str(vehicle.mode), vehicle.heading)) + time.sleep(1) + +def vehicle_launcher_target(i): + arm_and_takeoff(vehicles[i], 5) + +def launch_all_vehicles(): + launcher_threads = [] + for i in range(0,len(vehicles)): + print("Launching Vehicle %d:" % (target_systems[i],)) + launcher_threads.append(threading.Thread(target=vehicle_launcher_target, + args=(i,))) + launcher_threads[-1].start() + for thread in launcher_threads: + print("Waiting for launcher thread...") + thread.join() + + speed = 2 + for i in range(0,len(vehicles)): + print("Set default/target airspeed to %d on vehicle %d (%s)" % (target_systems[i],speed, str(target_systems[i]))) + vehicles[i].airspeed = speed + speed += 1 + +def oblique_chase(): + print("Starting oblique chase") + + bring_vehicles_to_altitudes([ 10, 5 ]) + + for i in range(0,len(vehicles)): + print("vehicle %d: doing simple_goto ..." % (target_systems[i],)) + point = LocationGlobalRelative(vehicle_setup[i]["target-lat"], vehicle_setup[i]["target-lon"], 20) + vehicles[i].simple_goto(point) + + watch_things_for_a_while(60) + + for i in range(0, len(vehicles)): + + while vehicles[i].mode != "RTL": + print("Setting returning to Launch - vehicle %d" % (target_systems[i],)) + vehicles[i].mode = VehicleMode("RTL") + time.sleep(0.1) + + watch_things_for_a_while(duration=60) + + print("Finished oblique chase") + +def bring_vehicles_to_altitudes(altitudes): + print("having vehicles climb a bit") + while True: + all_done = True + for i in range(0, len(vehicles)): + v_location = vehicles[i].location.global_relative_frame + print("%d alt: %f" % (i, v_location.alt)) + if v_location.alt < altitudes[i]-2: + v_location.alt = altitudes[i] + vehicles[i].simple_goto(v_location) + all_done = False + if all_done: + break + time.sleep(1) + +def vertical_separation(): + + bring_vehicles_to_altitudes([ 5, 30 ]) + + def should_see_no_collision_msgs(conn, name , m): + print("UNEXPECTED collision message: %s" % (str(m),)) + + vehicles[0].add_message_listener('COLLISION', should_see_no_collision_msgs) + + for i in range(0,len(vehicles)): + print("vehicle %d going towards first point for 30 seconds ..." % (target_systems[i],)) + point = LocationGlobalRelative(vehicle_setup[i]["target-lat"], vehicle_setup[i]["target-lon"], altitudes[i]) + vehicles[i].simple_goto(point) + + watch_things_for_a_while(60) + + for i in range(0, len(vehicles)): + + while vehicles[i].mode != "RTL": + print("Setting returning to Launch - vehicle %d" % (target_systems[i],)) + vehicles[i].mode = VehicleMode("RTL") + time.sleep(0.1) + + watch_things_for_a_while(duration=60) + +launch_all_vehicles() +oblique_chase() +# vertical_separation() + +print("All done") + +if hub_thread is not None: + hub_should_quit = True + hub_thread.join() diff --git a/examples/avoidance/mavlink_hub.py b/examples/avoidance/mavlink_hub.py new file mode 100644 index 000000000..338748a75 --- /dev/null +++ b/examples/avoidance/mavlink_hub.py @@ -0,0 +1,121 @@ +from __future__ import print_function + +from pymavlink import mavutil +import time +import threading + +class Connection(): + def __init__(self, addr): + self.addr = addr + self._active = False + self.last_packet_received = 0 + self.last_connection_attempt = 0 + + def open(self): + try: + print("HUB: Opening connection to %s" % (self.addr,)) + self.mav = mavutil.mavlink_connection(self.addr) + self._active = True + self.last_packet_received = time.time() # lie + + except Exception as e: + print("HUB: Connection to (%s) failed: %s" % (self.addr, str(e))) + + def close(self): + self.mav.close() + self._active = False + + def active(self): + return self._active + +class MAVLinkHub(): + def __init__(self, addrs): + self.addrs = addrs + self.conns = [] + self.connection_maintenance_target_should_live = True + self.inactivity_timeout = 10 + self.reconnect_interval = 5 + + def maintain_connections(self): + now = time.time() + for conn in self.conns: + if not conn.active(): + continue + if now - conn.last_packet_received > self.inactivity_timeout: + print("HUB: Connection (%s) timed out" % (conn.addr,)) + conn.close() + for conn in self.conns: + if not conn.active(): + if now - conn.last_connection_attempt > self.reconnect_interval: + conn.last_connection_attempt = now + conn.open() +# else: +# print("Connection %s OK" % (conn.addr)) + time.sleep(0.1) + + def create_connections(self): + for addr in self.addrs: + print("Creating connection (%s)" % addr) + self.conns.append(Connection(addr)) + + def handle_messages(self): + now = time.time() + packet_received = False + for conn in self.conns: + if not conn.active(): + continue + m = None + try: + m = conn.mav.recv_msg() + except Exception as e: + print("HUB: Exception receiving message on addr(%s): %s" % (str(conn.addr),str(e))) + conn.close() + + if m is not None: + conn.last_packet_received = now + packet_received = True +# print("HUB: Received message (%s) on connection %s from src=(%d/%d)" % (str(m), conn.addr, m.get_srcSystem(), m.get_srcComponent(),)) + for j in self.conns: + if not j.active(): + continue + if j.addr == conn.addr: + continue +# print("HUB: Resending message on connection %s" % (j.addr,)) + j.mav.write(m.get_msgbuf()) + if not packet_received: + time.sleep(0.01) + + def init(self): + self.create_connections() + self.create_connection_maintenance_thread() + + def loop(self): + self.handle_messages() + + def create_connection_maintenance_thread(self): + '''create and start helper threads and the like''' + def connection_maintenance_target(): + while self.connection_maintenance_target_should_live: + self.maintain_connections() + time.sleep(0.1) + connection_maintenance_thread = threading.Thread(target=connection_maintenance_target) + connection_maintenance_thread.start() + + def run(self): + self.init() + +# print("HUB: Entering main loop") + while True: + self.loop() + +if __name__ == '__main__': + + from optparse import OptionParser + parser = OptionParser("mavlink_hub.py [options]") + (opts, args) = parser.parse_args() + + hub = MAVLinkHub(args) + if len(args) == 0: + print("HUB: Insufficient arguments") + sys.exit(1) + hub.run() diff --git a/examples/channel_overrides/channel_overrides.py b/examples/channel_overrides/channel_overrides.py index 358a7ea51..0da683835 100644 --- a/examples/channel_overrides/channel_overrides.py +++ b/examples/channel_overrides/channel_overrides.py @@ -19,7 +19,7 @@ """ from __future__ import print_function from dronekit import connect - +import time #Set up option parsing to get connection string import argparse @@ -93,6 +93,31 @@ vehicle.channels.overrides = {} print(" Channel overrides: %s" % vehicle.channels.overrides) +print("Define a channel override callback and register it") +result = {'value': -1} +vehicle.channels.overrides = {} +def channels_callback(vehicle, name, channels): + print("channels['3'] == %d\n" % channels['3']) + result['value'] = channels['3'] + +vehicle.add_attribute_listener('channels', channels_callback) +vehicle.channels.overrides = {'3': 55} + +print("Wait for channel callback to be called") +i = 5 +while result['value'] != 55 and i>0: + time.sleep(.5) + i -= 1 + +if result['value'] != -1: + print("Value changed") +if result['value'] == 55: + print("Value correct") +else: + print("Value incorrect (%d)" % (result['value'],)) +vehicle.remove_attribute_listener('channels', channels_callback) +print("Unregistered") + #Close vehicle object before exiting script print("\nClose vehicle object") vehicle.close() diff --git a/examples/create_attribute/my_vehicle.py b/examples/create_attribute/my_vehicle.py index 01f12cea1..1c97c47b7 100644 --- a/examples/create_attribute/my_vehicle.py +++ b/examples/create_attribute/my_vehicle.py @@ -53,8 +53,8 @@ def __str__(self): class MyVehicle(Vehicle): - def __init__(self, *args): - super(MyVehicle, self).__init__(*args) + def __init__(self, *args, **kwargs): + super(MyVehicle, self).__init__(*args, **kwargs) # Create an Vehicle.raw_imu object with initial values set to None. self._raw_imu = RawIMU() diff --git a/examples/multivehicle/README.md b/examples/multivehicle/README.md new file mode 100644 index 000000000..8541af363 --- /dev/null +++ b/examples/multivehicle/README.md @@ -0,0 +1,58 @@ +These are some (hopefully short-lived) intructions on how to get multiple vehicles running in dronekit-python. These instructions assume you are running under Linux, but with minimal modification should run on other operating systems. + +Please note that these instructions will significantly change your environment. Unless you are quite familiar with how your build environment is put together you may wish to do this in a separate stand-alone environment. + +1. Run peterbarker's _source-system-filtering branch_ of dronekit-python + + Given that this README file exists within that branch, this should not be too much of a problem. + + The branch exists in this fork of dronekit-python: can be cloned from ssh://git@github.com/peterbarker/dronekit-python.git + ``` + DRONEKIT_TOP=$HOME # e.g. + cd $DRONEKIT_TOP/dronekit-python + git remote add peterbarker ssh://git@github.com/peterbarker/dronekit-python.git + git fetch peterbarker + git checkout peterbarker/source-system-filtering + ``` + +2. Run the _mavsource_ branch of pymavlink + + This branch introduces an object into pymavlink which filters messages to go to and come from a single system (e.g. your drone). Without this object, the abstractions in pymavlink do not allow manipulation of multiple vehicles suitable for dronekit-python. + + ``` + ARDUPILOT_HOME=$HOME/ardupilot # e.g. + cd $ARDUPILOT_HOME/modules/mavlink/pymavlink + git remote add peterbarker https://github.com/peterbarker/pymavlink + git fetch peterbarker + git checkout peterbarker/mavsource + python setup.py build install --user --force + ``` + + Note that in the above shell code we are re-using a pymavlink + repository present in a buildable ArduPilot repository. You can + instead clone the pymavlink tree directly. + +5. Run the multivehicle sample program: + ``` + DRONEKIT_TOP=$HOME # e.g. + export PYTHONPATH=$DRONEKIT_TOP/dronekit-python + cd $DRONEKIT_TOP/dronekit-python/examples/multivehicle + python multivehicle.py --simulation-count 3 --extra-connection udpout:localhost:9432 + ``` + +6. Connect a GCS to port 9432 + + This varies by GCS. With *MAVProxy* you might run this: + ``` + mavproxy.py --master udpin:localhost:9432 + ``` + + With *GQGroundControl* you might try this: + ``` + - run qgroundcontrol + - Hamburger -> Comm Links + - Add (near the bottom of the screen) + - Type: UDP + - Listening port 9432 + - You should see both vehicles appear at this point + ``` diff --git a/examples/multivehicle/mavlink_hub.py b/examples/multivehicle/mavlink_hub.py new file mode 100644 index 000000000..43de2408f --- /dev/null +++ b/examples/multivehicle/mavlink_hub.py @@ -0,0 +1,121 @@ +from __future__ import print_function + +from pymavlink import mavutil +import time +import threading + +class Connection(): + def __init__(self, addr): + self.addr = addr + self._active = False + self.last_packet_received = 0 + self.last_connection_attempt = 0 + + def open(self): + try: + print("Opening connection to %s" % (self.addr,)) + self.mav = mavutil.mavlink_connection(self.addr) + self._active = True + self.last_packet_received = time.time() # lie + + except Exception as e: + print("Connection to (%s) failed: %s" % (self.addr, str(e))) + + def close(self): + self.mav.close() + self._active = False + + def active(self): + return self._active + +class MAVLinkHub(): + def __init__(self, addrs): + self.addrs = addrs + self.conns = [] + self.connection_maintenance_target_should_live = True + self.inactivity_timeout = 10 + self.reconnect_interval = 5 + + def maintain_connections(self): + now = time.time() + for conn in self.conns: + if not conn.active(): + continue + if now - conn.last_packet_received > self.inactivity_timeout: + print("Connection (%s) timed out" % (conn.addr,)) + conn.close() + for conn in self.conns: + if not conn.active(): + if now - conn.last_connection_attempt > self.reconnect_interval: + conn.last_connection_attempt = now + conn.open() +# else: +# print("Connection %s OK" % (conn.addr)) + time.sleep(0.1) + + def create_connections(self): + for addr in self.addrs: + print("Creating connection (%s)" % addr) + self.conns.append(Connection(addr)) + + def handle_messages(self): + now = time.time() + packet_received = False + for conn in self.conns: + if not conn.active(): + continue + m = None + try: + m = conn.mav.recv_msg() + except Exception as e: + print("Exception receiving message on addr(%s): %s" % (str(conn.addr),str(e))) + conn.close() + + if m is not None: + conn.last_packet_received = now + packet_received = True +# print("Received message (%s) on connection %s from src=(%d/%d)" % (str(m), conn.addr, m.get_srcSystem(), m.get_srcComponent(),)) + for j in self.conns: + if not j.active(): + continue + if j.addr == conn.addr: + continue +# print(" Resending message on connection %s" % (j.addr,)) + j.mav.write(m.get_msgbuf()) + if not packet_received: + time.sleep(0.01) + + def init(self): + self.create_connections() + self.create_connection_maintenance_thread() + + def loop(self): + self.handle_messages() + + def create_connection_maintenance_thread(self): + '''create and start helper threads and the like''' + def connection_maintenance_target(): + while self.connection_maintenance_target_should_live: + self.maintain_connections() + time.sleep(0.1) + connection_maintenance_thread = threading.Thread(target=connection_maintenance_target) + connection_maintenance_thread.start() + + def run(self): + self.init() + +# print("Entering main loop") + while True: + self.loop() + +if __name__ == '__main__': + + from optparse import OptionParser + parser = OptionParser("mavlink_hub.py [options]") + (opts, args) = parser.parse_args() + + hub = MAVLinkHub(args) + if len(args) == 0: + print("Insufficient arguments") + sys.exit(1) + hub.run() diff --git a/examples/multivehicle/multivehicle.py b/examples/multivehicle/multivehicle.py new file mode 100644 index 000000000..5a7ac2a74 --- /dev/null +++ b/examples/multivehicle/multivehicle.py @@ -0,0 +1,247 @@ +from __future__ import print_function + +""" +multivehicle.py: Example demonstrating control of multiple vehicles on one connection + +Full documentation is provided at http://python.dronekit.io/examples/multivehicle.html +""" + +from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command +import time +import math +from pymavlink import mavutil +import threading + +import dronekit +import mavlink_hub + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates controlling multiple vehicles.') +parser.add_argument('--connect', + help="vehicle connection target string. If not specified, SITL instances automatically started and used.") +parser.add_argument('--simulation-count', + help="number of simulated vehicles to create.", + default=2) +parser.add_argument('--extra-connection', + help="extra MAVLink connections to make.") +args = parser.parse_args() + +connection_string = args.connect + +sitls = [] + +hub_thread = None +target_systems = [] + +if connection_string: + # Create a MAVLink connection: + mav = dronekit.mavlink.MAVConnection(connection_string) + target_systems = [1] +else: + simulation_count = int(args.simulation_count) + hub_connection_strings = [] + + # start many dronekit-sitl processes + port = 5760 # massive assumption + for i in range(0,simulation_count): + print("Creating simulator (SITL) %d" % (i,)) + from dronekit_sitl import SITL + sitl = SITL() + sitl.download('copter', '3.3', verbose=True) + lat = -35.363261 + i*0.00008 + sitl_args = ['-I' + str(i), '--model', 'quad', '--home='+str(lat)+',149.165230,584,353'] + sitls.append([sitl, sitl_args]) + hub_connection_strings.append('tcp:127.0.0.1:' + str(port)) + port += 10 # *cough* + + # start the SITLs one at a time, giving each a unique SYSID_THISMAV + def change_sysid_target(i, new_sysid, connection_string): + print("%d: Launching SITL (%s)" % (i,str(sitls[i][1]))) + sitls[i][0].launch(sitls[i][1], await_ready=True) + print("%d: Connecting to its vehicle 1" % (i,)) + vehicle = dronekit.connect(connection_string, wait_ready=True, target_system=1) + while vehicle.parameters["SYSID_THISMAV"] != new_sysid: + print("%d: Resetting its SYID_THISMAV to %d" % (i, new_sysid,)) + vehicle.parameters["SYSID_THISMAV"] = new_sysid + time.sleep(0.1) + print("%d: Allowing time for parameter write" % (i,)) + time.sleep(5) + print("%d: Stop" % (i,)) + sitls[i][0].stop() + vehicle.disconnect() + + change_sysid_threads = [] + for i in range(0,len(sitls)): + new_sysid = len(sitls)-i+1 + change_sysid_threads.append(threading.Thread(target=change_sysid_target, + args=(i,new_sysid, hub_connection_strings[i]))) + change_sysid_threads[-1].start() + target_systems.append(new_sysid) + time.sleep(1) # more race conditions in pymavlink?! +# mav.remove_message_listener(vehicle) + for thread in change_sysid_threads: + print("Waiting for thread...") + thread.join() + + print("Sleeping a little to let SITLs go away...") + time.sleep(2) + print("Launching SITLs") + for i in range(0,len(sitls)): + sitls[i][0].launch(sitls[i][1], await_ready=True, restart=True, use_saved_data=True, wd=sitls[i][0].wd) + + # create another connection so a GCS can be connected for visualisation + if args.extra_connection: + hub_connection_strings.append(args.extra_connection) + + # dronekit-python (us!) port: + connection_string = "udpout:localhost:2345" + hub_connection_strings.append("udpin:localhost:2345") + + hub_should_quit = False + def mavlink_hub_target(): + print("Hub thread starting") + hub = mavlink_hub.MAVLinkHub(hub_connection_strings) + hub.init() + while not hub_should_quit: + hub.loop() + print("Hub quitting") + hub.connection_maintenance_target_should_live = False + + print("Starting mavlink_hub thread") + hub_thread = threading.Thread(target=mavlink_hub_target) + hub_thread.start() + + # Create a MAVLink connection: + print("Attempting connect to (%s)" % (connection_string,)) + mav = dronekit.mavlink.MAVConnection(connection_string) + print("Connected") + +vehicles = [None] * len(target_systems) +# Connect to the Vehicle +def vehicle_connect_target(mav, id, offset): + vehicle = dronekit.connect(mav, wait_ready=True, target_system=id) + vehicles[offset] = vehicle + +offset = 0 +connect_threads = [] +for id in target_systems: + print('Connecting to vehicle with system ID (%d)' % id) + connect_threads.append(threading.Thread(target=vehicle_connect_target, + args=(mav,id,offset))) + connect_threads[-1].start() + offset += 1 + time.sleep(1) # mav is not thread safe?! + +for thread in connect_threads: + print("Waiting for connect thread...") + thread.join() + +def dump_vehicle_state(vehicle): + print(" Autopilot Firmware version: %s" % vehicle.version) + print(" Major version number: %s" % vehicle.version.major) + print(" Minor version number: %s" % vehicle.version.minor) + print(" Patch version number: %s" % vehicle.version.patch) + print(" Release type: %s" % vehicle.version.release_type()) + print(" Release version: %s" % vehicle.version.release_version()) + print(" Stable release?: %s" % vehicle.version.is_stable()) + + +for vehicle in vehicles: + dump_vehicle_state(vehicle) + +mav_lock = threading.Lock() # FIXME; move locking into MAVSystem + +def arm_and_takeoff(vehicle, aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + + print("Basic pre-arm checks") + # Don't try to arm until autopilot is ready + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + # Copter should arm in GUIDED mode + while vehicle.mode != 'GUIDED': + print("Setting mode GUIDED") + mav_lock.acquire() + vehicle.mode = VehicleMode("GUIDED") + mav_lock.release() + time.sleep(0.5) + + # Confirm vehicle armed before attempting to take off + while not vehicle.armed: + print("Arming motors") + mav_lock.acquire() + vehicle.armed = True + mav_lock.release() + time.sleep(0.5) + + print("Taking off!") + mav_lock.acquire() + vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude + mav_lock.release() + + # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command + # after Vehicle.simple_takeoff will execute immediately). + while True: + print(" Altitude: ", vehicle.location.global_relative_frame.alt) + #Break and return from function just below target altitude. + if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: + print("Reached target altitude") + break + time.sleep(1) + +def vehicle_launcher_target(i): + arm_and_takeoff(vehicles[i], 10) + +launcher_threads = [] +for i in range(0,len(vehicles)): + print("Launching Vehicle %d:" % (target_systems[i],)) + launcher_threads.append(threading.Thread(target=vehicle_launcher_target, + args=(i,))) + launcher_threads[-1].start() +for thread in launcher_threads: + print("Waiting for launcher thread...") + thread.join() + +speed = 3 +for i in range(0,len(vehicles)): + print("Set default/target airspeed to %d on vehicle %d (%s)" % (target_systems[i],speed, str(target_systems[i]))) + vehicles[i].airspeed = speed + speed += 1 + +for i in range(0,len(vehicles)): + print("vehicle %d going towards first point for 30 seconds ..." % (target_systems[i],)) + point = LocationGlobalRelative(vehicles[i].location.global_frame.lat, + vehicles[i].location.global_frame.lon + 0.0050, + 20) + vehicles[i].simple_goto(point) + +# sleep so we can see the change in map +def watch_things_for_a_while(duration=30): + start = time.time() + + while time.time() - start < duration: + for i in range(0,len(vehicles)): + vehicle = vehicles[i] + print("Vehicle %d (%s) Lat=%f Lon=%f" % (target_systems[i], vehicle.mode, vehicle.location.global_frame.lat, vehicle.location.global_frame.lon)) + time.sleep(1) + +watch_things_for_a_while() + +for i in range(0, len(vehicles)): + while vehicles[i].mode != "RTL": + print("Setting returning to Launch - vehicle %d" % (target_systems[i],)) + vehicles[i].mode = VehicleMode("RTL") + time.sleep(0.1) + +watch_things_for_a_while(duration=30) + +print("All done") + +if hub_thread is not None: + hub_should_quit = True + hub_thread.join() diff --git a/examples/rc_override_flight/rc_override_flight.py b/examples/rc_override_flight/rc_override_flight.py new file mode 100644 index 000000000..296a801e0 --- /dev/null +++ b/examples/rc_override_flight/rc_override_flight.py @@ -0,0 +1,45 @@ +#!/usr/bin/python + +import dronekit +import dronekit_sitl +import time + + +lat = 49.2778638 +lon = -123.0633418 + +sitl = dronekit_sitl.SITL() +sitl.download('copter', '3.3', verbose=True) +sitl_args = ['-I0', '--model', 'quad', '--home={0},{1},584,353'.format(lat, lon)] +sitl.launch(sitl_args, await_ready=True, restart=True) +connection_string = 'tcp:127.0.0.1:5760' + + +vehicle = dronekit.connect(connection_string, wait_ready=True) + +# Don't let the user try to arm until autopilot is ready +while not vehicle.is_armable: + print(" Waiting for vehicle to initialise... (GPS={0}, Battery={1})".format(vehicle.gps_0, vehicle.battery)) + time.sleep(1) + +# Set vehicle mode +desired_mode = 'STABILIZE' +while vehicle.mode != desired_mode: + vehicle.mode = dronekit.VehicleMode(desired_mode) + time.sleep(0.5) + +while not vehicle.armed: + print("Arming motors") + vehicle.armed = True + time.sleep(0.5) + +while True: + vehicle.channels.overrides[3] = 2000 + print " Ch3 override: %s" % vehicle.channels.overrides[3] + + if vehicle.location.global_relative_frame.alt >= 140: + print('Reached target altitude: {0:.2f}m'.format(vehicle.location.global_relative_frame.alt)) + break + else: + print("Altitude: {0:.2f}m".format(vehicle.location.global_relative_frame.alt)) + time.sleep(0.5)