From 0d77e600de0a97afe887b2b2fa9d864e959f9dc7 Mon Sep 17 00:00:00 2001 From: glemero Date: Thu, 23 Feb 2017 12:30:42 +0100 Subject: [PATCH 01/99] fix missing ** operator --- dronekit/mavlink.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index dd2f0d131..b47f67fed 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -140,7 +140,7 @@ def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_nati def newsendfn(mavmsg, **kwargs): self.fix_targets(mavmsg) - return sendfn(mavmsg, kwargs) + return sendfn(mavmsg, **kwargs) self.master.mav.send = newsendfn From 270e9d7502e256c4182506591bb9a86541540a4a Mon Sep 17 00:00:00 2001 From: glemero Date: Fri, 3 Mar 2017 12:56:59 +0100 Subject: [PATCH 02/99] adding *args to send method in case pymavlink modifies its send method signature --- dronekit/mavlink.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index b47f67fed..f5f3cf38d 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -138,9 +138,9 @@ def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_nati # Monkey-patch MAVLink object for fix_targets. sendfn = self.master.mav.send - def newsendfn(mavmsg, **kwargs): + def newsendfn(mavmsg, *args, **kwargs): self.fix_targets(mavmsg) - return sendfn(mavmsg, **kwargs) + return sendfn(mavmsg, *args, **kwargs) self.master.mav.send = newsendfn From 12e18a5dd39fd24295bb730eca0f32e988f56b1a Mon Sep 17 00:00:00 2001 From: cclauss Date: Tue, 18 Apr 2017 19:22:36 +0200 Subject: [PATCH 03/99] Step up testing to Python 2.7.13 and 3.6.0 (#702) * Step up testing to Python 3.6 * Python 2.7.13 and 3.6.0 * Python 2.7.13 * allow_failures: python: 3.6 --- .travis.yml | 6 ++++-- circle.yml | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index b8495e401..b143309cb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,8 +4,8 @@ env: - SITL_RATE=200 python: - - "2.7" - - "3.5" + - 2.7.13 + - 3.6 install: - 'pip install -r requirements.txt' @@ -29,6 +29,8 @@ notifications: on_start: never matrix: + allow_failures: + - python: 3.6 fast_finish: true branches: diff --git a/circle.yml b/circle.yml index 5ee47fc59..2e9e6a804 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: post: - - pyenv global 2.7.10 3.5.0 + - pyenv global 2.7.13 3.6.0 environment: SITL_SPEEDUP: 10 SITL_RATE: 200 From 7604bd976088dc5e7de6979851890256c172d409 Mon Sep 17 00:00:00 2001 From: Will Silva Date: Tue, 18 Apr 2017 10:56:57 -0700 Subject: [PATCH 04/99] add support for a logger function in errprinter (#681) * add support for a logger function in errprinter * this enables other software to monkey patch the logger function to capture dronekit output and exceptions * moved print to stderr to logger function * monkey patching logger will replace the print to stderr functionality instead of supplement it --- dronekit/util.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dronekit/util.py b/dronekit/util.py index f5800985b..081ffd2be 100644 --- a/dronekit/util.py +++ b/dronekit/util.py @@ -3,5 +3,8 @@ def errprinter(*args): + logger(*args) + +def logger(*args): print(*args, file=sys.stderr) sys.stderr.flush() From aa6ae753f992ea79d3d4cf63a490194ec8d361b0 Mon Sep 17 00:00:00 2001 From: Will Silva Date: Tue, 18 Apr 2017 11:01:16 -0700 Subject: [PATCH 05/99] =?UTF-8?q?adds=20a=20method=20to=20LocationLocal=20?= =?UTF-8?q?that=20returns=20distance=20from=20home,=20in=20me=E2=80=A6=20(?= =?UTF-8?q?#679)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * adds a method to LocationLocal that returns distance from home, in meters * Return 3D distance to home if `down` is known, otherwise return 2D distance * also, rename `distance` to `distance_home` --- dronekit/__init__.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 7d98364f4..a11b9eb50 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -184,6 +184,17 @@ def __init__(self, north, east, down): def __str__(self): return "LocationLocal:north=%s,east=%s,down=%s" % (self.north, self.east, self.down) + def distance_home(self): + """ + Distance away from home, in meters. Returns 3D distance if `down` is known, otherwise 2D distance. + """ + + if self.north is not None and self.east is not None: + if self.down is not None: + return math.sqrt(self.north**2 + self.east**2 + self.down**2) + else: + return math.sqrt(self.north**2 + self.east**2) + class GPSInfo(object): """ From 9f96bfc4e49d40081dad78e2b225d40a0d745236 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Fri, 21 Apr 2017 10:53:10 +1000 Subject: [PATCH 06/99] requirements: any pymavlink gte 2.0.6 --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 7a7076abe..c71a2d161 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -pymavlink==2.0.6 +pymavlink>=2.0.6 monotonic==1.2 future==0.15.2 nose==1.3.7 From 62eb6880393065558293f737bd4c40231e327db7 Mon Sep 17 00:00:00 2001 From: Amilcar Lucas Date: Fri, 21 Apr 2017 19:52:23 +0200 Subject: [PATCH 07/99] Fix windows installer, it is called dronekit, not droneapi. (#708) Improve documentation a bit --- windows/{droneapiWinBuild.bat => dronekitWinBuild.bat} | 3 ++- windows/{droneapi_installer.iss => dronekit_installer.iss} | 0 2 files changed, 2 insertions(+), 1 deletion(-) rename windows/{droneapiWinBuild.bat => dronekitWinBuild.bat} (67%) rename windows/{droneapi_installer.iss => dronekit_installer.iss} (100%) diff --git a/windows/droneapiWinBuild.bat b/windows/dronekitWinBuild.bat similarity index 67% rename from windows/droneapiWinBuild.bat rename to windows/dronekitWinBuild.bat index 1344267f3..95c8a79bb 100644 --- a/windows/droneapiWinBuild.bat +++ b/windows/dronekitWinBuild.bat @@ -1,5 +1,6 @@ rem build the standalone Dronekit.exe for Windows. -rem This assumes Python is installed in C:\Python27 +rem This assumes Python2 is installed in C:\Python27 +rem This assumes Inno Setup 5 is installed in C:\Program Files (x86)\Inno Setup 5 SETLOCAL enableextensions rem get the version diff --git a/windows/droneapi_installer.iss b/windows/dronekit_installer.iss similarity index 100% rename from windows/droneapi_installer.iss rename to windows/dronekit_installer.iss From 4d05c05363cf2300ddcc2b60af729f66c8f18fd4 Mon Sep 17 00:00:00 2001 From: Amilcar Lucas Date: Fri, 21 Apr 2017 19:53:19 +0200 Subject: [PATCH 08/99] convert paratenter set value to single precision floating point number (the type used by low level mavlink messages) before sending/comparing it (#707) This fixes bougus "timeout setting parameter x to y" messages when the passed double value and it's single representation differ --- dronekit/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index a11b9eb50..ad0baa045 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -45,6 +45,7 @@ import types import threading import math +import struct import copy import collections from pymavlink.dialects.v10 import ardupilotmega @@ -2433,7 +2434,8 @@ def set(self, name, value, retries=3, wait_ready=False): # instead just wait until the value itself was changed name = name.upper() - value = float(value) + # convert to single precision floating point number (the type used by low level mavlink messages) + value = float(struct.unpack('f', struct.pack('f', value))[0]) success = False remaining = retries while True: From c633a5ca514ac6464a00814f578237e031fef486 Mon Sep 17 00:00:00 2001 From: cclauss Date: Fri, 21 Apr 2017 20:35:06 +0200 Subject: [PATCH 09/99] Python 3: define basestring, use bytes.decode() (#705) * Run flake8 tests against both Python 2 and 3 * Python 3: from past.builtins import basestring * Python 3: from __future__ import print_function * Update simple_goto.py * flake8 --max-line-length=127 * Python 3: from __future__ import print_function * Separate flak8 run just for syntax errors --- .travis.yml | 20 ++++++-- dronekit/__init__.py | 34 +++++++------ examples/drone_delivery/drone_delivery.py | 58 ++++++++++------------ examples/simple_goto/simple_goto.py | 60 ++++++++++++----------- 4 files changed, 92 insertions(+), 80 deletions(-) diff --git a/.travis.yml b/.travis.yml index b143309cb..cc7d067ef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,5 @@ +language: python + env: global: - SITL_SPEEDUP=10 @@ -7,18 +9,26 @@ python: - 2.7.13 - 3.6 +before_install: + - pip install --upgrade pip + install: - - 'pip install -r requirements.txt' + - pip install -r requirements.txt + - pip install flake8 + +before_script: + # --exit-zero means that flake8 will not stop the build + # 127 characters is the width of a GitHub editor + - flake8 . --count --exit-zero --max-line-length=127 --select=E999 --statistics # syntax errors + - flake8 . --count --exit-zero --max-line-length=127 --statistics script: - - 'nosetests --debug=nose,nose.importer --debug-log=nose_debug -svx dronekit.test.unit' - - 'nosetests --debug=nose,nose.importer --debug-log=nose_debug -svx dronekit.test.sitl' + - nosetests --debug=nose,nose.importer --debug-log=nose_debug -svx dronekit.test.unit + - nosetests --debug=nose,nose.importer --debug-log=nose_debug -svx dronekit.test.sitl git: depth: 10 -language: python - notifications: email: false webhooks: diff --git a/dronekit/__init__.py b/dronekit/__init__.py index ad0baa045..9a573c9e1 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -31,23 +31,26 @@ """ from __future__ import print_function -import monotonic -import time -import socket -import sys +import collections +import copy +import math import os +import struct import platform -import re -from dronekit.util import errprinter -from pymavlink import mavutil, mavwp from queue import Queue, Empty +import re +import socket +import sys +import threading from threading import Thread +import time import types -import threading -import math -import struct -import copy -import collections + +import monotonic +from past.builtins import basestring +from dronekit.util import errprinter + +from pymavlink import mavutil, mavwp from pymavlink.dialects.v10 import ardupilotmega @@ -88,7 +91,8 @@ def __init__(self, pitch, yaw, roll): self.roll = roll def __str__(self): - return "Attitude:pitch=%s,yaw=%s,roll=%s" % (self.pitch, self.yaw, self.roll) + fmt = '{}:pitch={pitch},yaw={yaw},roll={roll}' + return fmt.format(self.__class__.__name__, **vars(self)) class LocationGlobal(object): @@ -2747,7 +2751,7 @@ def __len__(self): def __getitem__(self, index): if isinstance(index, slice): - return [self[ii] for ii in xrange(*index.indices(len(self)))] + return [self[ii] for ii in range(*index.indices(len(self)))] elif isinstance(index, int): item = self._vehicle._wploader.wp(index + 1) if not item: @@ -2835,7 +2839,7 @@ def connect(ip, @vehicle.on_message('STATUSTEXT') def listener(self, name, m): - status_printer(re.sub(r'(^|\n)', '>>> ', m.text.rstrip())) + status_printer(re.sub(r'(^|\n)', '>>> ', m.text.decode('utf-8').rstrip())) if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) diff --git a/examples/drone_delivery/drone_delivery.py b/examples/drone_delivery/drone_delivery.py index db2229784..10848877c 100644 --- a/examples/drone_delivery/drone_delivery.py +++ b/examples/drone_delivery/drone_delivery.py @@ -3,39 +3,39 @@ """ © Copyright 2015-2016, 3D Robotics. -drone_delivery.py: +drone_delivery.py: A CherryPy based web application that displays a mapbox map to let you view the current vehicle position and send the vehicle commands to fly to a particular latitude and longitude. Full documentation is provided at http://python.dronekit.io/examples/drone_delivery.html """ +from __future__ import print_function import os import simplejson import time -from pymavlink import mavutil + from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative import cherrypy -from cherrypy.process import wspbus, plugins from jinja2 import Environment, FileSystemLoader -#Set up option parsing to get connection string -import argparse +# Set up option parsing to get connection string +import argparse parser = argparse.ArgumentParser(description='Creates a CherryPy based web application that displays a mapbox map to let you view the current vehicle position and send the vehicle commands to fly to a particular latitude and longitude. Will start and connect to SITL if no connection string specified.') -parser.add_argument('--connect', - help="vehicle connection target string. If not specified, SITL is automatically started and used.") +parser.add_argument('--connect', + help="vehicle connection target string. If not specified, SITL is automatically started and used.") args = parser.parse_args() -connection_string=args.connect +connection_string = args.connect -#Start SITL if no connection string specified +# Start SITL if no connection string specified if not connection_string: import dronekit_sitl sitl = dronekit_sitl.start_default() connection_string = sitl.connection_string() -local_path=os.path.dirname(os.path.abspath(__file__)) -print "local path: %s" % local_path +local_path = os.path.dirname(os.path.abspath(__file__)) +print("local path: %s" % local_path) cherrypy_conf = { @@ -89,11 +89,10 @@ def takeoff(self): self._log("Taking off") self.vehicle.simple_takeoff(30.0) - def arm(self, value=True): if value: self._log('Waiting for arming...') - self.vehicle.armed = True + self.vehicle.armed = True while not self.vehicle.armed: time.sleep(.1) else: @@ -104,11 +103,9 @@ def _run_server(self): # Start web server if enabled cherrypy.tree.mount(DroneDelivery(self), '/', config=cherrypy_conf) - cherrypy.config.update({ - 'server.socket_port': 8080, - 'server.socket_host': '0.0.0.0', - 'log.screen': None - }) + cherrypy.config.update({'server.socket_port': 8080, + 'server.socket_host': '0.0.0.0', + 'log.screen': None}) print('''Server is bound on all addresses, port 8080 You may connect to it using your web broser using a URL looking like this: @@ -153,28 +150,26 @@ def location_callback(self, vehicle, name, location): self.current_location = location.global_relative_frame def _log(self, message): - print "[DEBUG]: {0}".format(message) + print("[DEBUG]: {0}".format(message)) + class Templates: def __init__(self, home_coords): self.home_coords = home_coords self.options = self.get_options() - self.environment = Environment(loader=FileSystemLoader( local_path + '/html')) + self.environment = Environment(loader=FileSystemLoader(local_path + '/html')) def get_options(self): - return { - 'width': 670, + return {'width': 670, 'height': 470, 'zoom': 13, 'format': 'png', 'access_token': 'pk.eyJ1Ijoia2V2aW4zZHIiLCJhIjoiY2lrOGoxN2s2MDJzYnR6a3drbTYwdGxmMiJ9.bv5u7QgmcJd6dZfLDGoykw', 'mapid': 'kevin3dr.n56ffjoo', 'home_coords': self.home_coords, - 'menu': [ - {'name': 'Home', 'location': '/'}, - {'name': 'Track', 'location': '/track'}, - {'name': 'Command', 'location': '/command'} - ], + 'menu': [{'name': 'Home', 'location': '/'}, + {'name': 'Track', 'location': '/track'}, + {'name': 'Command', 'location': '/command'}], 'current_url': '/', 'json': '' } @@ -198,9 +193,10 @@ def command(self, current_coords): return self.get_template('command') def get_template(self, file_name): - template = self.environment.get_template( file_name + '.html') + template = self.environment.get_template(file_name + '.html') return template.render(options=self.options) + class DroneDelivery(object): def __init__(self, drone): self.drone = drone @@ -230,13 +226,13 @@ def track(self, lat=None, lon=None): # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) -print 'Launching Drone...' +print('Launching Drone...') Drone().launch() -print 'Waiting for cherrypy engine...' +print('Waiting for cherrypy engine...') cherrypy.engine.block() if not args.connect: diff --git a/examples/simple_goto/simple_goto.py b/examples/simple_goto/simple_goto.py index b38e3b2d7..9fe54ee2f 100644 --- a/examples/simple_goto/simple_goto.py +++ b/examples/simple_goto/simple_goto.py @@ -10,22 +10,23 @@ Full documentation is provided at http://python.dronekit.io/examples/simple_goto.html """ -from dronekit import connect, VehicleMode, LocationGlobalRelative +from __future__ import print_function import time +from dronekit import connect, VehicleMode, LocationGlobalRelative -#Set up option parsing to get connection string -import argparse +# Set up option parsing to get connection string +import argparse parser = argparse.ArgumentParser(description='Commands vehicle using vehicle.simple_goto.') -parser.add_argument('--connect', - help="Vehicle connection target string. If not specified, SITL automatically started and used.") +parser.add_argument('--connect', + help="Vehicle connection target string. If not specified, SITL automatically started and used.") args = parser.parse_args() connection_string = args.connect sitl = None -#Start SITL if no connection string specified +# Start SITL if no connection string specified if not connection_string: import dronekit_sitl sitl = dronekit_sitl.start_default() @@ -33,7 +34,7 @@ # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) @@ -42,62 +43,63 @@ def arm_and_takeoff(aTargetAltitude): Arms vehicle and fly to aTargetAltitude. """ - print "Basic pre-arm checks" + 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..." + print(" Waiting for vehicle to initialise...") time.sleep(1) - - print "Arming motors" + print("Arming motors") # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") - vehicle.armed = True + vehicle.armed = True # Confirm vehicle armed before attempting to take off - while not vehicle.armed: - print " Waiting for arming..." + while not vehicle.armed: + print(" Waiting for arming...") time.sleep(1) - print "Taking off!" - vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude + print("Taking off!") + vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude - # Wait until the vehicle reaches a safe height before processing the goto (otherwise the command - # after Vehicle.simple_takeoff will execute immediately). + # 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" + 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) + arm_and_takeoff(10) -print "Set default/target airspeed to 3" +print("Set default/target airspeed to 3") vehicle.airspeed = 3 -print "Going towards first point for 30 seconds ..." +print("Going towards first point for 30 seconds ...") point1 = LocationGlobalRelative(-35.361354, 149.165218, 20) vehicle.simple_goto(point1) # sleep so we can see the change in map time.sleep(30) -print "Going towards second point for 30 seconds (groundspeed set to 10 m/s) ..." +print("Going towards second point for 30 seconds (groundspeed set to 10 m/s) ...") point2 = LocationGlobalRelative(-35.363244, 149.168801, 20) vehicle.simple_goto(point2, groundspeed=10) # sleep so we can see the change in map time.sleep(30) -print "Returning to Launch" +print("Returning to Launch") vehicle.mode = VehicleMode("RTL") -#Close vehicle object before exiting script -print "Close vehicle object" +# Close vehicle object before exiting script +print("Close vehicle object") vehicle.close() # Shut down simulator if it was started. -if sitl is not None: +if sitl: sitl.stop() From 3d6479a42ba8601ef9a5c771a85fa090336c9928 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ram=C3=B3n=20Roche?= Date: Fri, 21 Apr 2017 11:42:04 -0700 Subject: [PATCH 10/99] bump 2.9.1 --- CHANGELOG.md | 15 +++++++++++++++ docs/about/github_latest_release.txt | 22 ++++++++++++++++++++++ setup.py | 2 +- 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f97d9e763..21331ab2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog +## Version 2.9.1 (2017-04-21) + +### Improvements +* home locatin notifications +* notify ci status to gitter +* basic python 3 support +* isolated logger function so implementers can override +* rename windows installer + +### Cleanup +* removed legacy cloud integrations + +### Bug Fixes +* fix missing ** operator for pymavlink compatibility + ## Version 2.9.0 (2016-08-29) ### Bug Fixes diff --git a/docs/about/github_latest_release.txt b/docs/about/github_latest_release.txt index a644a3bd7..9a67880ee 100644 --- a/docs/about/github_latest_release.txt +++ b/docs/about/github_latest_release.txt @@ -3,6 +3,28 @@ Changelog ========= +Version 2.9.1 (2017-04-21) +-------------------------- + +Improvements +~~~~~~~~~~~~ + +- home locatin notifications +- notify ci status to gitter +- basic python 3 support +- isolated logger function so implementers can override +- rename windows installer + +Cleanup +~~~~~~~ + +- removed legacy cloud integrations + +Bug Fixes +~~~~~~~~~ + +- fix missing \*\* operator for pymavlink compatibility + Version 2.9.0 (2016-08-29) -------------------------- diff --git a/setup.py b/setup.py index 465743374..f9b215d5a 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ from setuptools import setup, Extension import platform -version = '2.9.0' +version = '2.9.1' setup(name='dronekit', zip_safe=True, From fa5e50c15827fb2a67624845fbe4f10701323ff2 Mon Sep 17 00:00:00 2001 From: cclauss Date: Fri, 7 Oct 2016 21:31:20 +0200 Subject: [PATCH 11/99] pymavlink==2.0.8 --- requirements.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements.txt b/requirements.txt index c71a2d161..432e11ef2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,6 @@ pymavlink>=2.0.6 -monotonic==1.2 -future==0.15.2 +monotonic>=1.3 +future>=0.15.2 nose==1.3.7 mock==2.0.0 dronekit-sitl==3.2.0 From ad9c438820708e645557162e8f2b82875a6665b1 Mon Sep 17 00:00:00 2001 From: "Dr.-Ing. Amilcar Do Carmo Lucas" Date: Mon, 13 Feb 2017 11:06:41 +0100 Subject: [PATCH 12/99] Ignore Visual studio file --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 7df502175..dec06d5da 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ build .idea *.pyc env +vs/.vs/dronekit-python/v14/*.suo From 5d2614f79092cc3ea03062a084579eb16577cd22 Mon Sep 17 00:00:00 2001 From: Jerry Lynch Date: Wed, 26 Apr 2017 21:08:40 -0400 Subject: [PATCH 13/99] fix BaseException.message deprecated in 2.6 and now an error in 3.x --- dronekit/mavlink.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index f5f3cf38d..7cff501df 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -182,7 +182,7 @@ def mavlink_thread_out(): errprinter('>>> mav send error:', e) break except APIException as e: - errprinter('>>> ' + str(e.message)) + errprinter('>>> ' + str(e)) self._alive = False self.master.close() self._death_error = e @@ -237,7 +237,7 @@ def mavlink_thread_in(): errprinter('>>> ' + str(e)) except APIException as e: - errprinter('>>> ' + str(e.message)) + errprinter('>>> ' + str(e)) self._alive = False self.master.close() self._death_error = e From 0cf17f8a6548d0c78452de471e6b81940af085e5 Mon Sep 17 00:00:00 2001 From: moobsen Date: Tue, 16 May 2017 13:46:31 +0200 Subject: [PATCH 14/99] Update README.md updated dead link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d93fc20cd..057eef556 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The API is primarily intended for use in onboard companion computers (to support ## Getting Started -The [Getting Started](http://python.dronekit.io/guide/getting_started.html) guide explains how to set up DroneKit on each of the supported platforms (Linux, Mac OSX, Windows) and how to write a script to connect to a vehicle (real or simulated). +The [Quick Start](http://python.dronekit.io/guide/quick_start.html) guide explains how to set up DroneKit on each of the supported platforms (Linux, Mac OSX, Windows) and how to write a script to connect to a vehicle (real or simulated). A basic script looks like this: From 5f6a6e7c2e8ba173b5c9d393be56d7792f4b1f9a Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 1 Jun 2017 17:50:42 +1000 Subject: [PATCH 15/99] Add play_tune() method on vehicle, example for same --- dronekit/__init__.py | 5 ++++ examples/play_tune/play_tune.py | 42 +++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 examples/play_tune/play_tune.py diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 9a573c9e1..0d6ab1d6b 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2146,6 +2146,11 @@ def send_capabilties_request(self, vehicle, name, m): capability_msg = vehicle.message_factory.command_long_encode(0, 0, mavutil.mavlink.MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, 0, 1, 0, 0, 0, 0, 0, 0) vehicle.send_mavlink(capability_msg) + def play_tune(self, tune): + '''Request an AUTOPILOT_VERSION packet''' + msg = self.message_factory.play_tune_encode(0, 0, tune) + self.send_mavlink(msg) + def wait_ready(self, *types, **kwargs): """ Waits for specified attributes to be populated from the vehicle (values are initially ``None``). diff --git a/examples/play_tune/play_tune.py b/examples/play_tune/play_tune.py new file mode 100644 index 000000000..df0995222 --- /dev/null +++ b/examples/play_tune/play_tune.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +© Copyright 2017, Peter Barker +play_tune.py: GUIDED mode "simple goto" example (Copter Only) + +Demonstrates how to play a custom tune on a vehicle using the vehicle's buzzer + +Full documentation is provided at http://python.dronekit.io/examples/play_tune.html +""" + +from __future__ import print_function +import time +from dronekit import connect + + +# Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Play tune on vehicle buzzer.') +parser.add_argument('--connect', + help="Vehicle connection target string. If not specified, SITL automatically started and used.") +parser.add_argument('--tune', type=str, help="tune to play", default="AAAA") +args = parser.parse_args() + +connection_string = args.connect +sitl = None + + +# Start SITL if no connection string specified +if not connection_string: + print("SITL doesn't do tunes?!") + import dronekit_sitl + sitl = dronekit_sitl.start_default() + connection_string = sitl.connection_string() + + +# Connect to the Vehicle +print('Connecting to vehicle on: %s' % connection_string) +vehicle = connect(connection_string, wait_ready=True) + +vehicle.play_tune(args.tune) From 07c3cd5ab93b041fd98e50b07073e04505d4a91a Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Mon, 19 Jun 2017 12:53:43 +1000 Subject: [PATCH 16/99] Improve diagnostics for heartbeat flight mode issues --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 0d6ab1d6b..68cf82c54 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1194,7 +1194,7 @@ def listener(self, name, m): self._autopilot_type = m.autopilot self._vehicle_type = m.type if self._is_mode_available(m.custom_mode, m.base_mode) == False: - raise APIException("mode %s not available on mavlink definition" % m.custom_mode) + raise APIException("mode (%s, %s) not available on mavlink definition" % (m.custom_mode, m.base_mode)) if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_PX4: self._flightmode = mavutil.interpret_px4_mode(m.base_mode, m.custom_mode) else: From e89084eb4ead9c9bd0c9ecadc65e9d566f160af4 Mon Sep 17 00:00:00 2001 From: mhefny Date: Thu, 29 Jun 2017 06:34:18 +0200 Subject: [PATCH 17/99] fixing altitude float --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 68cf82c54..d962956d7 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1983,7 +1983,7 @@ def simple_takeoff(self, alt=None): """ if alt is not None: altitude = float(alt) - if math.isnan(alt) or math.isinf(alt): + if math.isnan(altitude) or math.isinf(altitude): raise ValueError("Altitude was NaN or Infinity. Please provide a real number") self._master.mav.command_long_send(0, 0, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude) From 5cdd73a41998d9b342605351844def2bc0302c3e Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Wed, 14 Jun 2017 23:08:04 -0400 Subject: [PATCH 18/99] allow setting flight mode using a string value This modifies mode.setter so that we can write: vehicle.mode = 'LOITER' Rather than: vehicle.mode = VehicleMode('LOITER') --- dronekit/__init__.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index d962956d7..aec069bae 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1561,7 +1561,26 @@ def _is_mode_available(self, custommode_code, basemode_code=0): @property def mode(self): """ - This attribute is used to get and set the current flight mode (:py:class:`VehicleMode`). + This attribute is used to get and set the current flight mode. You + can specify the value as a :py:class:`VehicleMode`, like this: + + .. code-block:: python + + vehicle.mode = VehicleMode('LOITER') + + Or as a simple string: + + .. code-block:: python + + vehicle.mode = 'LOITER' + + If you are targeting ArduPilot you can also specify the flight mode + using a numeric value (this will not work with PX4 autopilots): + + .. code-block:: python + + # set mode to LOITER + vehicle.mode = 5 """ if not self._flightmode: return None @@ -1569,8 +1588,13 @@ def mode(self): @mode.setter def mode(self, v): + if isinstance(v, basestring): + v = VehicleMode(v) + if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_PX4: self._master.set_mode(v.name) + elif isinstance(v, int): + self._master.set_mode(v) else: self._master.set_mode(self._mode_mapping[v.name]) From ea252db8e73d5d499ca63e1c4b035db3b5641974 Mon Sep 17 00:00:00 2001 From: auturgy Date: Mon, 10 Jul 2017 23:05:37 +1000 Subject: [PATCH 19/99] Update requirements.txt update pymavlink --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 432e11ef2..b621f67c5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -pymavlink>=2.0.6 +pymavlink>=2.2.3 monotonic>=1.3 future>=0.15.2 nose==1.3.7 From 79b68eec98b0713ef302410c720dd2e852fc7387 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Mon, 24 Jul 2017 16:35:06 +1000 Subject: [PATCH 20/99] setup.py: bump pymavlink requirement to 2.2.3 to match requirements.txt --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index f9b215d5a..3824ee523 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ url='https://github.com/dronekit/dronekit-python', author='3D Robotics', install_requires=[ - 'pymavlink==2.0.6', + 'pymavlink>=2.2.3', 'monotonic==1.2', 'future==0.15.2' ], From 803ead0efa1dd33d8e5a83b743d5183182f0ff3f Mon Sep 17 00:00:00 2001 From: sanderux Date: Mon, 24 Jul 2017 01:05:38 +0200 Subject: [PATCH 21/99] Ignore heartbeats from groundstations --- dronekit/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index aec069bae..51c659ec4 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1189,6 +1189,9 @@ def listener(self, name, m): @self.on_message('HEARTBEAT') def listener(self, name, m): + # ignore groundstations + if m.type == mavutil.mavlink.MAV_TYPE_GCS: + return self._armed = (m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0 self.notify_attribute_listeners('armed', self.armed, cache=True) self._autopilot_type = m.autopilot @@ -1352,6 +1355,9 @@ def listener(_): @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() if self._heartbeat_timeout: From 92ee230792f7f3005556e2ad772d12bbd43f6684 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 27 Jul 2017 11:04:35 +1000 Subject: [PATCH 22/99] examples: vehicle_state no longer arms the vehicle --- examples/vehicle_state/vehicle_state.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index 4518533e1..c4d7d55c6 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -127,12 +127,12 @@ # If required, you can provide additional information about initialisation # using `vehicle.gps_0.fix_type` and `vehicle.mode.name`. -print "\nSet Vehicle.armed=True (currently: %s)" % vehicle.armed -vehicle.armed = True -while not vehicle.armed: - print " Waiting for arming..." - time.sleep(1) -print " Vehicle is armed: %s" % vehicle.armed +#print "\nSet Vehicle.armed=True (currently: %s)" % vehicle.armed +#vehicle.armed = True +#while not vehicle.armed: +# print " Waiting for arming..." +# time.sleep(1) +#print " Vehicle is armed: %s" % vehicle.armed # Add and remove and attribute callbacks @@ -250,7 +250,7 @@ def any_parameter_callback(self, attr_name, value): ## Reset variables to sensible values. print "\nReset vehicle attributes/parameters and exit" vehicle.mode = VehicleMode("STABILIZE") -vehicle.armed = False +#vehicle.armed = False vehicle.parameters['THR_MIN']=130 vehicle.parameters['THR_MID']=500 From 754ce6223dd26179045eaa394d5df0a5f787ebb2 Mon Sep 17 00:00:00 2001 From: cclauss Date: Mon, 4 Sep 2017 13:55:19 +0200 Subject: [PATCH 23/99] Define name `time_max` in sitl/test_110.py Without this change, a NameError is raised on line 50. --- dronekit/test/sitl/test_110.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dronekit/test/sitl/test_110.py b/dronekit/test/sitl/test_110.py index 8386ba0b2..9ab32c6c0 100644 --- a/dronekit/test/sitl/test_110.py +++ b/dronekit/test/sitl/test_110.py @@ -43,7 +43,8 @@ def armed_callback(vehicle, attribute, value): vehicle.armed = True # Wait for ACK. - wait_for(lambda : armed_callback.called, 10) + time_max = 10 + wait_for(lambda : armed_callback.called, time_max) # Ensure the callback was called. assert armed_callback.called > 0, "Callback should have been called within %d seconds" % (time_max,) From d8cca696b5b96a344d6f466662b52d2da253cbbf Mon Sep 17 00:00:00 2001 From: cclauss Date: Thu, 14 Sep 2017 13:22:45 +0200 Subject: [PATCH 24/99] Modernize Python 2 code to get ready for Python 3 --- .travis.yml | 11 +- .../channel_overrides/channel_overrides.py | 59 +-- examples/create_attribute/create_attribute.py | 9 +- examples/flight_replay/flight_replay.py | 32 +- examples/follow_me/follow_me.py | 27 +- examples/gcs/microgcs.py | 3 +- .../guided_set_speed_yaw.py | 27 +- examples/mission_basic/mission_basic.py | 433 +++++++++--------- .../mission_import_export.py | 345 +++++++------- examples/performance_test/performance_test.py | 5 +- examples/vehicle_state/vehicle_state.py | 161 +++---- windows/returnVersion.py | 23 +- 12 files changed, 572 insertions(+), 563 deletions(-) diff --git a/.travis.yml b/.travis.yml index cc7d067ef..9fc8157b9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,7 +6,7 @@ env: - SITL_RATE=200 python: - - 2.7.13 + - 2.7 - 3.6 before_install: @@ -17,10 +17,10 @@ install: - pip install flake8 before_script: - # --exit-zero means that flake8 will not stop the build - # 127 characters is the width of a GitHub editor - - flake8 . --count --exit-zero --max-line-length=127 --select=E999 --statistics # syntax errors - - flake8 . --count --exit-zero --max-line-length=127 --statistics + # stop the build if there are Python syntax errors or undefined names + - flake8 . --count --select=E901,E999,F821,F822,F823 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + - flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics script: - nosetests --debug=nose,nose.importer --debug-log=nose_debug -svx dronekit.test.unit @@ -41,7 +41,6 @@ notifications: matrix: allow_failures: - python: 3.6 - fast_finish: true branches: only: diff --git a/examples/channel_overrides/channel_overrides.py b/examples/channel_overrides/channel_overrides.py index a44f4f132..358a7ea51 100644 --- a/examples/channel_overrides/channel_overrides.py +++ b/examples/channel_overrides/channel_overrides.py @@ -17,6 +17,7 @@ Full documentation is provided at http://python.dronekit.io/examples/channel_overrides.html """ +from __future__ import print_function from dronekit import connect @@ -39,61 +40,61 @@ # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) # Get all original channel values (before override) -print "Channel values from RC Tx:", vehicle.channels +print("Channel values from RC Tx:", vehicle.channels) # Access channels individually -print "Read channels individually:" -print " Ch1: %s" % vehicle.channels['1'] -print " Ch2: %s" % vehicle.channels['2'] -print " Ch3: %s" % vehicle.channels['3'] -print " Ch4: %s" % vehicle.channels['4'] -print " Ch5: %s" % vehicle.channels['5'] -print " Ch6: %s" % vehicle.channels['6'] -print " Ch7: %s" % vehicle.channels['7'] -print " Ch8: %s" % vehicle.channels['8'] -print "Number of channels: %s" % len(vehicle.channels) +print("Read channels individually:") +print(" Ch1: %s" % vehicle.channels['1']) +print(" Ch2: %s" % vehicle.channels['2']) +print(" Ch3: %s" % vehicle.channels['3']) +print(" Ch4: %s" % vehicle.channels['4']) +print(" Ch5: %s" % vehicle.channels['5']) +print(" Ch6: %s" % vehicle.channels['6']) +print(" Ch7: %s" % vehicle.channels['7']) +print(" Ch8: %s" % vehicle.channels['8']) +print("Number of channels: %s" % len(vehicle.channels)) # Override channels -print "\nChannel overrides: %s" % vehicle.channels.overrides +print("\nChannel overrides: %s" % vehicle.channels.overrides) -print "Set Ch2 override to 200 (indexing syntax)" +print("Set Ch2 override to 200 (indexing syntax)") vehicle.channels.overrides['2'] = 200 -print " Channel overrides: %s" % vehicle.channels.overrides -print " Ch2 override: %s" % vehicle.channels.overrides['2'] +print(" Channel overrides: %s" % vehicle.channels.overrides) +print(" Ch2 override: %s" % vehicle.channels.overrides['2']) -print "Set Ch3 override to 300 (dictionary syntax)" +print("Set Ch3 override to 300 (dictionary syntax)") vehicle.channels.overrides = {'3':300} -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) -print "Set Ch1-Ch8 overrides to 110-810 respectively" +print("Set Ch1-Ch8 overrides to 110-810 respectively") vehicle.channels.overrides = {'1': 110, '2': 210,'3': 310,'4':4100, '5':510,'6':610,'7':710,'8':810} -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) # Clear override by setting channels to None -print "\nCancel Ch2 override (indexing syntax)" +print("\nCancel Ch2 override (indexing syntax)") vehicle.channels.overrides['2'] = None -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) -print "Clear Ch3 override (del syntax)" +print("Clear Ch3 override (del syntax)") del vehicle.channels.overrides['3'] -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) -print "Clear Ch5, Ch6 override and set channel 3 to 500 (dictionary syntax)" +print("Clear Ch5, Ch6 override and set channel 3 to 500 (dictionary syntax)") vehicle.channels.overrides = {'5':None, '6':None,'3':500} -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) -print "Clear all overrides" +print("Clear all overrides") vehicle.channels.overrides = {} -print " Channel overrides: %s" % vehicle.channels.overrides +print(" Channel overrides: %s" % vehicle.channels.overrides) #Close vehicle object before exiting script -print "\nClose vehicle object" +print("\nClose vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/examples/create_attribute/create_attribute.py b/examples/create_attribute/create_attribute.py index 5aa154f4b..5d8a20e15 100644 --- a/examples/create_attribute/create_attribute.py +++ b/examples/create_attribute/create_attribute.py @@ -14,6 +14,7 @@ Full documentation is provided at http://python.dronekit.io/examples/create_attribute.html """ +from __future__ import print_function from dronekit import connect, Vehicle from my_vehicle import MyVehicle #Our custom vehicle class @@ -40,7 +41,7 @@ # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True, vehicle_class=MyVehicle) # Add observer for the custom attribute @@ -48,17 +49,17 @@ def raw_imu_callback(self, attr_name, value): # attr_name == 'raw_imu' # value == vehicle.raw_imu - print value + print(value) vehicle.add_attribute_listener('raw_imu', raw_imu_callback) -print 'Display RAW_IMU messages for 5 seconds and then exit.' +print('Display RAW_IMU messages for 5 seconds and then exit.') time.sleep(5) #The message listener can be unset using ``vehicle.remove_message_listener`` #Close vehicle object before exiting script -print "Close vehicle object" +print("Close vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/examples/flight_replay/flight_replay.py b/examples/flight_replay/flight_replay.py index 04f0a599c..a7564abd1 100644 --- a/examples/flight_replay/flight_replay.py +++ b/examples/flight_replay/flight_replay.py @@ -10,6 +10,7 @@ Full documentation is provided at http://python.dronekit.io/examples/flight_replay.html """ +from __future__ import print_function from dronekit import connect, Command, VehicleMode, LocationGlobalRelative from pymavlink import mavutil @@ -107,7 +108,7 @@ def arm_and_takeoff(aTargetAltitude): # Don't try to arm until autopilot is ready while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." + print(" Waiting for vehicle to initialise...") time.sleep(1) # Set mode to GUIDED for arming and takeoff: @@ -118,10 +119,10 @@ def arm_and_takeoff(aTargetAltitude): # Confirm vehicle armed before attempting to take off while not vehicle.armed: vehicle.armed = True - print " Waiting for arming..." + print(" Waiting for arming...") time.sleep(1) - print " Taking off!" + print(" Taking off!") vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude # Wait until the vehicle reaches a safe height @@ -130,16 +131,16 @@ def arm_and_takeoff(aTargetAltitude): requiredAlt = aTargetAltitude*0.95 #Break and return from function just below target altitude. if vehicle.location.global_relative_frame.alt>=requiredAlt: - print " Reached target altitude of ~%f" % (aTargetAltitude) + print(" Reached target altitude of ~%f" % (aTargetAltitude)) break - print " Altitude: %f < %f" % (vehicle.location.global_relative_frame.alt, - requiredAlt) + print(" Altitude: %f < %f" % (vehicle.location.global_relative_frame.alt, + requiredAlt)) time.sleep(1) print("Generating waypoints from tlog...") messages = position_messages_from_tlog(args.tlog) -print " Generated %d waypoints from tlog" % len(messages) +print(" Generated %d waypoints from tlog" % len(messages)) if len(messages) == 0: print("No position messages found in log") exit(0) @@ -157,7 +158,7 @@ def arm_and_takeoff(aTargetAltitude): connection_string = sitl.connection_string() # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) @@ -168,8 +169,7 @@ def arm_and_takeoff(aTargetAltitude): cmds = vehicle.commands cmds.clear() -for i in xrange(0, len(messages)): - pt = messages[i] +for pt in messages: #print "Point: %d %d" % (pt.lat, pt.lon,) lat = pt.lat lon = pt.lon @@ -189,11 +189,11 @@ def arm_and_takeoff(aTargetAltitude): print("Uploading %d waypoints to vehicle..." % len(messages)) cmds.upload() -print "Arm and Takeoff" +print("Arm and Takeoff") arm_and_takeoff(30) -print "Starting mission" +print("Starting mission") # Reset mission set to first (0) waypoint vehicle.commands.next=0 @@ -207,20 +207,20 @@ def arm_and_takeoff(aTargetAltitude): time_start = time.time() while time.time() - time_start < 60: nextwaypoint=vehicle.commands.next - print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) + print('Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint())) if nextwaypoint==len(messages): - print "Exit 'standard' mission when start heading to final waypoint" + print("Exit 'standard' mission when start heading to final waypoint") break; time.sleep(1) -print 'Return to launch' +print('Return to launch') while (vehicle.mode.name != "RTL"): vehicle.mode = VehicleMode("RTL") time.sleep(0.1) #Close vehicle object before exiting script -print "Close vehicle object" +print("Close vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/examples/follow_me/follow_me.py b/examples/follow_me/follow_me.py index bd89a4e96..aa489d26b 100644 --- a/examples/follow_me/follow_me.py +++ b/examples/follow_me/follow_me.py @@ -13,6 +13,7 @@ Example documentation: http://python.dronekit.io/examples/follow_me.html """ +from __future__ import print_function from dronekit import connect, VehicleMode, LocationGlobalRelative import gps @@ -38,7 +39,7 @@ connection_string = sitl.connection_string() # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) @@ -48,31 +49,31 @@ def arm_and_takeoff(aTargetAltitude): Arms vehicle and fly to aTargetAltitude. """ - print "Basic pre-arm checks" + print("Basic pre-arm checks") # Don't let the user try to arm until autopilot is ready while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." + print(" Waiting for vehicle to initialise...") time.sleep(1) - print "Arming motors" + print("Arming motors") # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True while not vehicle.armed: - print " Waiting for arming..." + print(" Waiting for arming...") time.sleep(1) - print "Taking off!" + print("Taking off!") vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude # 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 + print(" Altitude: ", vehicle.location.global_relative_frame.alt) if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. - print "Reached target altitude" + print("Reached target altitude") break time.sleep(1) @@ -88,17 +89,17 @@ def arm_and_takeoff(aTargetAltitude): while True: if vehicle.mode.name != "GUIDED": - print "User has changed flight modes - aborting follow-me" + print("User has changed flight modes - aborting follow-me") break # Read the GPS state from the laptop - gpsd.next() + next(gpsd) # Once we have a valid location (see gpsd documentation) we can start moving our vehicle around if (gpsd.valid & gps.LATLON_SET) != 0: altitude = 30 # in meters dest = LocationGlobalRelative(gpsd.fix.latitude, gpsd.fix.longitude, altitude) - print "Going to: %s" % dest + print("Going to: %s" % dest) # A better implementation would only send new waypoints if the position had changed significantly vehicle.simple_goto(dest) @@ -108,11 +109,11 @@ def arm_and_takeoff(aTargetAltitude): time.sleep(2) except socket.error: - print "Error: gpsd service does not seem to be running, plug in USB GPS or run run-fake-gps.sh" + print("Error: gpsd service does not seem to be running, plug in USB GPS or run run-fake-gps.sh") sys.exit(1) #Close vehicle object before exiting script -print "Close vehicle object" +print("Close vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/examples/gcs/microgcs.py b/examples/gcs/microgcs.py index 1ebee38f4..a3d33aaca 100644 --- a/examples/gcs/microgcs.py +++ b/examples/gcs/microgcs.py @@ -4,6 +4,7 @@ """ © Copyright 2015-2016, 3D Robotics. """ +from __future__ import print_function # # This is a small example of the python drone API - an ultra minimal GCS # @@ -32,7 +33,7 @@ connection_string = sitl.connection_string() # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) def setMode(mode): diff --git a/examples/guided_set_speed_yaw/guided_set_speed_yaw.py b/examples/guided_set_speed_yaw/guided_set_speed_yaw.py index 0c161b6af..3dee73025 100644 --- a/examples/guided_set_speed_yaw/guided_set_speed_yaw.py +++ b/examples/guided_set_speed_yaw/guided_set_speed_yaw.py @@ -9,6 +9,7 @@ Example documentation: http://python.dronekit.io/examples/guided-set-speed-yaw-demo.html """ +from __future__ import print_function from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative from pymavlink import mavutil # Needed for command message definitions @@ -35,7 +36,7 @@ # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) @@ -44,31 +45,31 @@ def arm_and_takeoff(aTargetAltitude): Arms vehicle and fly to aTargetAltitude. """ - print "Basic pre-arm checks" + print("Basic pre-arm checks") # Don't let the user try to arm until autopilot is ready while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." + print(" Waiting for vehicle to initialise...") time.sleep(1) - print "Arming motors" + print("Arming motors") # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") vehicle.armed = True while not vehicle.armed: - print " Waiting for arming..." + print(" Waiting for arming...") time.sleep(1) - print "Taking off!" + print("Taking off!") vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude # 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 + print(" Altitude: ", vehicle.location.global_relative_frame.alt) if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. - print "Reached target altitude" + print("Reached target altitude") break time.sleep(1) @@ -316,9 +317,9 @@ def goto(dNorth, dEast, gotoFunction=vehicle.simple_goto): while vehicle.mode.name=="GUIDED": #Stop action if we are no longer in guided mode. #print "DEBUG: mode: %s" % vehicle.mode.name remainingDistance=get_distance_metres(vehicle.location.global_relative_frame, targetLocation) - print "Distance to target: ", remainingDistance + print("Distance to target: ", remainingDistance) if remainingDistance<=targetDistance*0.01: #Just below target, in case of undershoot. - print "Reached target" + print("Reached target") break; time.sleep(2) @@ -605,12 +606,12 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z, duration): print("Set new home location to current location") vehicle.home_location=vehicle.location.global_frame -print "Get new home location" +print("Get new home location") #This reloads the home location in DroneKit and GCSs cmds = vehicle.commands cmds.download() cmds.wait_ready() -print " Home Location: %s" % vehicle.home_location +print(" Home Location: %s" % vehicle.home_location) print("Yaw 90 relative (to previous yaw heading)") @@ -638,7 +639,7 @@ def send_global_velocity(velocity_x, velocity_y, velocity_z, duration): #Close vehicle object before exiting script -print "Close vehicle object" +print("Close vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/examples/mission_basic/mission_basic.py b/examples/mission_basic/mission_basic.py index 4255ec25c..8e394e4db 100644 --- a/examples/mission_basic/mission_basic.py +++ b/examples/mission_basic/mission_basic.py @@ -1,216 +1,217 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -© Copyright 2015-2016, 3D Robotics. -mission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions. - -Full documentation is provided at http://python.dronekit.io/examples/mission_basic.html -""" - -from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command -import time -import math -from pymavlink import mavutil - - -#Set up option parsing to get connection string -import argparse -parser = argparse.ArgumentParser(description='Demonstrates basic mission operations.') -parser.add_argument('--connect', - help="vehicle connection target string. If not specified, SITL automatically started and used.") -args = parser.parse_args() - -connection_string = args.connect -sitl = None - - -#Start SITL if no connection string specified -if not connection_string: - import dronekit_sitl - sitl = dronekit_sitl.start_default() - connection_string = sitl.connection_string() - - -# Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string -vehicle = connect(connection_string, wait_ready=True) - - -def get_location_metres(original_location, dNorth, dEast): - """ - Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the - specified `original_location`. The returned Location has the same `alt` value - as `original_location`. - - The function is useful when you want to move the vehicle around specifying locations relative to - the current vehicle position. - The algorithm is relatively accurate over small distances (10m within 1km) except close to the poles. - For more information see: - http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters - """ - earth_radius=6378137.0 #Radius of "spherical" earth - #Coordinate offsets in radians - dLat = dNorth/earth_radius - dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180)) - - #New position in decimal degrees - newlat = original_location.lat + (dLat * 180/math.pi) - newlon = original_location.lon + (dLon * 180/math.pi) - return LocationGlobal(newlat, newlon,original_location.alt) - - -def get_distance_metres(aLocation1, aLocation2): - """ - Returns the ground distance in metres between two LocationGlobal objects. - - This method is an approximation, and will not be accurate over large distances and close to the - earth's poles. It comes from the ArduPilot test code: - https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py - """ - dlat = aLocation2.lat - aLocation1.lat - dlong = aLocation2.lon - aLocation1.lon - return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5 - - - -def distance_to_current_waypoint(): - """ - Gets distance in metres to the current waypoint. - It returns None for the first waypoint (Home location). - """ - nextwaypoint = vehicle.commands.next - if nextwaypoint==0: - return None - missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed - lat = missionitem.x - lon = missionitem.y - alt = missionitem.z - targetWaypointLocation = LocationGlobalRelative(lat,lon,alt) - distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation) - return distancetopoint - - -def download_mission(): - """ - Download the current mission from the vehicle. - """ - cmds = vehicle.commands - cmds.download() - cmds.wait_ready() # wait until download is complete. - - - -def adds_square_mission(aLocation, aSize): - """ - Adds a takeoff command and four waypoint commands to the current mission. - The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation). - - The function assumes vehicle.commands matches the vehicle mission state - (you must have called download at least once in the session and after clearing the mission) - """ - - cmds = vehicle.commands - - print " Clear any existing commands" - cmds.clear() - - print " Define/add new commands." - # Add new commands. The meaning/order of the parameters is documented in the Command class. - - #Add MAV_CMD_NAV_TAKEOFF command. This is ignored if the vehicle is already in the air. - 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)) - - #Define the four MAV_CMD_NAV_WAYPOINT locations and add the commands - point1 = get_location_metres(aLocation, aSize, -aSize) - point2 = get_location_metres(aLocation, aSize, aSize) - point3 = get_location_metres(aLocation, -aSize, aSize) - point4 = get_location_metres(aLocation, -aSize, -aSize) - 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, point1.lat, point1.lon, 11)) - 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, point2.lat, point2.lon, 12)) - 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, point3.lat, point3.lon, 13)) - 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, point4.lat, point4.lon, 14)) - #add dummy waypoint "5" at point 4 (lets us know when have reached destination) - 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, point4.lat, point4.lon, 14)) - - print " Upload new commands to vehicle" - cmds.upload() - - -def arm_and_takeoff(aTargetAltitude): - """ - Arms vehicle and fly to aTargetAltitude. - """ - - print "Basic pre-arm checks" - # Don't let the user try to arm until autopilot is ready - while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." - time.sleep(1) - - - print "Arming motors" - # Copter should arm in GUIDED mode - vehicle.mode = VehicleMode("GUIDED") - vehicle.armed = True - - while not vehicle.armed: - print " Waiting for arming..." - time.sleep(1) - - print "Taking off!" - vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude - - # 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 - if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. - print "Reached target altitude" - break - time.sleep(1) - - -print 'Create a new mission (for current location)' -adds_square_mission(vehicle.location.global_frame,50) - - -# From Copter 3.3 you will be able to take off using a mission item. Plane must take off using a mission item (currently). -arm_and_takeoff(10) - -print "Starting mission" -# Reset mission set to first (0) waypoint -vehicle.commands.next=0 - -# Set mode to AUTO to start mission -vehicle.mode = VehicleMode("AUTO") - - -# Monitor mission. -# Demonstrates getting and setting the command number -# Uses distance_to_current_waypoint(), a convenience function for finding the -# distance to the next waypoint. - -while True: - nextwaypoint=vehicle.commands.next - print 'Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint()) - - if nextwaypoint==3: #Skip to next waypoint - print 'Skipping to Waypoint 5 when reach waypoint 3' - vehicle.commands.next = 5 - if nextwaypoint==5: #Dummy waypoint - as soon as we reach waypoint 4 this is true and we exit. - print "Exit 'standard' mission when start heading to final waypoint (5)" - break; - time.sleep(1) - -print 'Return to launch' -vehicle.mode = VehicleMode("RTL") - - -#Close vehicle object before exiting script -print "Close vehicle object" -vehicle.close() - -# Shut down simulator if it was started. -if sitl is not None: - sitl.stop() +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +© Copyright 2015-2016, 3D Robotics. +mission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions. + +Full documentation is provided at http://python.dronekit.io/examples/mission_basic.html +""" +from __future__ import print_function + +from dronekit import connect, VehicleMode, LocationGlobalRelative, LocationGlobal, Command +import time +import math +from pymavlink import mavutil + + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates basic mission operations.') +parser.add_argument('--connect', + help="vehicle connection target string. If not specified, SITL automatically started and used.") +args = parser.parse_args() + +connection_string = args.connect +sitl = None + + +#Start SITL if no connection string specified +if not connection_string: + import dronekit_sitl + sitl = dronekit_sitl.start_default() + connection_string = sitl.connection_string() + + +# Connect to the Vehicle +print('Connecting to vehicle on: %s' % connection_string) +vehicle = connect(connection_string, wait_ready=True) + + +def get_location_metres(original_location, dNorth, dEast): + """ + Returns a LocationGlobal object containing the latitude/longitude `dNorth` and `dEast` metres from the + specified `original_location`. The returned Location has the same `alt` value + as `original_location`. + + The function is useful when you want to move the vehicle around specifying locations relative to + the current vehicle position. + The algorithm is relatively accurate over small distances (10m within 1km) except close to the poles. + For more information see: + http://gis.stackexchange.com/questions/2951/algorithm-for-offsetting-a-latitude-longitude-by-some-amount-of-meters + """ + earth_radius=6378137.0 #Radius of "spherical" earth + #Coordinate offsets in radians + dLat = dNorth/earth_radius + dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180)) + + #New position in decimal degrees + newlat = original_location.lat + (dLat * 180/math.pi) + newlon = original_location.lon + (dLon * 180/math.pi) + return LocationGlobal(newlat, newlon,original_location.alt) + + +def get_distance_metres(aLocation1, aLocation2): + """ + Returns the ground distance in metres between two LocationGlobal objects. + + This method is an approximation, and will not be accurate over large distances and close to the + earth's poles. It comes from the ArduPilot test code: + https://github.com/diydrones/ardupilot/blob/master/Tools/autotest/common.py + """ + dlat = aLocation2.lat - aLocation1.lat + dlong = aLocation2.lon - aLocation1.lon + return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5 + + + +def distance_to_current_waypoint(): + """ + Gets distance in metres to the current waypoint. + It returns None for the first waypoint (Home location). + """ + nextwaypoint = vehicle.commands.next + if nextwaypoint==0: + return None + missionitem=vehicle.commands[nextwaypoint-1] #commands are zero indexed + lat = missionitem.x + lon = missionitem.y + alt = missionitem.z + targetWaypointLocation = LocationGlobalRelative(lat,lon,alt) + distancetopoint = get_distance_metres(vehicle.location.global_frame, targetWaypointLocation) + return distancetopoint + + +def download_mission(): + """ + Download the current mission from the vehicle. + """ + cmds = vehicle.commands + cmds.download() + cmds.wait_ready() # wait until download is complete. + + + +def adds_square_mission(aLocation, aSize): + """ + Adds a takeoff command and four waypoint commands to the current mission. + The waypoints are positioned to form a square of side length 2*aSize around the specified LocationGlobal (aLocation). + + The function assumes vehicle.commands matches the vehicle mission state + (you must have called download at least once in the session and after clearing the mission) + """ + + cmds = vehicle.commands + + print(" Clear any existing commands") + cmds.clear() + + print(" Define/add new commands.") + # Add new commands. The meaning/order of the parameters is documented in the Command class. + + #Add MAV_CMD_NAV_TAKEOFF command. This is ignored if the vehicle is already in the air. + 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)) + + #Define the four MAV_CMD_NAV_WAYPOINT locations and add the commands + point1 = get_location_metres(aLocation, aSize, -aSize) + point2 = get_location_metres(aLocation, aSize, aSize) + point3 = get_location_metres(aLocation, -aSize, aSize) + point4 = get_location_metres(aLocation, -aSize, -aSize) + 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, point1.lat, point1.lon, 11)) + 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, point2.lat, point2.lon, 12)) + 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, point3.lat, point3.lon, 13)) + 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, point4.lat, point4.lon, 14)) + #add dummy waypoint "5" at point 4 (lets us know when have reached destination) + 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, point4.lat, point4.lon, 14)) + + print(" Upload new commands to vehicle") + cmds.upload() + + +def arm_and_takeoff(aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude. + """ + + print("Basic pre-arm checks") + # Don't let the user try to arm until autopilot is ready + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + + print("Arming motors") + # Copter should arm in GUIDED mode + vehicle.mode = VehicleMode("GUIDED") + vehicle.armed = True + + while not vehicle.armed: + print(" Waiting for arming...") + time.sleep(1) + + print("Taking off!") + vehicle.simple_takeoff(aTargetAltitude) # Take off to target altitude + + # 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) + if vehicle.location.global_relative_frame.alt>=aTargetAltitude*0.95: #Trigger just below target alt. + print("Reached target altitude") + break + time.sleep(1) + + +print('Create a new mission (for current location)') +adds_square_mission(vehicle.location.global_frame,50) + + +# From Copter 3.3 you will be able to take off using a mission item. Plane must take off using a mission item (currently). +arm_and_takeoff(10) + +print("Starting mission") +# Reset mission set to first (0) waypoint +vehicle.commands.next=0 + +# Set mode to AUTO to start mission +vehicle.mode = VehicleMode("AUTO") + + +# Monitor mission. +# Demonstrates getting and setting the command number +# Uses distance_to_current_waypoint(), a convenience function for finding the +# distance to the next waypoint. + +while True: + nextwaypoint=vehicle.commands.next + print('Distance to waypoint (%s): %s' % (nextwaypoint, distance_to_current_waypoint())) + + if nextwaypoint==3: #Skip to next waypoint + print('Skipping to Waypoint 5 when reach waypoint 3') + vehicle.commands.next = 5 + if nextwaypoint==5: #Dummy waypoint - as soon as we reach waypoint 4 this is true and we exit. + print("Exit 'standard' mission when start heading to final waypoint (5)") + break; + time.sleep(1) + +print('Return to launch') +vehicle.mode = VehicleMode("RTL") + + +#Close vehicle object before exiting script +print("Close vehicle object") +vehicle.close() + +# Shut down simulator if it was started. +if sitl is not None: + sitl.stop() diff --git a/examples/mission_import_export/mission_import_export.py b/examples/mission_import_export/mission_import_export.py index 13a96c0d3..d0c77e04c 100644 --- a/examples/mission_import_export/mission_import_export.py +++ b/examples/mission_import_export/mission_import_export.py @@ -1,172 +1,173 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -© Copyright 2015-2016, 3D Robotics. -mission_import_export.py: - -This example demonstrates how to import and export files in the Waypoint file format -(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). The commands are imported -into a list, and can be modified before saving and/or uploading. - -Documentation is provided at http://python.dronekit.io/examples/mission_import_export.html -""" - - -from dronekit import connect, Command -import time - - -#Set up option parsing to get connection string -import argparse -parser = argparse.ArgumentParser(description='Demonstrates mission import/export from a file.') -parser.add_argument('--connect', - help="Vehicle connection target string. If not specified, SITL automatically started and used.") -args = parser.parse_args() - -connection_string = args.connect -sitl = None - - -#Start SITL if no connection string specified -if not connection_string: - import dronekit_sitl - sitl = dronekit_sitl.start_default() - connection_string = sitl.connection_string() - - -# Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string -vehicle = connect(connection_string, wait_ready=True) - -# Check that vehicle is armable. -# This ensures home_location is set (needed when saving WP file) - -while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." - time.sleep(1) - - -def readmission(aFileName): - """ - Load a mission from a file into a list. The mission definition is in the Waypoint file - format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). - - This function is used by upload_mission(). - """ - print "\nReading mission from file: %s" % aFileName - cmds = vehicle.commands - missionlist=[] - with open(aFileName) as f: - for i, line in enumerate(f): - if i==0: - if not line.startswith('QGC WPL 110'): - raise Exception('File is not supported WP version') - else: - linearray=line.split('\t') - ln_index=int(linearray[0]) - ln_currentwp=int(linearray[1]) - ln_frame=int(linearray[2]) - ln_command=int(linearray[3]) - ln_param1=float(linearray[4]) - ln_param2=float(linearray[5]) - ln_param3=float(linearray[6]) - ln_param4=float(linearray[7]) - ln_param5=float(linearray[8]) - ln_param6=float(linearray[9]) - ln_param7=float(linearray[10]) - ln_autocontinue=int(linearray[11].strip()) - cmd = Command( 0, 0, 0, ln_frame, ln_command, ln_currentwp, ln_autocontinue, ln_param1, ln_param2, ln_param3, ln_param4, ln_param5, ln_param6, ln_param7) - missionlist.append(cmd) - return missionlist - - -def upload_mission(aFileName): - """ - Upload a mission from a file. - """ - #Read mission from file - missionlist = readmission(aFileName) - - print "\nUpload mission from a file: %s" % import_mission_filename - #Clear existing mission from vehicle - print ' Clear mission' - cmds = vehicle.commands - cmds.clear() - #Add new mission to vehicle - for command in missionlist: - cmds.add(command) - print ' Upload mission' - vehicle.commands.upload() - - -def download_mission(): - """ - Downloads the current mission and returns it in a list. - It is used in save_mission() to get the file information to save. - """ - print " Download mission from vehicle" - missionlist=[] - cmds = vehicle.commands - cmds.download() - cmds.wait_ready() - for cmd in cmds: - missionlist.append(cmd) - return missionlist - -def save_mission(aFileName): - """ - Save a mission in the Waypoint file format - (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). - """ - print "\nSave mission from Vehicle to file: %s" % export_mission_filename - #Download mission from vehicle - missionlist = download_mission() - #Add file-format information - output='QGC WPL 110\n' - #Add home location as 0th waypoint - home = vehicle.home_location - output+="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (0,1,0,16,0,0,0,0,home.lat,home.lon,home.alt,1) - #Add commands - for cmd in missionlist: - commandline="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (cmd.seq,cmd.current,cmd.frame,cmd.command,cmd.param1,cmd.param2,cmd.param3,cmd.param4,cmd.x,cmd.y,cmd.z,cmd.autocontinue) - output+=commandline - with open(aFileName, 'w') as file_: - print " Write mission to file" - file_.write(output) - - -def printfile(aFileName): - """ - Print a mission file to demonstrate "round trip" - """ - print "\nMission file: %s" % aFileName - with open(aFileName) as f: - for line in f: - print ' %s' % line.strip() - - -import_mission_filename = 'mpmission.txt' -export_mission_filename = 'exportedmission.txt' - - -#Upload mission from file -upload_mission(import_mission_filename) - -#Download mission we just uploaded and save to a file -save_mission(export_mission_filename) - -#Close vehicle object before exiting script -print "Close vehicle object" -vehicle.close() - -# Shut down simulator if it was started. -if sitl is not None: - sitl.stop() - - -print "\nShow original and uploaded/downloaded files:" -#Print original file (for demo purposes only) -printfile(import_mission_filename) -#Print exported file (for demo purposes only) -printfile(export_mission_filename) +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +© Copyright 2015-2016, 3D Robotics. +mission_import_export.py: + +This example demonstrates how to import and export files in the Waypoint file format +(http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). The commands are imported +into a list, and can be modified before saving and/or uploading. + +Documentation is provided at http://python.dronekit.io/examples/mission_import_export.html +""" +from __future__ import print_function + + +from dronekit import connect, Command +import time + + +#Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Demonstrates mission import/export from a file.') +parser.add_argument('--connect', + help="Vehicle connection target string. If not specified, SITL automatically started and used.") +args = parser.parse_args() + +connection_string = args.connect +sitl = None + + +#Start SITL if no connection string specified +if not connection_string: + import dronekit_sitl + sitl = dronekit_sitl.start_default() + connection_string = sitl.connection_string() + + +# Connect to the Vehicle +print('Connecting to vehicle on: %s' % connection_string) +vehicle = connect(connection_string, wait_ready=True) + +# Check that vehicle is armable. +# This ensures home_location is set (needed when saving WP file) + +while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + +def readmission(aFileName): + """ + Load a mission from a file into a list. The mission definition is in the Waypoint file + format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). + + This function is used by upload_mission(). + """ + print("\nReading mission from file: %s" % aFileName) + cmds = vehicle.commands + missionlist=[] + with open(aFileName) as f: + for i, line in enumerate(f): + if i==0: + if not line.startswith('QGC WPL 110'): + raise Exception('File is not supported WP version') + else: + linearray=line.split('\t') + ln_index=int(linearray[0]) + ln_currentwp=int(linearray[1]) + ln_frame=int(linearray[2]) + ln_command=int(linearray[3]) + ln_param1=float(linearray[4]) + ln_param2=float(linearray[5]) + ln_param3=float(linearray[6]) + ln_param4=float(linearray[7]) + ln_param5=float(linearray[8]) + ln_param6=float(linearray[9]) + ln_param7=float(linearray[10]) + ln_autocontinue=int(linearray[11].strip()) + cmd = Command( 0, 0, 0, ln_frame, ln_command, ln_currentwp, ln_autocontinue, ln_param1, ln_param2, ln_param3, ln_param4, ln_param5, ln_param6, ln_param7) + missionlist.append(cmd) + return missionlist + + +def upload_mission(aFileName): + """ + Upload a mission from a file. + """ + #Read mission from file + missionlist = readmission(aFileName) + + print("\nUpload mission from a file: %s" % import_mission_filename) + #Clear existing mission from vehicle + print(' Clear mission') + cmds = vehicle.commands + cmds.clear() + #Add new mission to vehicle + for command in missionlist: + cmds.add(command) + print(' Upload mission') + vehicle.commands.upload() + + +def download_mission(): + """ + Downloads the current mission and returns it in a list. + It is used in save_mission() to get the file information to save. + """ + print(" Download mission from vehicle") + missionlist=[] + cmds = vehicle.commands + cmds.download() + cmds.wait_ready() + for cmd in cmds: + missionlist.append(cmd) + return missionlist + +def save_mission(aFileName): + """ + Save a mission in the Waypoint file format + (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). + """ + print("\nSave mission from Vehicle to file: %s" % export_mission_filename) + #Download mission from vehicle + missionlist = download_mission() + #Add file-format information + output='QGC WPL 110\n' + #Add home location as 0th waypoint + home = vehicle.home_location + output+="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (0,1,0,16,0,0,0,0,home.lat,home.lon,home.alt,1) + #Add commands + for cmd in missionlist: + commandline="%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (cmd.seq,cmd.current,cmd.frame,cmd.command,cmd.param1,cmd.param2,cmd.param3,cmd.param4,cmd.x,cmd.y,cmd.z,cmd.autocontinue) + output+=commandline + with open(aFileName, 'w') as file_: + print(" Write mission to file") + file_.write(output) + + +def printfile(aFileName): + """ + Print a mission file to demonstrate "round trip" + """ + print("\nMission file: %s" % aFileName) + with open(aFileName) as f: + for line in f: + print(' %s' % line.strip()) + + +import_mission_filename = 'mpmission.txt' +export_mission_filename = 'exportedmission.txt' + + +#Upload mission from file +upload_mission(import_mission_filename) + +#Download mission we just uploaded and save to a file +save_mission(export_mission_filename) + +#Close vehicle object before exiting script +print("Close vehicle object") +vehicle.close() + +# Shut down simulator if it was started. +if sitl is not None: + sitl.stop() + + +print("\nShow original and uploaded/downloaded files:") +#Print original file (for demo purposes only) +printfile(import_mission_filename) +#Print exported file (for demo purposes only) +printfile(export_mission_filename) diff --git a/examples/performance_test/performance_test.py b/examples/performance_test/performance_test.py index 7758a5440..2be53b46c 100644 --- a/examples/performance_test/performance_test.py +++ b/examples/performance_test/performance_test.py @@ -12,6 +12,7 @@ Full documentation is provided at http://python.dronekit.io/examples/performance_test.html """ +from __future__ import print_function from dronekit import connect from pymavlink import mavutil import time @@ -36,7 +37,7 @@ # Connect to the Vehicle -print 'Connecting to vehicle on: %s' % connection_string +print('Connecting to vehicle on: %s' % connection_string) vehicle = connect(connection_string, wait_ready=True) #global vehicle @@ -107,7 +108,7 @@ def send_testpackets(): #Start logging by sending a test packet send_testpackets() -print "Logging for 30 seconds" +print("Logging for 30 seconds") for x in range(1,30): time.sleep(1) diff --git a/examples/vehicle_state/vehicle_state.py b/examples/vehicle_state/vehicle_state.py index c4d7d55c6..3fd3717d0 100644 --- a/examples/vehicle_state/vehicle_state.py +++ b/examples/vehicle_state/vehicle_state.py @@ -10,6 +10,7 @@ Full documentation is provided at http://python.dronekit.io/examples/vehicle_state.html """ +from __future__ import print_function from dronekit import connect, VehicleMode import time @@ -33,55 +34,55 @@ # Connect to the Vehicle. # Set `wait_ready=True` to ensure default attributes are populated before `connect()` returns. -print "\nConnecting to vehicle on: %s" % connection_string +print("\nConnecting to vehicle on: %s" % connection_string) vehicle = connect(connection_string, wait_ready=True) vehicle.wait_ready('autopilot_version') # Get all vehicle attributes (state) -print "\nGet all vehicle attribute values:" -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() -print " Autopilot capabilities" -print " Supports MISSION_FLOAT message type: %s" % vehicle.capabilities.mission_float -print " Supports PARAM_FLOAT message type: %s" % vehicle.capabilities.param_float -print " Supports MISSION_INT message type: %s" % vehicle.capabilities.mission_int -print " Supports COMMAND_INT message type: %s" % vehicle.capabilities.command_int -print " Supports PARAM_UNION message type: %s" % vehicle.capabilities.param_union -print " Supports ftp for file transfers: %s" % vehicle.capabilities.ftp -print " Supports commanding attitude offboard: %s" % vehicle.capabilities.set_attitude_target -print " Supports commanding position and velocity targets in local NED frame: %s" % vehicle.capabilities.set_attitude_target_local_ned -print " Supports set position + velocity targets in global scaled integers: %s" % vehicle.capabilities.set_altitude_target_global_int -print " Supports terrain protocol / data handling: %s" % vehicle.capabilities.terrain -print " Supports direct actuator control: %s" % vehicle.capabilities.set_actuator_target -print " Supports the flight termination command: %s" % vehicle.capabilities.flight_termination -print " Supports mission_float message type: %s" % vehicle.capabilities.mission_float -print " Supports onboard compass calibration: %s" % vehicle.capabilities.compass_calibration -print " Global Location: %s" % vehicle.location.global_frame -print " Global Location (relative altitude): %s" % vehicle.location.global_relative_frame -print " Local Location: %s" % vehicle.location.local_frame -print " Attitude: %s" % vehicle.attitude -print " Velocity: %s" % vehicle.velocity -print " GPS: %s" % vehicle.gps_0 -print " Gimbal status: %s" % vehicle.gimbal -print " Battery: %s" % vehicle.battery -print " EKF OK?: %s" % vehicle.ekf_ok -print " Last Heartbeat: %s" % vehicle.last_heartbeat -print " Rangefinder: %s" % vehicle.rangefinder -print " Rangefinder distance: %s" % vehicle.rangefinder.distance -print " Rangefinder voltage: %s" % vehicle.rangefinder.voltage -print " Heading: %s" % vehicle.heading -print " Is Armable?: %s" % vehicle.is_armable -print " System status: %s" % vehicle.system_status.state -print " Groundspeed: %s" % vehicle.groundspeed # settable -print " Airspeed: %s" % vehicle.airspeed # settable -print " Mode: %s" % vehicle.mode.name # settable -print " Armed: %s" % vehicle.armed # settable +print("\nGet all vehicle attribute values:") +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()) +print(" Autopilot capabilities") +print(" Supports MISSION_FLOAT message type: %s" % vehicle.capabilities.mission_float) +print(" Supports PARAM_FLOAT message type: %s" % vehicle.capabilities.param_float) +print(" Supports MISSION_INT message type: %s" % vehicle.capabilities.mission_int) +print(" Supports COMMAND_INT message type: %s" % vehicle.capabilities.command_int) +print(" Supports PARAM_UNION message type: %s" % vehicle.capabilities.param_union) +print(" Supports ftp for file transfers: %s" % vehicle.capabilities.ftp) +print(" Supports commanding attitude offboard: %s" % vehicle.capabilities.set_attitude_target) +print(" Supports commanding position and velocity targets in local NED frame: %s" % vehicle.capabilities.set_attitude_target_local_ned) +print(" Supports set position + velocity targets in global scaled integers: %s" % vehicle.capabilities.set_altitude_target_global_int) +print(" Supports terrain protocol / data handling: %s" % vehicle.capabilities.terrain) +print(" Supports direct actuator control: %s" % vehicle.capabilities.set_actuator_target) +print(" Supports the flight termination command: %s" % vehicle.capabilities.flight_termination) +print(" Supports mission_float message type: %s" % vehicle.capabilities.mission_float) +print(" Supports onboard compass calibration: %s" % vehicle.capabilities.compass_calibration) +print(" Global Location: %s" % vehicle.location.global_frame) +print(" Global Location (relative altitude): %s" % vehicle.location.global_relative_frame) +print(" Local Location: %s" % vehicle.location.local_frame) +print(" Attitude: %s" % vehicle.attitude) +print(" Velocity: %s" % vehicle.velocity) +print(" GPS: %s" % vehicle.gps_0) +print(" Gimbal status: %s" % vehicle.gimbal) +print(" Battery: %s" % vehicle.battery) +print(" EKF OK?: %s" % vehicle.ekf_ok) +print(" Last Heartbeat: %s" % vehicle.last_heartbeat) +print(" Rangefinder: %s" % vehicle.rangefinder) +print(" Rangefinder distance: %s" % vehicle.rangefinder.distance) +print(" Rangefinder voltage: %s" % vehicle.rangefinder.voltage) +print(" Heading: %s" % vehicle.heading) +print(" Is Armable?: %s" % vehicle.is_armable) +print(" System status: %s" % vehicle.system_status.state) +print(" Groundspeed: %s" % vehicle.groundspeed) # settable +print(" Airspeed: %s" % vehicle.airspeed) # settable +print(" Mode: %s" % vehicle.mode.name) # settable +print(" Armed: %s" % vehicle.armed) # settable @@ -91,38 +92,38 @@ cmds.download() cmds.wait_ready() if not vehicle.home_location: - print " Waiting for home location ..." + print(" Waiting for home location ...") # We have a home location, so print it! -print "\n Home location: %s" % vehicle.home_location +print("\n Home location: %s" % vehicle.home_location) # Set vehicle home_location, mode, and armed attributes (the only settable attributes) -print "\nSet new home location" +print("\nSet new home location") # Home location must be within 50km of EKF home location (or setting will fail silently) # In this case, just set value to current location with an easily recognisable altitude (222) my_location_alt = vehicle.location.global_frame my_location_alt.alt = 222.0 vehicle.home_location = my_location_alt -print " New Home Location (from attribute - altitude should be 222): %s" % vehicle.home_location +print(" New Home Location (from attribute - altitude should be 222): %s" % vehicle.home_location) #Confirm current value on vehicle by re-downloading commands cmds = vehicle.commands cmds.download() cmds.wait_ready() -print " New Home Location (from vehicle - altitude should be 222): %s" % vehicle.home_location +print(" New Home Location (from vehicle - altitude should be 222): %s" % vehicle.home_location) -print "\nSet Vehicle.mode = GUIDED (currently: %s)" % vehicle.mode.name +print("\nSet Vehicle.mode = GUIDED (currently: %s)" % vehicle.mode.name) vehicle.mode = VehicleMode("GUIDED") while not vehicle.mode.name=='GUIDED': #Wait until mode has changed - print " Waiting for mode change ..." + print(" Waiting for mode change ...") time.sleep(1) # Check that vehicle is armable while not vehicle.is_armable: - print " Waiting for vehicle to initialise..." + print(" Waiting for vehicle to initialise...") time.sleep(1) # If required, you can provide additional information about initialisation # using `vehicle.gps_0.fix_type` and `vehicle.mode.name`. @@ -146,87 +147,87 @@ def attitude_callback(self, attr_name, value): global last_attitude_cache # Only publish when value changes if value!=last_attitude_cache: - print " CALLBACK: Attitude changed to", value + print(" CALLBACK: Attitude changed to", value) last_attitude_cache=value -print "\nAdd `attitude` attribute callback/observer on `vehicle`" +print("\nAdd `attitude` attribute callback/observer on `vehicle`") vehicle.add_attribute_listener('attitude', attitude_callback) -print " Wait 2s so callback invoked before observer removed" +print(" Wait 2s so callback invoked before observer removed") time.sleep(2) -print " Remove Vehicle.attitude observer" +print(" Remove Vehicle.attitude observer") # Remove observer added with `add_attribute_listener()` specifying the attribute and callback function vehicle.remove_attribute_listener('attitude', attitude_callback) # Add mode attribute callback using decorator (callbacks added this way cannot be removed). -print "\nAdd `mode` attribute callback/observer using decorator" +print("\nAdd `mode` attribute callback/observer using decorator") @vehicle.on_attribute('mode') def decorated_mode_callback(self, attr_name, value): # `attr_name` is the observed attribute (used if callback is used for multiple attributes) # `attr_name` - the observed attribute (used if callback is used for multiple attributes) # `value` is the updated attribute value. - print " CALLBACK: Mode changed to", value + print(" CALLBACK: Mode changed to", value) -print " Set mode=STABILIZE (currently: %s) and wait for callback" % vehicle.mode.name +print(" Set mode=STABILIZE (currently: %s) and wait for callback" % vehicle.mode.name) vehicle.mode = VehicleMode("STABILIZE") -print " Wait 2s so callback invoked before moving to next example" +print(" Wait 2s so callback invoked before moving to next example") time.sleep(2) -print "\n Attempt to remove observer added with `on_attribute` decorator (should fail)" +print("\n Attempt to remove observer added with `on_attribute` decorator (should fail)") try: vehicle.remove_attribute_listener('mode', decorated_mode_callback) except: - print " Exception: Cannot remove observer added using decorator" + print(" Exception: Cannot remove observer added using decorator") # Demonstrate getting callback on any attribute change def wildcard_callback(self, attr_name, value): - print " CALLBACK: (%s): %s" % (attr_name,value) + print(" CALLBACK: (%s): %s" % (attr_name,value)) -print "\nAdd attribute callback detecting ANY attribute change" +print("\nAdd attribute callback detecting ANY attribute change") vehicle.add_attribute_listener('*', wildcard_callback) -print " Wait 1s so callback invoked before observer removed" +print(" Wait 1s so callback invoked before observer removed") time.sleep(1) -print " Remove Vehicle attribute observer" +print(" Remove Vehicle attribute observer") # Remove observer added with `add_attribute_listener()` vehicle.remove_attribute_listener('*', wildcard_callback) # Get/Set Vehicle Parameters -print "\nRead and write parameters" -print " Read vehicle param 'THR_MIN': %s" % vehicle.parameters['THR_MIN'] +print("\nRead and write parameters") +print(" Read vehicle param 'THR_MIN': %s" % vehicle.parameters['THR_MIN']) -print " Write vehicle param 'THR_MIN' : 10" +print(" Write vehicle param 'THR_MIN' : 10") vehicle.parameters['THR_MIN']=10 -print " Read new value of param 'THR_MIN': %s" % vehicle.parameters['THR_MIN'] +print(" Read new value of param 'THR_MIN': %s" % vehicle.parameters['THR_MIN']) -print "\nPrint all parameters (iterate `vehicle.parameters`):" +print("\nPrint all parameters (iterate `vehicle.parameters`):") for key, value in vehicle.parameters.iteritems(): - print " Key:%s Value:%s" % (key,value) + print(" Key:%s Value:%s" % (key,value)) -print "\nCreate parameter observer using decorator" +print("\nCreate parameter observer using decorator") # Parameter string is case-insensitive # Value is cached (listeners are only updated on change) # Observer added using decorator can't be removed. @vehicle.parameters.on_attribute('THR_MIN') def decorated_thr_min_callback(self, attr_name, value): - print " PARAMETER CALLBACK: %s changed to: %s" % (attr_name, value) + print(" PARAMETER CALLBACK: %s changed to: %s" % (attr_name, value)) -print "Write vehicle param 'THR_MIN' : 20 (and wait for callback)" +print("Write vehicle param 'THR_MIN' : 20 (and wait for callback)") vehicle.parameters['THR_MIN']=20 for x in range(1,5): #Callbacks may not be updated for a few seconds @@ -236,19 +237,19 @@ def decorated_thr_min_callback(self, attr_name, value): #Callback function for "any" parameter -print "\nCreate (removable) observer for any parameter using wildcard string" +print("\nCreate (removable) observer for any parameter using wildcard string") def any_parameter_callback(self, attr_name, value): - print " ANY PARAMETER CALLBACK: %s changed to: %s" % (attr_name, value) + print(" ANY PARAMETER CALLBACK: %s changed to: %s" % (attr_name, value)) #Add observer for the vehicle's any/all parameters parameter (defined using wildcard string ``'*'``) vehicle.parameters.add_attribute_listener('*', any_parameter_callback) -print " Change THR_MID and THR_MIN parameters (and wait for callback)" +print(" Change THR_MID and THR_MIN parameters (and wait for callback)") vehicle.parameters['THR_MID']=400 vehicle.parameters['THR_MIN']=30 ## Reset variables to sensible values. -print "\nReset vehicle attributes/parameters and exit" +print("\nReset vehicle attributes/parameters and exit") vehicle.mode = VehicleMode("STABILIZE") #vehicle.armed = False vehicle.parameters['THR_MIN']=130 @@ -256,7 +257,7 @@ def any_parameter_callback(self, attr_name, value): #Close vehicle object before exiting script -print "\nClose vehicle object" +print("\nClose vehicle object") vehicle.close() # Shut down simulator if it was started. diff --git a/windows/returnVersion.py b/windows/returnVersion.py index a15976f88..ec9ebbadc 100644 --- a/windows/returnVersion.py +++ b/windows/returnVersion.py @@ -1,12 +1,13 @@ -# This script reads the setup.py and returns the current version number -# Used as part of building the WIndows setup file (DronekitWinBuild.bat) -# It assumes there is a line like this: -# version = "12344" - -# glob supports Unix style pathname extensions -with open("../setup.py") as f: - searchlines = f.readlines() - for i, line in enumerate(searchlines): - if "version = " in line: - print line[11:len(line)-2] +from __future__ import print_function +# This script reads the setup.py and returns the current version number +# Used as part of building the WIndows setup file (DronekitWinBuild.bat) +# It assumes there is a line like this: +# version = "12344" + +# glob supports Unix style pathname extensions +with open("../setup.py") as f: + searchlines = f.readlines() + for i, line in enumerate(searchlines): + if "version = " in line: + print(line[11:len(line)-2]) break \ No newline at end of file From bd3048a63c8278ecea826a1b34ee0267c4a55ca9 Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Tue, 31 Oct 2017 22:47:25 -0400 Subject: [PATCH 25/99] send_capabilities_request was misspelled this corrects the spelling of "capabilities" and adds an alias to the old name to avoid breaking existing code. --- dronekit/__init__.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 51c659ec4..b4dae41b8 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1110,7 +1110,7 @@ def listener(vehicle, name, m): # ArduPilot <3.4 fails to send capabilities correctly # straight after boot, and even older versions send # this back as always-0. - vehicle.remove_message_listener('HEARTBEAT', self.send_capabilties_request) + vehicle.remove_message_listener('HEARTBEAT', self.send_capabilities_request) self.notify_attribute_listeners('autopilot_version', self._raw_version) # gimbal @@ -2160,7 +2160,7 @@ def initialize(self, rate=4, heartbeat_timeout=30): self._master.mav.request_data_stream_send(0, 0, mavutil.mavlink.MAV_DATA_STREAM_ALL, rate, 1) - self.add_message_listener('HEARTBEAT', self.send_capabilties_request) + self.add_message_listener('HEARTBEAT', self.send_capabilities_request) # Ensure initial parameter download has started. while True: @@ -2172,6 +2172,14 @@ def initialize(self, rate=4, heartbeat_timeout=30): break def send_capabilties_request(self, vehicle, name, m): + '''An alias for send_capabilities_request. + + The word "capabilities" was misspelled in previous versions of this code. This is simply + an alias to send_capabilities_request using the legacy name. + ''' + return self.send_capabilities_request(vehicle, name, m) + + def send_capabilities_request(self, vehicle, name, m): '''Request an AUTOPILOT_VERSION packet''' capability_msg = vehicle.message_factory.command_long_encode(0, 0, mavutil.mavlink.MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES, 0, 1, 0, 0, 0, 0, 0, 0) vehicle.send_mavlink(capability_msg) From f9991fde389d55ce1cb030a80b5dbbf02e13657d Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Fri, 3 Nov 2017 14:53:51 -0400 Subject: [PATCH 26/99] raise ValueError if we are passed a bad value Given a bad value, we were sometimes raising a bare Exception, sometimes raising a ValueError, and sometimes raising an APIError. This commit attempts to make things consistent by raising ValueError when that's what we mean. There is also a drive-by correction to the spelling of "Expecting". --- dronekit/__init__.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b4dae41b8..d369fc788 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1957,7 +1957,7 @@ def home_location(self, pos): """ if not isinstance(pos, LocationGlobal): - raise Exception('Excepting home_location to be set to a LocationGlobal.') + raise ValueError('Expecting home_location to be set to a LocationGlobal.') # Set cached home location. self._home_location = copy.copy(pos) @@ -2058,7 +2058,7 @@ def simple_goto(self, location, airspeed=None, groundspeed=None): self.commands.wait_ready() alt = location.alt - self.home_location.alt else: - raise APIException('Expecting location to be LocationGlobal or LocationGlobalRelative.') + raise ValueError('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, @@ -2229,7 +2229,7 @@ def wait_ready(self, *types, **kwargs): types = self._default_ready_attrs if not all(isinstance(item, basestring) for item in types): - raise APIException('wait_ready expects one or more string arguments.') + raise ValueError('wait_ready expects one or more string arguments.') # Wait for these attributes to have been set. await = set(types) @@ -2387,7 +2387,7 @@ def target_location(self,roi): self.commands.wait_ready() alt = roi.alt - self.home_location.alt else: - raise APIException('Expecting location to be LocationGlobal or LocationGlobalRelative.') + raise ValueError('Expecting location to be LocationGlobal or LocationGlobalRelative.') #set the ROI msg = self._vehicle.message_factory.command_long_encode( From 200fbaf50208e0d7a99dbd026d2324ff6b26a03b Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Fri, 3 Nov 2017 15:03:29 -0400 Subject: [PATCH 27/99] raise KeyError instead of a bare Exception This removes the last instance of the code raising a bare Exception. Since this is a failure in a __setitem__ method it seems reasonable to raise a KeyError. --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index d369fc788..277bfec5e 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -730,7 +730,7 @@ def __getitem__(self, key): def __setitem__(self, key, value): if not (int(key) > 0 and int(key) <= self._count): - raise Exception('Invalid channel index %s' % key) + raise KeyError('Invalid channel index %s' % key) if not value: try: dict.__delitem__(self, str(key)) From b5eaa1874780f0f9d7fa1c1dfb1e47becf557639 Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Fri, 3 Nov 2017 14:52:58 -0400 Subject: [PATCH 28/99] add convenience methods for common synchronous operations this adds wait_for_armable, arm, disarm, wait_for_mode, and wait_for_alt methods that wrap common operations with wait-for-complete behavior with an optional timeout. --- dronekit/__init__.py | 120 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 117 insertions(+), 3 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 277bfec5e..10e04a213 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -61,8 +61,9 @@ class APIException(Exception): :param String message: Message string describing the exception """ - def __init__(self, message): - super(APIException, self).__init__(message) + +class TimeoutError(APIException): + '''Raised by operations that have timeouts.''' class Attitude(object): @@ -1989,6 +1990,119 @@ def parameters(self): """ return self._parameters + def wait_for(self, condition, timeout=None, interval=0.1, errmsg=None): + '''Wait for a condition to be True. + + Wait for condition, a callable, to return True. If timeout is + nonzero, raise a TimeoutError(errmsg) if the condition is not + True after timeout seconds. Check the condition everal + interval seconds. + ''' + + t0 = time.time() + while not condition(): + t1 = time.time() + if timeout and (t1 - t0) >= timeout: + raise TimeoutError(errmsg) + + time.sleep(interval) + + def wait_for_armable(self, timeout=None): + '''Wait for the vehicle to become armable. + + If timeout is nonzero, raise a TimeoutError if the vehicle + is not armable after timeout seconds. + ''' + + def check_armable(): + return self.is_armable + + self.wait_for(check_armable, timeout=timeout) + + def arm(self, wait=True, timeout=None): + '''Arm the vehicle. + + If wait is True, wait for arm operation to complete before + returning. If timeout is nonzero, raise a TimeouTerror if the + vehicle has not armed after timeout seconds. + ''' + + self.armed = True + + if wait: + self.wait_for(lambda: self.armed, timeout=timeout, + errmsg='failed to arm vehicle') + + def disarm(self, wait=True, timeout=None): + '''Disarm the vehicle. + + If wait is True, wait for disarm operation to complete before + returning. If timeout is nonzero, raise a TimeouTerror if the + vehicle has not disarmed after timeout seconds. + ''' + self.armed = False + + if wait: + self.wait_for(lambda: not self.armed, timeout=timeout, + errmsg='failed to disarm vehicle') + + def wait_for_mode(self, mode, timeout=None): + '''Set the flight mode. + + If wait is True, wait for the mode to change before returning. + If timeout is nonzero, raise a TimeoutError if the flight mode + hasn't changed after timeout seconds. + ''' + + if not isinstance(mode, VehicleMode): + mode = VehicleMode(mode) + + self.mode = mode + + self.wait_for(lambda: self.mode.name == mode.name, + timeout=timeout, + errmsg='failed to set flight mode') + + def wait_for_alt(self, alt, epsilon=0.1, rel=True, timeout=None): + '''Wait for the vehicle to reach the specified altitude. + + Wait for the vehicle to get within epsilon meters of the + given altitude. If rel is True (the default), use the + global_relative_frame. If rel is False, use the global_frame. + If timeout is nonzero, raise a TimeoutError if the specified + altitude has not been reached after timeout seconds. + ''' + + def get_alt(): + if rel: + alt = self.location.global_relative_frame.alt + else: + alt = self.location.global_frame.alt + + return alt + + def check_alt(): + cur = get_alt() + delta = abs(alt-cur) + + return ( + (delta < epsilon) or + (start < alt and cur > alt) or + (start > alt and cur < alt) + ) + + start = get_alt() + + self.wait_for( + check_alt, + timeout=timeout, + errmsg='failed to reach specified altitude') + + def wait_simple_takeoff(self, alt=None, epsilon=0.1, timeout=None): + self.simple_takeoff(alt) + + if alt is not None: + self.wait_for_alt(alt, epsilon=epsilon, timeout=timeout) def simple_takeoff(self, alt=None): """ @@ -2238,7 +2352,7 @@ def wait_ready(self, *types, **kwargs): time.sleep(0.1) if monotonic.monotonic() - start > timeout: if raise_exception: - raise APIException('wait_ready experienced a timeout after %s seconds.' % + raise TimeoutError('wait_ready experienced a timeout after %s seconds.' % timeout) else: return False From c337ba52e54e212a76ee17b01336f78b9531018f Mon Sep 17 00:00:00 2001 From: SJKim Date: Thu, 27 Apr 2017 20:57:40 +0900 Subject: [PATCH 29/99] Examples: add example for set_attitude_target Add an example code for movement in GUIDED_NOGPS mode Add the caution to the preface comment and delete the copyright Unify the format of print function Unify the format of comments Change the format of printing current altitude to improve the message visibility in Python 2 Add console messages to give users more information about current status --- .../set_attitude_target.py | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 examples/set_attitude_target/set_attitude_target.py diff --git a/examples/set_attitude_target/set_attitude_target.py b/examples/set_attitude_target/set_attitude_target.py new file mode 100644 index 000000000..c6ebd0ed3 --- /dev/null +++ b/examples/set_attitude_target/set_attitude_target.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" + +set_attitude_target.py: (Copter Only) + +This example shows how to move/direct Copter and send commands + in GUIDED_NOGPS mode using DroneKit Python. + +Caution: A lot of unexpected behaviors may occur in GUIDED_NOGPS mode. + Always watch the drone movement, and make sure that you are in dangerless environment. + Land the drone as soon as possible when it shows any unexpected behavior. + +Tested in Python 2.7.10 + +""" + +from dronekit import connect, VehicleMode, LocationGlobal, LocationGlobalRelative +from pymavlink import mavutil # Needed for command message definitions +import time +import math + +# Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Control Copter and send commands in GUIDED mode ') +parser.add_argument('--connect', + help="Vehicle connection target string. If not specified, SITL automatically started and used.") +args = parser.parse_args() + +connection_string = args.connect +sitl = None + +# Start SITL if no connection string specified +if not connection_string: + import dronekit_sitl + sitl = dronekit_sitl.start_default() + connection_string = sitl.connection_string() + + +# Connect to the Vehicle +print('Connecting to vehicle on: %s' % connection_string) +vehicle = connect(connection_string, wait_ready=True) + +def arm_and_takeoff_nogps(aTargetAltitude): + """ + Arms vehicle and fly to aTargetAltitude without GPS data. + """ + + ##### CONSTANTS ##### + DEFAULT_TAKEOFF_THRUST = 0.7 + SMOOTH_TAKEOFF_THRUST = 0.6 + + print("Basic pre-arm checks") + # Don't let the user try to arm until autopilot is ready + # If you need to disable the arming check, + # just comment it with your own responsibility. + while not vehicle.is_armable: + print(" Waiting for vehicle to initialise...") + time.sleep(1) + + + print("Arming motors") + # Copter should arm in GUIDED_NOGPS mode + vehicle.mode = VehicleMode("GUIDED_NOGPS") + vehicle.armed = True + + while not vehicle.armed: + print(" Waiting for arming...") + vehicle.armed = True + time.sleep(1) + + print("Taking off!") + + thrust = DEFAULT_TAKEOFF_THRUST + while True: + current_altitude = vehicle.location.global_relative_frame.alt + print(" Altitude: %f Desired: %f" % + (current_altitude, aTargetAltitude)) + if current_altitude >= aTargetAltitude*0.95: # Trigger just below target alt. + print("Reached target altitude") + break + elif current_altitude >= aTargetAltitude*0.6: + thrust = SMOOTH_TAKEOFF_THRUST + set_attitude(thrust = thrust) + time.sleep(0.2) + + +def set_attitude(roll_angle = 0.0, pitch_angle = 0.0, yaw_rate = 0.0, thrust = 0.5, duration = 0): + """ + Note that from AC3.3 the message should be re-sent every second (after about 3 seconds + with no message the velocity will drop back to zero). In AC3.2.1 and earlier the specified + velocity persists until it is canceled. The code below should work on either version + (sending the message multiple times does not cause problems). + """ + + """ + The roll and pitch rate cannot be controllbed with rate in radian in AC3.4.4 or earlier, + so you must use quaternion to control the pitch and roll for those vehicles. + """ + + # Thrust > 0.5: Ascend + # Thrust == 0.5: Hold the altitude + # Thrust < 0.5: Descend + msg = vehicle.message_factory.set_attitude_target_encode( + 0, # time_boot_ms + 1, # Target system + 1, # Target component + 0b00000000, # Type mask: bit 1 is LSB + to_quaternion(roll_angle, pitch_angle), # Quaternion + 0, # Body roll rate in radian + 0, # Body pitch rate in radian + math.radians(yaw_rate), # Body yaw rate in radian + thrust # Thrust + ) + vehicle.send_mavlink(msg) + + start = time.time() + while time.time() - start < duration: + vehicle.send_mavlink(msg) + time.sleep(0.1) + +def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0): + """ + Convert degrees to quaternions + """ + t0 = math.cos(math.radians(yaw * 0.5)) + t1 = math.sin(math.radians(yaw * 0.5)) + t2 = math.cos(math.radians(roll * 0.5)) + t3 = math.sin(math.radians(roll * 0.5)) + t4 = math.cos(math.radians(pitch * 0.5)) + t5 = math.sin(math.radians(pitch * 0.5)) + + w = t0 * t2 * t4 + t1 * t3 * t5 + x = t0 * t3 * t4 - t1 * t2 * t5 + y = t0 * t2 * t5 + t1 * t3 * t4 + z = t1 * t2 * t4 - t0 * t3 * t5 + + return [w, x, y, z] + +# Take off 2.5m in GUIDED_NOGPS mode. +arm_and_takeoff_nogps(2.5) + +# Hold the position for 3 seconds. +print("Hold position for 3 seconds") +set_attitude(duration = 3) + +# Uncomment the lines below for testing roll angle and yaw rate. +# Make sure that there is enough space for testing this. + +# set_attitude(roll_angle = 1, thrust = 0.5, duration = 3) +# set_attitude(yaw_rate = 30, thrust = 0.5, duration = 3) + +# Move the drone forward and backward. +# Note that it will be in front of original position due to inertia. +print("Move forward") +set_attitude(pitch_angle = -5, thrust = 0.5, duration = 3.21) + +print("Move backward") +set_attitude(pitch_angle = 5, thrust = 0.5, duration = 3) + + +print("Setting LAND mode...") +vehicle.mode = VehicleMode("LAND") +time.sleep(1) + +# Close vehicle object before exiting script +print("Close vehicle object") +vehicle.close() + +# Shut down simulator if it was started. +if sitl is not None: + sitl.stop() + +print("Completed") From de31ac6a80c8edb82efbfde7b99e4a3de72fe2b0 Mon Sep 17 00:00:00 2001 From: Lars Kellogg-Stedman Date: Tue, 9 Jan 2018 09:21:34 -0500 Subject: [PATCH 30/99] update connecting_vehicle with a serial example New dronekit users will often encounter timeout errors when attempting to open a serial connection (as in #704 and https://stackoverflow.com/q/48168953/147356). This updates the documentation to include an example for a serial connection and a note about setting the baud rate. --- docs/guide/connecting_vehicle.rst | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/guide/connecting_vehicle.rst b/docs/guide/connecting_vehicle.rst index f4430f501..135e29d38 100644 --- a/docs/guide/connecting_vehicle.rst +++ b/docs/guide/connecting_vehicle.rst @@ -27,6 +27,20 @@ The second parameter (``wait_ready``) is used to determine whether ``connect()`` on connection or if it waits until *some* vehicle parameters and attributes are populated. In most cases you should use ``wait_ready=True`` to wait on the default set of parameters. +Connecting over a serial device will look something like this: + +.. code-block:: python + + from dronekit import connect + + # Connect to the Vehicle (in this case a UDP endpoint) + vehicle = connect('/dev/ttyAMA0', wait_ready=True, baud=57600) + +.. tip:: + + If the baud rate is not set correctly, ``connect`` may fail with a + timeout error. It is best to set the baud rate explicitly. + :py:func:`connect() ` also has arguments for setting the baud rate, the length of the connection timeout, and/or to use a :ref:`custom vehicle class `. From ee6de416a561773388e524ac143ad19326e32dc7 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Mon, 22 Jan 2018 18:27:02 +0100 Subject: [PATCH 31/99] Fixes for intermittent timing failures of tests --- dronekit/test/sitl/test_mavlink.py | 5 +++-- dronekit/test/sitl/test_parameters.py | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/dronekit/test/sitl/test_mavlink.py b/dronekit/test/sitl/test_mavlink.py index 972c8ac8b..ac9330253 100644 --- a/dronekit/test/sitl/test_mavlink.py +++ b/dronekit/test/sitl/test_mavlink.py @@ -8,12 +8,12 @@ @with_sitl def test_mavlink(connpath): - vehicle = connect(connpath) + vehicle = connect(connpath, wait_ready=True) out = MAVConnection('udpin:localhost:15668') vehicle._handler.pipe(out) out.start() - vehicle2 = connect('udpout:localhost:15668') + vehicle2 = connect('udpout:localhost:15668', wait_ready=True) result = {'success': False} @@ -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/dronekit/test/sitl/test_parameters.py b/dronekit/test/sitl/test_parameters.py index ecd7b75d9..7a5529d8f 100644 --- a/dronekit/test/sitl/test_parameters.py +++ b/dronekit/test/sitl/test_parameters.py @@ -50,7 +50,7 @@ def test_setting(connpath): @vehicle.parameters.on_attribute('THR_MIN') def listener(self, name, value): - result['success'] = name == 'THR_MIN' and value == 3.000 + result['success'] = (name == 'THR_MIN' and value == 3.000) vehicle.parameters['THR_MIN'] = 3.000 From 4528e75444b86b725d5ac17a10a9c432bcfd43ad Mon Sep 17 00:00:00 2001 From: pietrodn Date: Mon, 22 Jan 2018 18:35:50 +0100 Subject: [PATCH 32/99] Fixes to make the test suite run under Python 3 also --- dronekit/__init__.py | 18 +++++++++++------- dronekit/test/sitl/test_channels.py | 4 ++-- dronekit/test/sitl/test_parameters.py | 2 +- 3 files changed, 14 insertions(+), 10 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 10e04a213..b8450196d 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -342,7 +342,7 @@ def release_type(self): if self.release is None: return None types = [ "dev", "alpha", "beta", "rc" ] - return types[self.release/64] + return types[self.release >> 6] def __str__(self): prefix="" @@ -751,7 +751,7 @@ def __len__(self): def _send(self): if self._active: overrides = [0] * 8 - for k, v in self.iteritems(): + for k, v in self.items(): overrides[int(k) - 1] = v self._vehicle._master.mav.rc_channels_override_send(0, 0, *overrides) @@ -846,7 +846,7 @@ def overrides(self): def overrides(self, newch): self._overrides._active = False self._overrides.clear() - for k, v in newch.iteritems(): + for k, v in newch.items(): if v: self._overrides[str(k)] = v else: @@ -1290,7 +1290,7 @@ def listener(_): c = 0 for i, v in enumerate(self._params_set): if v == None: - self._master.mav.param_request_read_send(0, 0, '', i) + self._master.mav.param_request_read_send(0, 0, b'', i) c += 1 if c > 50: break @@ -1316,8 +1316,12 @@ def listener(self, name, msg): self._params_last = monotonic.monotonic() self._params_duration = start_duration self._params_set[msg.param_index] = msg - self._params_map[msg.param_id] = msg.param_value - self._parameters.notify_attribute_listeners(msg.param_id, msg.param_value, + + # Normalize parameter name (remove trailing null bytes and convert to string) + param_name = msg.param_id.rstrip(b'\x00').decode('utf8') + + self._params_map[param_name] = msg.param_value + self._parameters.notify_attribute_listeners(param_name, msg.param_value, cache=True) except: import traceback @@ -2996,7 +3000,7 @@ def connect(ip, @vehicle.on_message('STATUSTEXT') def listener(self, name, m): - status_printer(re.sub(r'(^|\n)', '>>> ', m.text.decode('utf-8').rstrip())) + status_printer(re.sub(r'(^|\n)', '>>> ', m.text.rstrip(b'\x00').decode('utf-8').rstrip())) if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) diff --git a/dronekit/test/sitl/test_channels.py b/dronekit/test/sitl/test_channels.py index 44c484353..f3f02b1fa 100644 --- a/dronekit/test/sitl/test_channels.py +++ b/dronekit/test/sitl/test_channels.py @@ -10,7 +10,7 @@ def assert_readback(vehicle, values): while i > 0: time.sleep(.1) i -= .1 - for k, v in values.iteritems(): + for k, v in values.items(): if vehicle.channels[k] != v: continue break @@ -135,7 +135,7 @@ def test_timeout(connpath): # Set Ch2 to 33, clear channel 6 vehicle.channels.overrides = {'2': 33, '6': None} assert_readback(vehicle, {'2': 33, '6': 1500}) - assert_equals(vehicle.channels.overrides.keys(), ['2']) + assert_equals(list(vehicle.channels.overrides.keys()), ['2']) # Callbacks result = {'success': False} diff --git a/dronekit/test/sitl/test_parameters.py b/dronekit/test/sitl/test_parameters.py index 7a5529d8f..cb7d2f4bb 100644 --- a/dronekit/test/sitl/test_parameters.py +++ b/dronekit/test/sitl/test_parameters.py @@ -32,7 +32,7 @@ def test_iterating(connpath): vehicle = connect(connpath, wait_ready=True) # Iterate over parameters. - for k, v in vehicle.parameters.iteritems(): + for k, v in vehicle.parameters.items(): break for key in vehicle.parameters: break From 328977a89c6047152e10f56d49b3a94198e9fbec Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Tue, 23 Jan 2018 07:50:45 +0100 Subject: [PATCH 33/99] =?UTF-8?q?Take=20out=20the=20.rstrip(b=E2=80=99\x00?= =?UTF-8?q?=E2=80=99)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dronekit/__init__.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b8450196d..5c189fe54 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1317,8 +1317,8 @@ def listener(self, name, msg): self._params_duration = start_duration self._params_set[msg.param_index] = msg - # Normalize parameter name (remove trailing null bytes and convert to string) - param_name = msg.param_id.rstrip(b'\x00').decode('utf8') + # Normalize parameter name (convert to string) + param_name = msg.param_id.decode('utf8') self._params_map[param_name] = msg.param_value self._parameters.notify_attribute_listeners(param_name, msg.param_value, @@ -3000,7 +3000,7 @@ def connect(ip, @vehicle.on_message('STATUSTEXT') def listener(self, name, m): - status_printer(re.sub(r'(^|\n)', '>>> ', m.text.rstrip(b'\x00').decode('utf-8').rstrip())) + status_printer(re.sub(r'(^|\n)', '>>> ', m.text.decode('utf-8').rstrip())) if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) From 20ad0cd1d8a54b5fc25fbded8f3b0de12ed76628 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Tue, 23 Jan 2018 19:37:43 +0100 Subject: [PATCH 34/99] String encoding to bytes should be done in pymavlink, not here --- dronekit/__init__.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 5c189fe54..3c1c854a8 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1290,7 +1290,7 @@ def listener(_): c = 0 for i, v in enumerate(self._params_set): if v == None: - self._master.mav.param_request_read_send(0, 0, b'', i) + self._master.mav.param_request_read_send(0, 0, '', i) c += 1 if c > 50: break @@ -1317,11 +1317,8 @@ def listener(self, name, msg): self._params_duration = start_duration self._params_set[msg.param_index] = msg - # Normalize parameter name (convert to string) - param_name = msg.param_id.decode('utf8') - - self._params_map[param_name] = msg.param_value - self._parameters.notify_attribute_listeners(param_name, msg.param_value, + self._params_map[msg.param_id] = msg.param_value + self._parameters.notify_attribute_listeners(msg.param_id, msg.param_value, cache=True) except: import traceback @@ -3000,7 +2997,7 @@ def connect(ip, @vehicle.on_message('STATUSTEXT') def listener(self, name, m): - status_printer(re.sub(r'(^|\n)', '>>> ', m.text.decode('utf-8').rstrip())) + status_printer(re.sub(r'(^|\n)', '>>> ', m.text.rstrip())) if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) From 1861b047c450a6acd0f38e36c17d6c217121dccf Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Sun, 25 Mar 2018 20:57:44 +0200 Subject: [PATCH 35/99] circle.yml: use latest available Python versions https://circleci.com/docs/1.0/build-image-trusty/#python --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 2e9e6a804..89573040a 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: post: - - pyenv global 2.7.13 3.6.0 + - pyenv global 2.7.12 3.6.2 environment: SITL_SPEEDUP: 10 SITL_RATE: 200 From b238edb36db9c5d248370ddde0092b7ed82d9df5 Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Mon, 26 Mar 2018 07:24:41 +0200 Subject: [PATCH 36/99] circle.yml: these versions surely work https://github.com/dronekit/dronekit-python/commit/fb004baddbedc510e17726474e8c40af88ccb208 --- circle.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 89573040a..5ee47fc59 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: post: - - pyenv global 2.7.12 3.6.2 + - pyenv global 2.7.10 3.5.0 environment: SITL_SPEEDUP: 10 SITL_RATE: 200 From 87abf28c4e5a08dabee35c36565e6cc6162b28d6 Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Mon, 26 Mar 2018 19:25:46 +0200 Subject: [PATCH 37/99] circle.yml: fix the build - Install future beforehand as workaround to pymavlink bug: https://github.com/ArduPilot/pymavlink/issues/25 - Install dependencies before dronekit, not after --- circle.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/circle.yml b/circle.yml index 5ee47fc59..f4208dfce 100644 --- a/circle.yml +++ b/circle.yml @@ -7,8 +7,9 @@ machine: dependencies: override: - - 'pip install . -UI' + - 'pip install -UI future' - 'pip install -r requirements.txt -UI' + - 'pip install . -UI' test: override: From 689aa2240b86d8c5903768c47553869632ed2415 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 31 Mar 2018 11:39:56 +0200 Subject: [PATCH 38/99] Implement autopilot reboot + test --- dronekit/__init__.py | 15 +++++++++++++++ dronekit/test/sitl/test_reboot.py | 27 +++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 dronekit/test/sitl/test_reboot.py diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 3c1c854a8..85d101514 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2360,6 +2360,21 @@ def wait_ready(self, *types, **kwargs): return True + def reboot(self): + """Requests an autopilot reboot by sending a ``MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN`` command.""" + + reboot_msg = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, # command + 0, # confirmation + 1, # param 1, autopilot (reboot) + 0, # param 2, onboard computer (do nothing) + 0, # param 3, camera (do nothing) + 0, # param 4, mount (do nothing) + 0, 0, 0) # param 5 ~ 7 not used + + self.send_mavlink(reboot_msg) + class Gimbal(object): """ diff --git a/dronekit/test/sitl/test_reboot.py b/dronekit/test/sitl/test_reboot.py new file mode 100644 index 000000000..3a7252fdc --- /dev/null +++ b/dronekit/test/sitl/test_reboot.py @@ -0,0 +1,27 @@ +from nose.tools import assert_equal + +from dronekit import connect +from dronekit.test import with_sitl +import time + + +@with_sitl +def test_reboot(connpath): + """Tries to reboot the vehicle, and checks that the autopilot ACKs the command.""" + + vehicle = connect(connpath, wait_ready=True) + + reboot_acks = [] + + def on_ack(self, name, message): + if message.command == 246: # reboot/shutdown + reboot_acks.append(message) + + vehicle.add_message_listener('COMMAND_ACK', on_ack) + vehicle.reboot() + time.sleep(0.5) + vehicle.remove_message_listener('COMMAND_ACK', on_ack) + + assert_equal(1, len(reboot_acks)) # one and only one ACK + assert_equal(246, reboot_acks[0].command) # for the correct command + assert_equal(0, reboot_acks[0].result) # the result must be successful From 9f6572a9ea20cdeaeba93c4029b5409966d25535 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Sat, 31 Mar 2018 23:50:14 +1100 Subject: [PATCH 39/99] examples: add a reboot example --- examples/reboot/reboot.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 examples/reboot/reboot.py diff --git a/examples/reboot/reboot.py b/examples/reboot/reboot.py new file mode 100755 index 000000000..698d10142 --- /dev/null +++ b/examples/reboot/reboot.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +from __future__ import print_function + +from dronekit import connect +import time + +# Set up option parsing to get connection string +import argparse +parser = argparse.ArgumentParser(description='Reboots vehicle') +parser.add_argument('--connect', + help="Vehicle connection target string. If not specified, SITL automatically started and used.") +args = parser.parse_args() + +connection_string = args.connect +sitl = None + + +# Start SITL if no connection string specified +if not connection_string: + import dronekit_sitl + sitl = dronekit_sitl.start_default() + connection_string = sitl.connection_string() + + +# Connect to the Vehicle +print('Connecting to vehicle on: %s' % connection_string) +vehicle = connect(connection_string, wait_ready=True) + +vehicle.reboot() +time.sleep(1) + +# Shut down simulator if it was started. +if sitl: + sitl.stop() From ac6d4aeaad50ca56a5d54af0268c316de8ef76ba Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Wed, 11 Apr 2018 21:14:29 +0200 Subject: [PATCH 40/99] Upgrade CircleCI configuration to version 2.0 (#810) * Upgrade CircleCI config to version 2.0 - Parallel Python 2, Python 3 builds - Well-defined environments using Docker - CircleCI 1.0 will be deprecated soon * config.yml: disable Python 3 testing Comment out Python 3 testing until support is ready. Otherwise, the "deploy" step will fail. --- .circleci/config.yml | 87 ++++++++++++++++++++++++++++++++++++++++++++ circle.yml | 34 ----------------- 2 files changed, 87 insertions(+), 34 deletions(-) create mode 100644 .circleci/config.yml delete mode 100644 circle.yml diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 000000000..f386bc9e0 --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,87 @@ +# CircleCI 2.0 configuration file for dronekit-python + +# Steps common to both Python 2 and Python 3 +common: &commonsteps + steps: + - checkout + + - run: + name: Install global tools + command: | + pip install -U virtualenv + + - run: + name: Install dronekit with dependencies + command: | + virtualenv venv + source venv/bin/activate + pip install -UI future + pip install -r requirements.txt -UI + pip install . -UI + + - run: + name: Run dronekit tests + environment: + SITL_SPEEDUP: 10 + SITL_RATE: 200 + command: | + source venv/bin/activate + nosetests -svx dronekit.test.unit + nosetests -svx dronekit.test.sitl + + - run: + name: Build documentation + command: | + source venv/bin/activate + cd docs; make clean; make html + + - store_artifacts: + path: test-reports + destination: test-reports + +# Jobs definition +version: 2 +jobs: + python2: + docker: + - image: circleci/python:2.7-stretch + working_directory: ~/dronekit-python2 + <<: *commonsteps + +# python3: +# docker: +# - image: circleci/python:3.6-stretch +# working_directory: ~/dronekit-python3 +# <<: *commonsteps + + deploy: + name: Deploy to dronekit.io + working_directory: ~/deploy + machine: true + steps: + - checkout + - run: + name: update docs + command: ./scripts/update-docs.sh + +# Send a notification on Gitter +notify: + webhooks: + - url: https://webhooks.gitter.im/e/27b0e1a9fede99dbbe6c + +# Workflow definition +# Run Python 2 and Python 3 testing in parallel +# and deploy if the Python 2 build succeeds +workflows: + version: 2 + build_test_deploy: + jobs: + - python2 +# - python3 + - deploy: + requires: + - python2 + filters: + branches: + only: + - master diff --git a/circle.yml b/circle.yml deleted file mode 100644 index f4208dfce..000000000 --- a/circle.yml +++ /dev/null @@ -1,34 +0,0 @@ -machine: - post: - - pyenv global 2.7.10 3.5.0 - environment: - SITL_SPEEDUP: 10 - SITL_RATE: 200 - -dependencies: - override: - - 'pip install -UI future' - - 'pip install -r requirements.txt -UI' - - 'pip install . -UI' - -test: - override: - # docs - - 'cd docs; make clean; make html' - - # code - - 'nosetests -svx dronekit.test.unit' - - 'nosetests -svx dronekit.test.sitl' - -general: - build_dir: . - -deployment: - production: - branch: master - commands: - - ./scripts/update-docs.sh - -notify: - webhooks: - - url: https://webhooks.gitter.im/e/27b0e1a9fede99dbbe6c From 0d4a368dde1cbd2c2741739cba6efe2cd91d4b1a Mon Sep 17 00:00:00 2001 From: Ramon Roche Date: Wed, 11 Apr 2018 12:31:39 -0700 Subject: [PATCH 41/99] disable docs deploy from circleci (#814) we are migrating service providers and need to disable deployments of docs --- .circleci/config.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index f386bc9e0..21c28075f 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -78,10 +78,11 @@ workflows: jobs: - python2 # - python3 - - deploy: - requires: - - python2 - filters: - branches: - only: - - master +# disabling until we find a new docs server +# - deploy: +# requires: +# - python2 +# filters: +# branches: +# only: +# - master From 8f5fa48e675dac3a270517f5c093fd5785f98f5c Mon Sep 17 00:00:00 2001 From: Ramon Roche Date: Wed, 11 Apr 2018 12:52:54 -0700 Subject: [PATCH 42/99] travisci: disable python3 environment tests (#815) TODO: re enable tests once we fix pymavlink --- .travis.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9fc8157b9..a230b369c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,11 +7,11 @@ env: python: - 2.7 - - 3.6 + #- 3.6 before_install: - pip install --upgrade pip - + install: - pip install -r requirements.txt - pip install flake8 @@ -38,9 +38,9 @@ notifications: on_failure: always on_start: never -matrix: - allow_failures: - - python: 3.6 +#matrix: + #allow_failures: + #- python: 3.6 branches: only: From 32b6ba10713b35f8cd61492bab5e5235c5e149cc Mon Sep 17 00:00:00 2001 From: michael-hart Date: Tue, 15 May 2018 15:27:52 +0100 Subject: [PATCH 43/99] Home location set command corrected param1 should have value 0 rather than 2 --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 85d101514..44d70e2d7 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1969,7 +1969,7 @@ def home_location(self, pos): 0, 0, # target system, target component mavutil.mavlink.MAV_CMD_DO_SET_HOME, # command 0, # confirmation - 2, # param 1: 1 to use current position, 2 to use the entered values. + 0, # param 1: 1 to use current position, 0 to use the entered values. 0, 0, 0, # params 2-4 pos.lat, pos.lon, pos.alt)) From a20eadf92b5d30940a7533a8a57a39273cdf3938 Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Thu, 2 Aug 2018 14:15:21 +0200 Subject: [PATCH 44/99] __init__.py: rename variable "await" As of Python 3.7, "await" is a reserved word (PEP 492). --- dronekit/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 85d101514..8f11fe69a 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2347,9 +2347,9 @@ def wait_ready(self, *types, **kwargs): raise ValueError('wait_ready expects one or more string arguments.') # Wait for these attributes to have been set. - await = set(types) + await_attributes = set(types) start = monotonic.monotonic() - while not await.issubset(self._ready_attrs): + while not await_attributes.issubset(self._ready_attrs): time.sleep(0.1) if monotonic.monotonic() - start > timeout: if raise_exception: From 7000397ad04441eb1531ca7e546fa7dbdfd88986 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 20 Oct 2018 10:43:39 +0200 Subject: [PATCH 45/99] Properly close Vehicle instances after SITL tests If Vehicle instances are left unclosed, the latest pymavlink (2.2.20) will spam a lot of "EOF on TCP socket" warning messages: https://github.com/ArduPilot/pymavlink/issues/230 --- dronekit/test/sitl/test_capability_and_version.py | 2 ++ dronekit/test/sitl/test_locations.py | 2 ++ dronekit/test/sitl/test_mavlink.py | 3 +++ dronekit/test/sitl/test_mode_settings.py | 2 ++ dronekit/test/sitl/test_reboot.py | 2 ++ dronekit/test/sitl/test_state.py | 2 ++ dronekit/test/sitl/test_timeout.py | 2 ++ dronekit/test/sitl/test_waypoints.py | 4 ++++ 8 files changed, 19 insertions(+) diff --git a/dronekit/test/sitl/test_capability_and_version.py b/dronekit/test/sitl/test_capability_and_version.py index ed466cdd3..1aa1cd531 100644 --- a/dronekit/test/sitl/test_capability_and_version.py +++ b/dronekit/test/sitl/test_capability_and_version.py @@ -34,3 +34,5 @@ def test_115(connpath): assert_true(v.version.major is not None) assert_true(len(v.version.release_type()) >= 2) assert_true(v.version.release_version() is not None) + + v.close() diff --git a/dronekit/test/sitl/test_locations.py b/dronekit/test/sitl/test_locations.py index c1e5ef2b7..326b62b8b 100644 --- a/dronekit/test/sitl/test_locations.py +++ b/dronekit/test/sitl/test_locations.py @@ -83,3 +83,5 @@ def callback(*args): wait_for(lambda : ret['success'], 30) assert ret['success'], 'Expected location object to emit notifications.' + + vehicle.close() diff --git a/dronekit/test/sitl/test_mavlink.py b/dronekit/test/sitl/test_mavlink.py index ac9330253..6ddf2d442 100644 --- a/dronekit/test/sitl/test_mavlink.py +++ b/dronekit/test/sitl/test_mavlink.py @@ -27,3 +27,6 @@ def callback(*args): i -= 1 assert result['success'] + + vehicle2.close() + vehicle.close() diff --git a/dronekit/test/sitl/test_mode_settings.py b/dronekit/test/sitl/test_mode_settings.py index da7ec794c..95392c36e 100644 --- a/dronekit/test/sitl/test_mode_settings.py +++ b/dronekit/test/sitl/test_mode_settings.py @@ -13,3 +13,5 @@ def listener(self, name, m): assert_equals('STABILIZE', self._flightmode) vehicle.add_message_listener('HEARTBEAT', listener) + + vehicle.close() diff --git a/dronekit/test/sitl/test_reboot.py b/dronekit/test/sitl/test_reboot.py index 3a7252fdc..bf9236c8e 100644 --- a/dronekit/test/sitl/test_reboot.py +++ b/dronekit/test/sitl/test_reboot.py @@ -25,3 +25,5 @@ def on_ack(self, name, message): assert_equal(1, len(reboot_acks)) # one and only one ACK assert_equal(246, reboot_acks[0].command) # for the correct command assert_equal(0, reboot_acks[0].result) # the result must be successful + + vehicle.close() diff --git a/dronekit/test/sitl/test_state.py b/dronekit/test/sitl/test_state.py index 8f6502856..850f9da58 100644 --- a/dronekit/test/sitl/test_state.py +++ b/dronekit/test/sitl/test_state.py @@ -13,3 +13,5 @@ def test_state(connpath): assert_equals(type(vehicle.system_status), SystemStatus) assert_equals(type(vehicle.system_status.state), str) + + vehicle.close() diff --git a/dronekit/test/sitl/test_timeout.py b/dronekit/test/sitl/test_timeout.py index b6d539682..d36b78ca1 100644 --- a/dronekit/test/sitl/test_timeout.py +++ b/dronekit/test/sitl/test_timeout.py @@ -35,6 +35,8 @@ def test_timeout_empty(): # Connect with timeout of 10s. vehicle = connect('tcp:127.0.0.1:5760', wait_ready=True, heartbeat_timeout=20) + vehicle.close() + # Should not pass assert False except: diff --git a/dronekit/test/sitl/test_waypoints.py b/dronekit/test/sitl/test_waypoints.py index 61976fbbd..288509b98 100644 --- a/dronekit/test/sitl/test_waypoints.py +++ b/dronekit/test/sitl/test_waypoints.py @@ -41,6 +41,8 @@ def test_set_home(connpath): assert_equals(vehicle.home_location.lon, 149) assert_equals(vehicle.home_location.alt, 600) + vehicle.close() + @with_sitl def test_parameter(connpath): @@ -139,3 +141,5 @@ def assert_commands(count): vehicle.flush() # Send commands assert_commands(1) + + vehicle.close() From d52ebda3e991b88c154f81f1e24bfb4d6951c4ad Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 20 Oct 2018 11:03:45 +0200 Subject: [PATCH 46/99] Update pymavlink for Python 3 support --- .circleci/config.yml | 12 ++++++------ requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 21c28075f..31203edc5 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -48,11 +48,11 @@ jobs: working_directory: ~/dronekit-python2 <<: *commonsteps -# python3: -# docker: -# - image: circleci/python:3.6-stretch -# working_directory: ~/dronekit-python3 -# <<: *commonsteps + python3: + docker: + - image: circleci/python:3.6-stretch + working_directory: ~/dronekit-python3 + <<: *commonsteps deploy: name: Deploy to dronekit.io @@ -77,7 +77,7 @@ workflows: build_test_deploy: jobs: - python2 -# - python3 + - python3 # disabling until we find a new docs server # - deploy: # requires: diff --git a/requirements.txt b/requirements.txt index b621f67c5..7b67b3550 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -pymavlink>=2.2.3 +pymavlink>=2.2.20 monotonic>=1.3 future>=0.15.2 nose==1.3.7 diff --git a/setup.py b/setup.py index 3824ee523..8b4805b32 100644 --- a/setup.py +++ b/setup.py @@ -11,7 +11,7 @@ url='https://github.com/dronekit/dronekit-python', author='3D Robotics', install_requires=[ - 'pymavlink>=2.2.3', + 'pymavlink>=2.2.20', 'monotonic==1.2', 'future==0.15.2' ], From d33778858d42b5d263933c7ce0754ab7f57d0fb7 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 28 Oct 2018 08:35:27 +0100 Subject: [PATCH 47/99] mavlink.py: efficient I/O waiting with select() pymavlink uses non-blocking sockets and serial ports: polling for data in a while loop with a sleep(0.05) is inefficient and leads to increased latency for incoming MAVLink messages (issue #863). --- dronekit/mavlink.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index 7cff501df..b27ec83bf 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -203,13 +203,13 @@ def mavlink_thread_in(): # Huge try catch in case we see http://bugs.python.org/issue1856 try: while self._alive: - # Downtime - time.sleep(0.05) - # Loop listeners. for fn in self.loop_listeners: fn(self) + # Sleep + self.master.select(0.05) + while self._accept_input: try: msg = self.master.recv_msg() From 883fadc88af181296a9e437bfef124180ec0c92d Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Mon, 29 Oct 2018 14:24:26 +1100 Subject: [PATCH 48/99] Correct comment on play_tune --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b2e0cf36b..3bbc0927d 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2300,7 +2300,7 @@ def send_capabilities_request(self, vehicle, name, m): vehicle.send_mavlink(capability_msg) def play_tune(self, tune): - '''Request an AUTOPILOT_VERSION packet''' + '''Play a tune on the vehicle''' msg = self.message_factory.play_tune_encode(0, 0, tune) self.send_mavlink(msg) From a8f3907a562ad714d1f21b16c971cb236f72884f Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 9 Nov 2017 14:37:49 +1100 Subject: [PATCH 49/99] Add still-waiting interval and callback to wait_ready --- dronekit/__init__.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 3bbc0927d..b66ec9ad8 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2349,14 +2349,24 @@ def wait_ready(self, *types, **kwargs): # Wait for these attributes to have been set. await_attributes = set(types) start = monotonic.monotonic() + still_waiting_last_message_sent = start + still_waiting_callback = kwargs.get('still_waiting_callback') + still_waiting_message_interval = kwargs.get('still_waiting_interval', 1) + while not await_attributes.issubset(self._ready_attrs): time.sleep(0.1) - if monotonic.monotonic() - start > timeout: + now = monotonic.monotonic() + if now - start > timeout: if raise_exception: raise TimeoutError('wait_ready experienced a timeout after %s seconds.' % timeout) else: return False + if (still_waiting_callback and + now - still_waiting_last_message_sent > still_waiting_message_interval): + still_waiting_last_message_sent = now + if still_waiting_callback: + still_waiting_callback(await-self._ready_attrs) return True @@ -2941,9 +2951,15 @@ def __setitem__(self, index, value): from dronekit.mavlink import MAVConnection +def default_still_waiting_callback(atts): + print("Still waiting for data from vehicle: %s" % ','.join(atts), + file=sys.stderr) + def connect(ip, _initialize=True, wait_ready=None, + still_waiting_callback=default_still_waiting_callback, + still_waiting_interval=1, status_printer=errprinter, vehicle_class=None, rate=4, @@ -3019,7 +3035,8 @@ def listener(self, name, m): if wait_ready: if wait_ready == True: - vehicle.wait_ready(True) + vehicle.wait_ready(still_waiting_interval=still_waiting_interval, + still_waiting_callback=still_waiting_callback) else: vehicle.wait_ready(*wait_ready) From e7e5ab1ea43b9b99249623cb6ed160a834170a02 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 9 Nov 2017 16:59:50 +1100 Subject: [PATCH 50/99] Add timeout to kwargs in connect, pass to wait_ready --- dronekit/__init__.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b66ec9ad8..8aa66431e 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2958,6 +2958,7 @@ def default_still_waiting_callback(atts): def connect(ip, _initialize=True, wait_ready=None, + timeout=30, still_waiting_callback=default_still_waiting_callback, still_waiting_interval=1, status_printer=errprinter, @@ -3036,7 +3037,8 @@ def listener(self, name, m): if wait_ready: if wait_ready == True: vehicle.wait_ready(still_waiting_interval=still_waiting_interval, - still_waiting_callback=still_waiting_callback) + still_waiting_callback=still_waiting_callback, + timeout=timeout) else: vehicle.wait_ready(*wait_ready) From 63e913b1b5bddfb8e771641d883934789a93d5db Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 9 Nov 2017 17:00:31 +1100 Subject: [PATCH 51/99] examples/follow_me: set timeout on connect to 300 --- examples/follow_me/follow_me.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/follow_me/follow_me.py b/examples/follow_me/follow_me.py index aa489d26b..ef1227bce 100644 --- a/examples/follow_me/follow_me.py +++ b/examples/follow_me/follow_me.py @@ -40,7 +40,7 @@ # Connect to the Vehicle print('Connecting to vehicle on: %s' % connection_string) -vehicle = connect(connection_string, wait_ready=True) +vehicle = connect(connection_string, wait_ready=True, timeout=300) From 513ab4ef68bd5b578ea08ed481b471091db1e44b Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 1 Nov 2018 08:23:34 +1100 Subject: [PATCH 52/99] fixup! Add still-waiting interval and callback to wait_ready --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 8aa66431e..dcba106a9 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2366,7 +2366,7 @@ def wait_ready(self, *types, **kwargs): now - still_waiting_last_message_sent > still_waiting_message_interval): still_waiting_last_message_sent = now if still_waiting_callback: - still_waiting_callback(await-self._ready_attrs) + still_waiting_callback(await_attributes-self._ready_attrs) return True From 6eaa942e9015df7f1bb0861d0809ff238ebbebbb Mon Sep 17 00:00:00 2001 From: pietrodn Date: Tue, 30 Oct 2018 22:45:42 +0100 Subject: [PATCH 53/99] Faster comparisons with None/True/False, various performance fixes --- dronekit/__init__.py | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index dcba106a9..51fdf2d9c 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -304,7 +304,7 @@ def __init__(self, raw_version, autopilot_type, vehicle_type): self.autopilot_type = autopilot_type self.vehicle_type = vehicle_type self.raw_version = raw_version - if(raw_version == None): + if raw_version is None: self.major = None self.minor = None self.patch = None @@ -640,7 +640,7 @@ def notify_attribute_listeners(self, attr_name, value, cache=False): """ # Cached values are not re-sent if they are unchanged. if cache: - if attr_name in self._attribute_cache and self._attribute_cache[attr_name] == value: + if self._attribute_cache.get(attr_name) == value: return self._attribute_cache[attr_name] = value @@ -885,7 +885,7 @@ def listener(vehicle, name, m): vehicle.notify_attribute_listeners('location.global_relative_frame', vehicle.location.global_relative_frame) - if self._alt != None or m.alt != 0: + if self._alt is not None or m.alt != 0: # Require first alt value to be non-0 # TODO is this the proper check to do? self._alt = m.alt / 1000.0 @@ -1197,7 +1197,7 @@ def listener(self, name, m): self.notify_attribute_listeners('armed', self.armed, cache=True) self._autopilot_type = m.autopilot self._vehicle_type = m.type - if self._is_mode_available(m.custom_mode, m.base_mode) == False: + if self._is_mode_available(m.custom_mode, m.base_mode) is False: raise APIException("mode (%s, %s) not available on mavlink definition" % (m.custom_mode, m.base_mode)) if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_PX4: self._flightmode = mavutil.interpret_px4_mode(m.base_mode, m.custom_mode) @@ -1254,7 +1254,7 @@ def listener(self, name, msg): # Waypoint send to master @self.on_message(['WAYPOINT_REQUEST', 'MISSION_REQUEST']) def listener(self, name, msg): - if self._wp_uploaded != None: + if self._wp_uploaded is not None: wp = self._wploader.wp(msg.seq) handler.fix_targets(wp) self._master.mav.send(wp) @@ -1282,7 +1282,7 @@ def listener(_): if not self._params_start: return - if None not in self._params_set and not self._params_loaded: + if not self._params_loaded and all(x is not None for x in self._params_set): self._params_loaded = True self.notify_attribute_listeners('parameters', self.parameters) @@ -1312,7 +1312,7 @@ def listener(self, name, msg): # we lack a param_id. try: if msg.param_index < msg.param_count and msg: - if self._params_set[msg.param_index] == None: + if self._params_set[msg.param_index] is None: self._params_last = monotonic.monotonic() self._params_duration = start_duration self._params_set[msg.param_index] = msg @@ -1350,7 +1350,7 @@ def listener(_): 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: + if self._heartbeat_timeout is False: errprinter('>>> Link timeout, no heartbeat in last %s seconds' % self._heartbeat_warning) self._heartbeat_timeout = True @@ -1673,7 +1673,7 @@ def battery(self): """ Current system batter status (:py:class:`Battery`). """ - if self._voltage == None or self._current == None or self._level == None: + if self._voltage is None or self._current is None or self._level is None: return None return Battery(self._voltage, self._current, self._level) @@ -2180,9 +2180,9 @@ def simple_goto(self, location, airspeed=None, groundspeed=None): 0, 0, 0, location.lat, location.lon, alt) - if airspeed != None: + if airspeed is not None: self.airspeed = airspeed - if groundspeed != None: + if groundspeed is not None: self.groundspeed = groundspeed def send_mavlink(self, message): @@ -2271,7 +2271,7 @@ def initialize(self, rate=4, heartbeat_timeout=30): time.sleep(0.1) # Initialize data stream. - if rate != None: + if rate is not None: self._master.mav.request_data_stream_send(0, 0, mavutil.mavlink.MAV_DATA_STREAM_ALL, rate, 1) @@ -3035,7 +3035,7 @@ def listener(self, name, m): vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) if wait_ready: - if wait_ready == True: + if wait_ready is True: vehicle.wait_ready(still_waiting_interval=still_waiting_interval, still_waiting_callback=still_waiting_callback, timeout=timeout) From 3f89410a1f29c65029206010e82516865e406387 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Thu, 1 Nov 2018 00:14:04 +0100 Subject: [PATCH 54/99] Fix virtualenv installation for CircleCI --- .circleci/config.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 31203edc5..825f26624 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -5,11 +5,6 @@ common: &commonsteps steps: - checkout - - run: - name: Install global tools - command: | - pip install -U virtualenv - - run: name: Install dronekit with dependencies command: | From b559bf1f4ce2eeefe7b6898d6e6de84eb6a8113d Mon Sep 17 00:00:00 2001 From: pietrodn Date: Thu, 1 Nov 2018 01:04:06 +0100 Subject: [PATCH 55/99] Travis: build for Python 3; resolve #816 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a230b369c..16dfd6d8b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,7 +7,7 @@ env: python: - 2.7 - #- 3.6 + - 3.6 before_install: - pip install --upgrade pip From 16d6a793e5132e24263754d4af68b3d81e58b014 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Thu, 1 Nov 2018 10:17:56 +0100 Subject: [PATCH 56/99] mavlink.py: specific exception handling for MAVError --- dronekit/mavlink.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index b27ec83bf..f19d1a5ae 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -218,11 +218,15 @@ def mavlink_thread_in(): if error.errno == ECONNABORTED: raise APIException('Connection aborting during send') raise - except Exception as e: - # TODO this should be more rigorous. How to avoid + except mavutil.mavlink.MAVError as e: + # Avoid # invalid MAVLink prefix '73' # invalid MAVLink prefix '13' - # errprinter('mav recv error:', e) + #errprinter('mav recv error:', e) + msg = None + except Exception as e: + # Log any other unexpected exception + errprinter('>>> Exception while receiving message: ', e) msg = None if not msg: break From 945b2f8ed67330a3decffde8ace906d098f7f4fd Mon Sep 17 00:00:00 2001 From: pietrodn Date: Thu, 1 Nov 2018 13:10:50 +0100 Subject: [PATCH 57/99] PEP8 and style improvements --- dronekit/__init__.py | 193 ++++++++---------- dronekit/mavlink.py | 15 +- dronekit/test/__init__.py | 7 +- dronekit/test/sitl/__init__.py | 1 - dronekit/test/sitl/test_110.py | 6 +- dronekit/test/sitl/test_115.py | 2 - dronekit/test/sitl/test_12.py | 4 +- .../test/sitl/test_capability_and_version.py | 4 +- dronekit/test/sitl/test_channels.py | 7 +- dronekit/test/sitl/test_earlyattrs.py | 6 +- dronekit/test/sitl/test_locations.py | 10 +- dronekit/test/sitl/test_mavlink.py | 2 - dronekit/test/sitl/test_mode_settings.py | 2 - dronekit/test/sitl/test_modeavailable.py | 11 +- dronekit/test/sitl/test_parameters.py | 4 +- dronekit/test/sitl/test_simpledemo.py | 3 - dronekit/test/sitl/test_state.py | 6 +- dronekit/test/sitl/test_timeout.py | 4 +- dronekit/test/sitl/test_vehicleclass.py | 1 - dronekit/test/sitl/test_waypoints.py | 3 +- dronekit/test/unit/__init__.py | 1 - dronekit/test/unit/test_api.py | 2 - dronekit/util.py | 1 + 23 files changed, 123 insertions(+), 172 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 51fdf2d9c..17dbf2090 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -34,17 +34,10 @@ import collections import copy import math -import os import struct -import platform -from queue import Queue, Empty import re -import socket import sys -import threading -from threading import Thread import time -import types import monotonic from past.builtins import basestring @@ -197,7 +190,7 @@ def distance_home(self): if self.north is not None and self.east is not None: if self.down is not None: - return math.sqrt(self.north**2 + self.east**2 + self.down**2) + return math.sqrt(self.north**2 + self.east**2 + self.down**2) else: return math.sqrt(self.north**2 + self.east**2) @@ -270,6 +263,7 @@ def __init__(self, distance, voltage): def __str__(self): return "Rangefinder: distance={}, voltage={}".format(self.distance, self.voltage) + class Version(object): """ Autopilot version and type. @@ -322,7 +316,6 @@ def is_stable(self): """ return self.release == 255 - def release_version(self): """ Returns the version within the release type (an integer). @@ -330,38 +323,37 @@ def release_version(self): """ if self.release is None: return None - if(self.release == 255): + if self.release == 255: return 0 return self.release % 64 - def release_type(self): """ Returns text describing the release type e.g. "alpha", "stable" etc. """ if self.release is None: return None - types = [ "dev", "alpha", "beta", "rc" ] + types = ["dev", "alpha", "beta", "rc"] return types[self.release >> 6] def __str__(self): - prefix="" + prefix = "" - if(self.autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA): + if self.autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA: prefix += "APM:" - elif(self.autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_PX4): + elif self.autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_PX4: prefix += "PX4" else: prefix += "UnknownAutoPilot" - if(self.vehicle_type == mavutil.mavlink.MAV_TYPE_QUADROTOR): + if self.vehicle_type == mavutil.mavlink.MAV_TYPE_QUADROTOR: prefix += "Copter-" - elif(self.vehicle_type == mavutil.mavlink.MAV_TYPE_FIXED_WING): + elif self.vehicle_type == mavutil.mavlink.MAV_TYPE_FIXED_WING: prefix += "Plane-" - elif(self.vehicle_type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER): + elif self.vehicle_type == mavutil.mavlink.MAV_TYPE_GROUND_ROVER: prefix += "Rover-" else: - prefix += "UnknownVehicleType%d-" % (self.vehicle_type) + prefix += "UnknownVehicleType%d-" % self.vehicle_type if self.release_type() is None: release_type = "UnknownReleaseType" @@ -373,6 +365,7 @@ def __str__(self): return prefix + "%s.%s.%s" % (self.major, self.minor, self.patch) + release_type + class Capabilities: """ Autopilot capabilities (supported message types and functionality). @@ -542,8 +535,6 @@ def __init__(self): self._attribute_listeners = {} self._attribute_cache = {} - - def add_attribute_listener(self, attr_name, observer): """ Add an attribute listener callback. @@ -587,12 +578,12 @@ def location_callback(self, attr_name, msg): :param observer: The callback to invoke when a change in the attribute is detected. """ - l = self._attribute_listeners.get(attr_name) - if l is None: - l = [] - self._attribute_listeners[attr_name] = l - if not observer in l: - l.append(observer) + listeners_for_attr = self._attribute_listeners.get(attr_name) + if listeners_for_attr is None: + listeners_for_attr = [] + self._attribute_listeners[attr_name] = listeners_for_attr + if observer not in listeners_for_attr: + listeners_for_attr.append(observer) def remove_attribute_listener(self, attr_name, observer): """ @@ -611,10 +602,10 @@ def remove_attribute_listener(self, attr_name, observer): :param observer: The callback function to remove. """ - l = self._attribute_listeners.get(attr_name) - if l is not None: - l.remove(observer) - if len(l) == 0: + listeners_for_attr = self._attribute_listeners.get(attr_name) + if listeners_for_attr is not None: + listeners_for_attr.remove(observer) + if len(listeners_for_attr) == 0: del self._attribute_listeners[attr_name] def notify_attribute_listeners(self, attr_name, value, cache=False): @@ -695,7 +686,7 @@ def attitude_listener(self, name, msg): See :ref:`vehicle_state_observe_attributes` for more information. - :param String attr_name: The name of the attribute to watch (or '*' to watch all attributes). + :param String name: The name of the attribute to watch (or '*' to watch all attributes). :param observer: The callback to invoke when a change in the attribute is detected. """ @@ -730,7 +721,7 @@ def __getitem__(self, key): return dict.__getitem__(self, str(key)) def __setitem__(self, key, value): - if not (int(key) > 0 and int(key) <= self._count): + if not (0 < int(key) <= self._count): raise KeyError('Invalid channel index %s' % key) if not value: try: @@ -1022,7 +1013,7 @@ def __init__(self, handler): # Cache all updated attributes for wait_ready. # By default, we presume all "commands" are loaded. - self._ready_attrs = set(['commands']) + self._ready_attrs = {'commands'} # Default parameters when calling wait_ready() or wait_ready(True). self._default_ready_attrs = ['parameters', 'gps_0', 'armed', 'mode', 'attitude'] @@ -1099,7 +1090,7 @@ def listener(self, name, m): self.notify_attribute_listeners('mount', self.mount_status) self._capabilities = None - self._raw_version =None + self._raw_version = None self._autopilot_version_msg_count = 0 @self.on_message('AUTOPILOT_VERSION') @@ -1185,8 +1176,8 @@ def listener(self, name, m): self._flightmode = 'AUTO' self._armed = False self._system_status = None - self._autopilot_type = None#PX4, ArduPilot, etc. - self._vehicle_type = None#quadcopter, plane, etc. + self._autopilot_type = None # PX4, ArduPilot, etc. + self._vehicle_type = None # quadcopter, plane, etc. @self.on_message('HEARTBEAT') def listener(self, name, m): @@ -1223,10 +1214,9 @@ def listener(self, name, msg): self._wploader.expected_count = msg.count self._master.waypoint_request_send(0) - @self.on_message(['HOME_POSITION']) def listener(self, name, msg): - self._home_location = LocationGlobal(msg.latitude/1.0e7, msg.longitude/1.0e7, msg.altitude/1000.0); + self._home_location = LocationGlobal(msg.latitude / 1.0e7, msg.longitude / 1.0e7, msg.altitude / 1000.0) self.notify_attribute_listeners('home_location', self.home_location, cache=True) @self.on_message(['WAYPOINT', 'MISSION_ITEM']) @@ -1289,7 +1279,7 @@ def listener(_): if not self._params_loaded and monotonic.monotonic() - self._params_last > self._params_duration: c = 0 for i, v in enumerate(self._params_set): - if v == None: + if v is None: self._master.mav.param_request_read_send(0, 0, '', i) c += 1 if c > 50: @@ -1345,8 +1335,7 @@ def listener(_): # Timeouts. if self._heartbeat_started: - if self._heartbeat_error and self._heartbeat_error > 0 and monotonic.monotonic( - ) - self._heartbeat_lastreceived > self._heartbeat_error: + if self._heartbeat_error and monotonic.monotonic() - self._heartbeat_lastreceived > self._heartbeat_error > 0: raise APIException('No heartbeat in %s seconds, aborting.' % self._heartbeat_error) elif monotonic.monotonic() - self._heartbeat_lastreceived > self._heartbeat_warning: @@ -1523,7 +1512,6 @@ def notify_message_listeners(self, name, msg): msg.get_type()) errprinter('>>> ' + str(e)) - def close(self): return self._handler.close() @@ -1812,20 +1800,19 @@ def groundspeed(self): @groundspeed.setter def groundspeed(self, speed): - speed_type = 1 # ground speed + speed_type = 1 # ground speed msg = self.message_factory.command_long_encode( 0, 0, # target system, target component - mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, #command - 0, #confirmation - speed_type, #param 1 - speed, # speed in metres/second - -1, 0, 0, 0, 0 #param 3 - 7 - ) + mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, # command + 0, # confirmation + speed_type, # param 1 + speed, # speed in metres/second + -1, 0, 0, 0, 0 # param 3 - 7 + ) # send command to vehicle self.send_mavlink(msg) - @property def airspeed(self): """ @@ -1839,15 +1826,15 @@ def airspeed(self): @airspeed.setter def airspeed(self, speed): - speed_type = 0 # air speed + speed_type = 0 # air speed msg = self.message_factory.command_long_encode( 0, 0, # target system, target component - mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, #command - 0, #confirmation - speed_type, #param 1 - speed, # speed in metres/second - -1, 0, 0, 0, 0 #param 3 - 7 - ) + mavutil.mavlink.MAV_CMD_DO_CHANGE_SPEED, # command + 0, # confirmation + speed_type, # param 1 + speed, # speed in metres/second + -1, 0, 0, 0, 0 # param 3 - 7 + ) # send command to vehicle self.send_mavlink(msg) @@ -2084,12 +2071,12 @@ def get_alt(): def check_alt(): cur = get_alt() - delta = abs(alt-cur) + delta = abs(alt - cur) return ( (delta < epsilon) or - (start < alt and cur > alt) or - (start > alt and cur < alt) + (cur > alt > start) or + (cur < alt < start) ) start = get_alt() @@ -2131,7 +2118,7 @@ def simple_takeoff(self, alt=None): if math.isnan(altitude) or math.isinf(altitude): raise ValueError("Altitude was NaN or Infinity. Please provide a real number") self._master.mav.command_long_send(0, 0, mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, - 0, 0, 0, 0, 0, 0, 0, altitude) + 0, 0, 0, 0, 0, 0, 0, altitude) def simple_goto(self, location, airspeed=None, groundspeed=None): ''' @@ -2363,10 +2350,10 @@ def wait_ready(self, *types, **kwargs): else: return False if (still_waiting_callback and - now - still_waiting_last_message_sent > still_waiting_message_interval): + now - still_waiting_last_message_sent > still_waiting_message_interval): still_waiting_last_message_sent = now if still_waiting_callback: - still_waiting_callback(await_attributes-self._ready_attrs) + still_waiting_callback(await_attributes - self._ready_attrs) return True @@ -2476,22 +2463,23 @@ def rotate(self, pitch, roll, yaw): :param yaw: Gimbal yaw in degrees relative to *global frame* (0 is North, 90 is West, 180 is South etc.) """ msg = self._vehicle.message_factory.mount_configure_encode( - 0, 1, # target system, target component - mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING, #mount_mode - 1, # stabilize roll - 1, # stabilize pitch - 1, # stabilize yaw - ) + 0, 1, # target system, target component + mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING, #mount_mode + 1, # stabilize roll + 1, # stabilize pitch + 1, # stabilize yaw + ) self._vehicle.send_mavlink(msg) msg = self._vehicle.message_factory.mount_control_encode( - 0, 1, # target system, target component - pitch * 100, # pitch is in centidegrees - roll * 100, # roll - yaw * 100, # yaw is in centidegrees - 0) # save position + 0, 1, # target system, target component + pitch * 100, # pitch is in centidegrees + roll * 100, # roll + yaw * 100, # yaw is in centidegrees + 0 # save position + ) self._vehicle.send_mavlink(msg) - def target_location(self,roi): + def target_location(self, roi): """ Point the gimbal at a specific region of interest (ROI). @@ -2508,17 +2496,17 @@ def target_location(self,roi): :param roi: Target location in global relative frame. """ - #set gimbal to targeting mode + # set gimbal to targeting mode msg = self._vehicle.message_factory.mount_configure_encode( - 0, 1, # target system, target component - mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT, #mount_mode - 1, # stabilize roll - 1, # stabilize pitch - 1, # stabilize yaw - ) + 0, 1, # target system, target component + mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT, # mount_mode + 1, # stabilize roll + 1, # stabilize pitch + 1, # stabilize yaw + ) self._vehicle.send_mavlink(msg) - #Get altitude relative to home irrespective of Location object passed in. + # Get altitude relative to home irrespective of Location object passed in. if isinstance(roi, LocationGlobalRelative): alt = roi.alt elif isinstance(roi, LocationGlobal): @@ -2529,16 +2517,16 @@ def target_location(self,roi): else: raise ValueError('Expecting location to be LocationGlobal or LocationGlobalRelative.') - #set the ROI + # set the ROI msg = self._vehicle.message_factory.command_long_encode( - 0, 1, # target system, target component - mavutil.mavlink.MAV_CMD_DO_SET_ROI, #command - 0, #confirmation - 0, 0, 0, 0, #params 1-4 - roi.lat, - roi.lon, - alt - ) + 0, 1, # target system, target component + mavutil.mavlink.MAV_CMD_DO_SET_ROI, # command + 0, # confirmation + 0, 0, 0, 0, # params 1-4 + roi.lat, + roi.lon, + alt + ) self._vehicle.send_mavlink(msg) def release(self): @@ -2549,12 +2537,12 @@ def release(self): or :py:func:`target_location`. Control will automatically be released if you change vehicle mode. """ msg = self._vehicle.message_factory.mount_configure_encode( - 0, 1, # target system, target component - mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING, #mount_mode - 1, # stabilize roll - 1, # stabilize pitch - 1, # stabilize yaw - ) + 0, 1, # target system, target component + mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING, # mount_mode + 1, # stabilize roll + 1, # stabilize pitch + 1, # stabilize yaw + ) self._vehicle.send_mavlink(msg) def __str__(self): @@ -2623,7 +2611,6 @@ def set(self, name, value, retries=3, wait_ready=False): name = name.upper() # convert to single precision floating point number (the type used by low level mavlink messages) value = float(struct.unpack('f', struct.pack('f', value))[0]) - success = False remaining = retries while True: self._vehicle._master.param_set_send(name, value) @@ -2948,13 +2935,11 @@ def __setitem__(self, index, value): self._vehicle._wpts_dirty = True -from dronekit.mavlink import MAVConnection - - def default_still_waiting_callback(atts): print("Still waiting for data from vehicle: %s" % ','.join(atts), file=sys.stderr) + def connect(ip, _initialize=True, wait_ready=None, @@ -3019,6 +3004,8 @@ def connect(ip, :returns: A connected vehicle of the type defined in ``vehicle_class`` (a superclass of :py:class:`Vehicle`). """ + from dronekit.mavlink import MAVConnection + if not vehicle_class: vehicle_class = Vehicle diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index f19d1a5ae..a38bde1c5 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -5,15 +5,12 @@ import sys import os import platform -import re import copy -import dronekit from dronekit import APIException from dronekit.util import errprinter -from pymavlink import mavutil, mavwp +from pymavlink import mavutil from queue import Queue, Empty from threading import Thread -import types if platform.system() == 'Windows': from errno import WSAECONNRESET as ECONNABORTED @@ -58,23 +55,23 @@ def __init__(self, device, baud=None, input=True, broadcast=False, source_system self.port.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) self.broadcast = True mavutil.set_close_on_exec(self.port.fileno()) - self.port.setblocking(0) + self.port.setblocking(False) mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, input=input, use_native=use_native) def close(self): self.port.close() - def recv(self,n=None): + def recv(self, n=None): try: try: data, new_addr = self.port.recvfrom(65535) except socket.error as e: - if e.errno in [ errno.EAGAIN, errno.EWOULDBLOCK, errno.ECONNREFUSED ]: + if e.errno in [errno.EAGAIN, errno.EWOULDBLOCK, errno.ECONNREFUSED]: return "" if self.udp_server: self.addresses.add(new_addr) elif self.broadcast: - self.addresses = set([new_addr]) + self.addresses = {new_addr} return data except Exception as e: print(e) @@ -222,7 +219,7 @@ def mavlink_thread_in(): # Avoid # invalid MAVLink prefix '73' # invalid MAVLink prefix '13' - #errprinter('mav recv error:', e) + # errprinter('mav recv error:', e) msg = None except Exception as e: # Log any other unexpected exception diff --git a/dronekit/test/__init__.py b/dronekit/test/__init__.py index fa1442c74..04ad5353a 100644 --- a/dronekit/test/__init__.py +++ b/dronekit/test/__init__.py @@ -1,8 +1,7 @@ from __future__ import print_function import os -import sys from dronekit_sitl import SITL -from nose.tools import assert_equals, with_setup +from nose.tools import with_setup import time sitl = None @@ -13,21 +12,25 @@ if 'SITL_RATE' in os.environ: sitl_args += ['-r', str(os.environ['SITL_RATE'])] + def setup_sitl(): global sitl sitl = SITL() sitl.download('copter', '3.3') sitl.launch(sitl_args, await_ready=True, restart=True) + def teardown_sitl(): sitl.stop() + def with_sitl(fn): @with_setup(setup_sitl, teardown_sitl) def test(*args, **kargs): return fn('tcp:127.0.0.1:5760', *args, **kargs) return test + def wait_for(condition, time_max): time_start = time.time() while not condition(): diff --git a/dronekit/test/sitl/__init__.py b/dronekit/test/sitl/__init__.py index 8b1378917..e69de29bb 100644 --- a/dronekit/test/sitl/__init__.py +++ b/dronekit/test/sitl/__init__.py @@ -1 +0,0 @@ - diff --git a/dronekit/test/sitl/test_110.py b/dronekit/test/sitl/test_110.py index 9ab32c6c0..43ed92135 100644 --- a/dronekit/test/sitl/test_110.py +++ b/dronekit/test/sitl/test_110.py @@ -1,6 +1,4 @@ import time -import sys -import os from dronekit import connect, VehicleMode from dronekit.test import with_sitl, wait_for from nose.tools import assert_equals @@ -17,7 +15,7 @@ def test_110(connpath): vehicle.parameters['FS_EKF_THRESH'] = 100 # Await armability. - wait_for(lambda : vehicle.is_armable, 60) + wait_for(lambda: vehicle.is_armable, 60) # Change the vehicle into STABILIZE mode vehicle.mode = VehicleMode("GUIDED") @@ -44,7 +42,7 @@ def armed_callback(vehicle, attribute, value): # Wait for ACK. time_max = 10 - wait_for(lambda : armed_callback.called, time_max) + wait_for(lambda: armed_callback.called, time_max) # Ensure the callback was called. assert armed_callback.called > 0, "Callback should have been called within %d seconds" % (time_max,) diff --git a/dronekit/test/sitl/test_115.py b/dronekit/test/sitl/test_115.py index 28f4a3f11..ae17d4a11 100644 --- a/dronekit/test/sitl/test_115.py +++ b/dronekit/test/sitl/test_115.py @@ -1,6 +1,4 @@ import time -import sys -import os from dronekit import connect, VehicleMode from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_12.py b/dronekit/test/sitl/test_12.py index d2c55a15c..c30e30b0b 100644 --- a/dronekit/test/sitl/test_12.py +++ b/dronekit/test/sitl/test_12.py @@ -1,7 +1,5 @@ import time -import sys -import os -from dronekit import connect, VehicleMode +from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_capability_and_version.py b/dronekit/test/sitl/test_capability_and_version.py index 1aa1cd531..cae0a0c45 100644 --- a/dronekit/test/sitl/test_capability_and_version.py +++ b/dronekit/test/sitl/test_capability_and_version.py @@ -1,6 +1,6 @@ import time -from dronekit import VehicleMode, connect +from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_false, assert_true @@ -15,11 +15,9 @@ def test_115(connpath): # flags before they are initialised. Vehicle attempts to refetch # until capabilities are non-zero, but we may need to wait: start_time = time.time() - nonzero_capabilities = True slept = False while v.capabilities.mission_float == 0: if time.time() > start_time + 30: - nonzero_capabilities = False break time.sleep(0.1) slept = True diff --git a/dronekit/test/sitl/test_channels.py b/dronekit/test/sitl/test_channels.py index f3f02b1fa..a23d536a2 100644 --- a/dronekit/test/sitl/test_channels.py +++ b/dronekit/test/sitl/test_channels.py @@ -1,8 +1,7 @@ -from pymavlink import mavutil import time -from dronekit import connect, VehicleMode, LocationGlobal +from dronekit import connect from dronekit.test import with_sitl -from nose.tools import assert_equals, assert_not_equals +from nose.tools import assert_equals def assert_readback(vehicle, values): @@ -63,7 +62,7 @@ def test_timeout(connpath): vehicle.channels.overrides['1'] = None assert_readback(vehicle, {'1': 1500, '2': 1500}) - #test + # test try: vehicle.channels['9'] assert False, "Can read over end of channels" diff --git a/dronekit/test/sitl/test_earlyattrs.py b/dronekit/test/sitl/test_earlyattrs.py index 91ec2c97b..3d48a1140 100644 --- a/dronekit/test/sitl/test_earlyattrs.py +++ b/dronekit/test/sitl/test_earlyattrs.py @@ -1,8 +1,4 @@ -import time -import sys -import os -import socket -from dronekit import connect, VehicleMode +from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals, assert_not_equals diff --git a/dronekit/test/sitl/test_locations.py b/dronekit/test/sitl/test_locations.py index 326b62b8b..be48cc7a6 100644 --- a/dronekit/test/sitl/test_locations.py +++ b/dronekit/test/sitl/test_locations.py @@ -1,5 +1,5 @@ import time -from dronekit import connect, VehicleMode, LocationGlobal +from dronekit import connect, VehicleMode from dronekit.test import with_sitl, wait_for from nose.tools import assert_equals, assert_not_equals @@ -20,17 +20,17 @@ def arm_and_takeoff(aTargetAltitude): """ # Don't let the user try to fly autopilot is booting - wait_for(lambda : vehicle.is_armable, 60) + wait_for(lambda: vehicle.is_armable, 60) assert_equals(vehicle.is_armable, True) # Copter should arm in GUIDED mode vehicle.mode = VehicleMode("GUIDED") - wait_for(lambda : vehicle.mode.name == 'GUIDED', 60) + wait_for(lambda: vehicle.mode.name == 'GUIDED', 60) assert_equals(vehicle.mode.name, 'GUIDED') # Arm copter. vehicle.armed = True - wait_for(lambda : vehicle.armed, 60) + wait_for(lambda: vehicle.armed, 60) assert_equals(vehicle.armed, True) # Take off to target altitude @@ -80,7 +80,7 @@ def callback(*args): assert_not_equals(args[2].alt, 0) ret['success'] = True - wait_for(lambda : ret['success'], 30) + wait_for(lambda: ret['success'], 30) assert ret['success'], 'Expected location object to emit notifications.' diff --git a/dronekit/test/sitl/test_mavlink.py b/dronekit/test/sitl/test_mavlink.py index 6ddf2d442..006240981 100644 --- a/dronekit/test/sitl/test_mavlink.py +++ b/dronekit/test/sitl/test_mavlink.py @@ -1,9 +1,7 @@ import time -import math from dronekit import connect from dronekit.mavlink import MAVConnection from dronekit.test import with_sitl -from nose.tools import assert_not_equals, assert_equals @with_sitl diff --git a/dronekit/test/sitl/test_mode_settings.py b/dronekit/test/sitl/test_mode_settings.py index 95392c36e..7c777f7ac 100644 --- a/dronekit/test/sitl/test_mode_settings.py +++ b/dronekit/test/sitl/test_mode_settings.py @@ -1,5 +1,3 @@ -import time -import math from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_modeavailable.py b/dronekit/test/sitl/test_modeavailable.py index 2796f7ad3..f95298f69 100644 --- a/dronekit/test/sitl/test_modeavailable.py +++ b/dronekit/test/sitl/test_modeavailable.py @@ -2,22 +2,19 @@ Simple test to trigger a bug in Vehicle class: issue #610 fixed in PR #611 """ -import time -import sys -import os -from dronekit import connect, VehicleMode +from dronekit import connect from dronekit.test import with_sitl -from nose.tools import assert_equals + @with_sitl def test_timeout(connpath): v = connect(connpath) - + # Set the vehicle and autopilot type to 'unsupported' types that MissionPlanner uses as of 17.Apr.2016 v._vehicle_type = 6 v._autopilot_type = 8 # The above types trigger 'TypeError: argument of type 'NoneType' is not iterable' which is addressed in issue #610 - is_available = v._is_mode_available(0) + v._is_mode_available(0) v.close() diff --git a/dronekit/test/sitl/test_parameters.py b/dronekit/test/sitl/test_parameters.py index cb7d2f4bb..bdfc5c3b8 100644 --- a/dronekit/test/sitl/test_parameters.py +++ b/dronekit/test/sitl/test_parameters.py @@ -1,7 +1,5 @@ import time -import sys -import os -from dronekit import connect, VehicleMode +from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals, assert_not_equals diff --git a/dronekit/test/sitl/test_simpledemo.py b/dronekit/test/sitl/test_simpledemo.py index 0f8319d12..d79dda11b 100644 --- a/dronekit/test/sitl/test_simpledemo.py +++ b/dronekit/test/sitl/test_simpledemo.py @@ -3,9 +3,6 @@ Feel free to copy and modify at your leisure. """ -import time -import sys -import os from dronekit import connect, VehicleMode from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_state.py b/dronekit/test/sitl/test_state.py index 850f9da58..b53889548 100644 --- a/dronekit/test/sitl/test_state.py +++ b/dronekit/test/sitl/test_state.py @@ -1,8 +1,4 @@ -import time -import sys -import os -import socket -from dronekit import connect, VehicleMode, SystemStatus +from dronekit import connect, SystemStatus from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_timeout.py b/dronekit/test/sitl/test_timeout.py index d36b78ca1..11b99baf1 100644 --- a/dronekit/test/sitl/test_timeout.py +++ b/dronekit/test/sitl/test_timeout.py @@ -1,8 +1,6 @@ import time -import sys -import os import socket -from dronekit import connect, VehicleMode +from dronekit import connect from dronekit.test import with_sitl from nose.tools import assert_equals diff --git a/dronekit/test/sitl/test_vehicleclass.py b/dronekit/test/sitl/test_vehicleclass.py index b7d386eed..ddc1054be 100644 --- a/dronekit/test/sitl/test_vehicleclass.py +++ b/dronekit/test/sitl/test_vehicleclass.py @@ -1,7 +1,6 @@ import time from dronekit import connect, Vehicle from dronekit.test import with_sitl -from nose.tools import assert_equals class DummyVehicle(Vehicle): diff --git a/dronekit/test/sitl/test_waypoints.py b/dronekit/test/sitl/test_waypoints.py index 288509b98..af594ca1b 100644 --- a/dronekit/test/sitl/test_waypoints.py +++ b/dronekit/test/sitl/test_waypoints.py @@ -1,6 +1,5 @@ import time -import math -from dronekit import connect, VehicleMode, LocationGlobal, Command +from dronekit import connect, LocationGlobal, Command from pymavlink import mavutil from dronekit.test import with_sitl from nose.tools import assert_not_equals, assert_equals diff --git a/dronekit/test/unit/__init__.py b/dronekit/test/unit/__init__.py index 8b1378917..e69de29bb 100644 --- a/dronekit/test/unit/__init__.py +++ b/dronekit/test/unit/__init__.py @@ -1 +0,0 @@ - diff --git a/dronekit/test/unit/test_api.py b/dronekit/test/unit/test_api.py index a7224e4a8..1ce8190dd 100644 --- a/dronekit/test/unit/test_api.py +++ b/dronekit/test/unit/test_api.py @@ -1,5 +1,3 @@ -import mock -from mock import MagicMock from dronekit import VehicleMode from nose.tools import assert_equals, assert_not_equals diff --git a/dronekit/util.py b/dronekit/util.py index 081ffd2be..f72166b67 100644 --- a/dronekit/util.py +++ b/dronekit/util.py @@ -5,6 +5,7 @@ def errprinter(*args): logger(*args) + def logger(*args): print(*args, file=sys.stderr) sys.stderr.flush() From cede8e090a7f444ba3ae43667298cdcdc3d42680 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Mon, 5 Nov 2018 19:01:40 +0100 Subject: [PATCH 58/99] Avoid pinning requirements to specific version (#872) --- requirements.txt | 4 ++-- setup.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements.txt b/requirements.txt index 7b67b3550..18f64c791 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ pymavlink>=2.2.20 monotonic>=1.3 future>=0.15.2 -nose==1.3.7 -mock==2.0.0 +nose>=1.3.7 +mock>=2.0.0 dronekit-sitl==3.2.0 sphinx-3dr-theme>=0.4.3 diff --git a/setup.py b/setup.py index 8b4805b32..a31072480 100644 --- a/setup.py +++ b/setup.py @@ -12,8 +12,8 @@ author='3D Robotics', install_requires=[ 'pymavlink>=2.2.20', - 'monotonic==1.2', - 'future==0.15.2' + 'monotonic>=1.2', + 'future>=0.15.2' ], author_email='tim@3drobotics.com, kevinh@geeksville.com', classifiers=[ From 8f97dd99a5db8d430c87dd9939d7db67437fee32 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 4 Nov 2018 09:50:33 +0100 Subject: [PATCH 59/99] Logging: use builting logging module, not print() Deprecate status_printer and log STATUSTEXT messages on a separate logger with the correct severity. Improved exception logging with stack traces in the log where necessary. --- dronekit/__init__.py | 86 ++++++++++++++++++++++++++------------------ dronekit/mavlink.py | 44 +++++++++++++---------- 2 files changed, 76 insertions(+), 54 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 17dbf2090..3b5bf80f5 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -25,6 +25,8 @@ It is also possible to work with vehicle "missions" using the :py:attr:`Vehicle.commands` attribute, and run them in AUTO mode. +All the logging is handled through the builtin Python `logging` module. + A number of other useful classes and methods are listed below. ---- @@ -33,15 +35,13 @@ from __future__ import print_function import collections import copy +import logging import math import struct -import re -import sys import time import monotonic from past.builtins import basestring -from dronekit.util import errprinter from pymavlink import mavutil, mavwp from pymavlink.dialects.v10 import ardupilotmega @@ -531,6 +531,8 @@ def __ne__(self, other): class HasObservers(object): def __init__(self): + self._logger = logging.getLogger(__name__) + # A mapping from attr_name to a list of observers self._attribute_listeners = {} self._attribute_cache = {} @@ -639,18 +641,14 @@ def notify_attribute_listeners(self, attr_name, value, cache=False): for fn in self._attribute_listeners.get(attr_name, []): try: fn(self, attr_name, value) - except Exception as e: - errprinter('>>> Exception in attribute handler for %s' % - attr_name) - errprinter('>>> ' + str(e)) + except Exception: + self._logger.exception('Exception in attribute handler for %s' % attr_name, exc_info=True) for fn in self._attribute_listeners.get('*', []): try: fn(self, attr_name, value) - except Exception as e: - errprinter('>>> Exception in attribute handler for %s' % - attr_name) - errprinter('>>> ' + str(e)) + except Exception: + self._logger.exception('Exception in attribute handler for %s' % attr_name, exc_info=True) def on_attribute(self, name): """ @@ -987,6 +985,15 @@ class Vehicle(HasObservers): It is also possible to work with vehicle "missions" using the :py:attr:`commands` attribute, and run them in AUTO mode. + STATUSTEXT log messages from the autopilot are handled through a separate logger. + It is possible to configure the log level, the formatting, etc. by accessing the logger, e.g.: + + .. code-block:: python + + import logging + autopilot_logger = logging.getLogger('autopilot') + autopilot_logger.setLevel(logging.DEBUG) + The guide contains more detailed information on the different ways you can use the ``Vehicle`` class: @@ -1008,6 +1015,20 @@ class Vehicle(HasObservers): def __init__(self, handler): super(Vehicle, self).__init__() + self._logger = logging.getLogger(__name__) # Logger for DroneKit + self._autopilot_logger = logging.getLogger('autopilot') # Logger for the autopilot messages + # MAVLink-to-logging-module log severity mappings + self._mavlink_statustext_severity = { + 0: logging.CRITICAL, + 1: logging.CRITICAL, + 2: logging.CRITICAL, + 3: logging.ERROR, + 4: logging.WARNING, + 5: logging.INFO, + 6: logging.INFO, + 7: logging.DEBUG + } + self._handler = handler self._master = handler.master @@ -1034,6 +1055,14 @@ def listener(_, msg): self._vy = None self._vz = None + @self.on_message('STATUSTEXT') + def statustext_listener(self, name, m): + # Log the STATUSTEXT on the autopilot logger, with the correct severity + self._autopilot_logger.log( + msg=m.text.strip(), + level=self._mavlink_statustext_severity[m.severity] + ) + @self.on_message('GLOBAL_POSITION_INT') def listener(self, name, m): (self._vx, self._vy, self._vz) = (m.vx / 100.0, m.vy / 100.0, m.vz / 100.0) @@ -1340,8 +1369,7 @@ def listener(_): self._heartbeat_error) elif monotonic.monotonic() - self._heartbeat_lastreceived > self._heartbeat_warning: if self._heartbeat_timeout is False: - errprinter('>>> Link timeout, no heartbeat in last %s seconds' % - self._heartbeat_warning) + self._logger.warning('Link timeout, no heartbeat in last %s seconds' % self._heartbeat_warning) self._heartbeat_timeout = True @self.on_message(['HEARTBEAT']) @@ -1352,7 +1380,7 @@ def listener(self, name, msg): self._heartbeat_system = msg.get_srcSystem() self._heartbeat_lastreceived = monotonic.monotonic() if self._heartbeat_timeout: - errprinter('>>> ...link restored.') + self._logger.info('...link restored.') self._heartbeat_timeout = False self._last_heartbeat = None @@ -1499,18 +1527,14 @@ def notify_message_listeners(self, name, msg): for fn in self._message_listeners.get(name, []): try: fn(self, name, msg) - except Exception as e: - errprinter('>>> Exception in message handler for %s' % - msg.get_type()) - errprinter('>>> ' + str(e)) + except Exception: + self._logger.exception('Exception in message handler for %s' % msg.get_type(), exc_info=True) for fn in self._message_listeners.get('*', []): try: fn(self, name, msg) - except Exception as e: - errprinter('>>> Exception in message handler for %s' % - msg.get_type()) - errprinter('>>> ' + str(e)) + except Exception: + self._logger.exception('Exception in message handler for %s' % msg.get_type(), exc_info=True) def close(self): return self._handler.close() @@ -2572,6 +2596,7 @@ class Parameters(collections.MutableMapping, HasObservers): def __init__(self, vehicle): super(Parameters, self).__init__() + self._logger = logging.getLogger(__name__) self._vehicle = vehicle def __getitem__(self, name): @@ -2624,7 +2649,7 @@ def set(self, name, value, retries=3, wait_ready=False): time.sleep(0.1) if retries > 0: - errprinter("timeout setting parameter %s to %f" % (name, value)) + self._logger.error("timeout setting parameter %s to %f" % (name, value)) return False def wait_ready(self, **kwargs): @@ -2936,8 +2961,7 @@ def __setitem__(self, index, value): def default_still_waiting_callback(atts): - print("Still waiting for data from vehicle: %s" % ','.join(atts), - file=sys.stderr) + logging.getLogger(__name__).debug("Still waiting for data from vehicle: %s" % ','.join(atts)) def connect(ip, @@ -2946,7 +2970,7 @@ def connect(ip, timeout=30, still_waiting_callback=default_still_waiting_callback, still_waiting_interval=1, - status_printer=errprinter, + status_printer=None, vehicle_class=None, rate=4, baud=115200, @@ -2978,9 +3002,7 @@ def connect(ip, For more information see :py:func:`Vehicle.wait_ready `. - :param status_printer: Method of signature ``def status_printer(txt)`` that prints - STATUS_TEXT messages from the Vehicle and other diagnostic information. - By default the status information is printed to the command prompt in which the script is running. + :param status_printer: deprecated and unused (STATUSTEXT messages are directed to their own logger) :param Vehicle vehicle_class: The class that will be instantiated by the ``connect()`` method. 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). @@ -3012,12 +3034,6 @@ def connect(ip, handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native) vehicle = vehicle_class(handler) - if status_printer: - - @vehicle.on_message('STATUSTEXT') - def listener(self, name, m): - status_printer(re.sub(r'(^|\n)', '>>> ', m.text.rstrip())) - if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index a38bde1c5..514f7f7a1 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -1,4 +1,6 @@ from __future__ import print_function + +import logging import time import socket import errno @@ -7,7 +9,6 @@ import platform import copy from dronekit import APIException -from dronekit.util import errprinter from pymavlink import mavutil from queue import Queue, Empty from threading import Thread @@ -25,22 +26,24 @@ class MAVWriter(object): """ def __init__(self, queue): + self._logger = logging.getLogger(__name__) self.queue = queue def write(self, pkt): self.queue.put(pkt) def read(self): - errprinter('writer should not have had a read request') + self._logger.critical('writer should not have had a read request') os._exit(43) class mavudpin_multi(mavutil.mavfile): '''a UDP mavlink socket''' def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, use_native=mavutil.default_native): + self._logger = logging.getLogger(__name__) a = device.split(':') if len(a) != 2: - print("UDP ports must be specified as host:port") + self._logger.critical("UDP ports must be specified as host:port") sys.exit(1) self.port = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.udp_server = input @@ -73,8 +76,8 @@ def recv(self, n=None): elif self.broadcast: self.addresses = {new_addr} return data - except Exception as e: - print(e) + except Exception: + self._logger.exception("Exception while reading data", exc_info=True) def write(self, buf): try: @@ -90,8 +93,8 @@ def write(self, buf): self.port.sendto(buf, self.destination_addr) except socket.error: pass - except Exception as e: - print(e) + except Exception: + self._logger.exception("Exception while writing data", exc_info=True) def recv_msg(self): '''message receive routine for UDP link''' @@ -119,6 +122,8 @@ def stop_threads(self): self.mavlink_thread_out = None def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_native=False): + self._logger = logging.getLogger(__name__) + if ip.startswith("udpin:"): self.master = mavudpin_multi(ip[6:], input=True, baud=baud, source_system=source_system) else: @@ -176,10 +181,10 @@ def mavlink_thread_out(): raise APIException('Connection aborting during read') raise except Exception as e: - errprinter('>>> mav send error:', e) + self._logger.exception('mav send error: %s' % str(e)) break except APIException as e: - errprinter('>>> ' + str(e)) + self._logger.exception("Exception in MAVLink write loop", exc_info=True) self._alive = False self.master.close() self._death_error = e @@ -219,11 +224,11 @@ def mavlink_thread_in(): # Avoid # invalid MAVLink prefix '73' # invalid MAVLink prefix '13' - # errprinter('mav recv error:', e) + self._logger.debug('mav recv error: %s' % str(e)) msg = None - except Exception as e: + except Exception: # Log any other unexpected exception - errprinter('>>> Exception while receiving message: ', e) + self._logger.exception('Exception while receiving message: ', exc_info=True) msg = None if not msg: break @@ -232,13 +237,14 @@ def mavlink_thread_in(): 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)) + except Exception: + self._logger.exception( + 'Exception in message handler for %s' % msg.get_type(), + exc_info=True + ) except APIException as e: - errprinter('>>> ' + str(e)) + self._logger.exception('Exception in MAVLink input loop') self._alive = False self.master.close() self._death_error = e @@ -316,7 +322,7 @@ def callback(_, msg): assert len(msg.get_msgbuf()) > 0 target.out_queue.put(msg.get_msgbuf()) except: - errprinter('>>> Could not pack this object on receive: %s' % type(msg)) + self._logger.exception('Could not pack this object on receive: %s' % type(msg), exc_info=True) # target -> self -> vehicle @target.forward_message @@ -330,6 +336,6 @@ def callback(_, msg): assert len(msg.get_msgbuf()) > 0 self.out_queue.put(msg.get_msgbuf()) except: - errprinter('>>> Could not pack this object on forward: %s' % type(msg)) + self._logger.exception('Could not pack this object on forward: %s' % type(msg), exc_info=True) return target From f786a6323191ab1fe0cf252111262287ff511adb Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 10 Nov 2018 11:21:54 +0100 Subject: [PATCH 60/99] Backwards compatibility for status_printer Add test for status_printer support --- dronekit/__init__.py | 13 ++++++++-- dronekit/test/sitl/test_errprinter.py | 34 +++++++++++++++++++++++++++ dronekit/util.py | 14 +++++++++++ 3 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 dronekit/test/sitl/test_errprinter.py diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 3b5bf80f5..6c207297b 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -32,7 +32,6 @@ ---- """ -from __future__ import print_function import collections import copy import logging @@ -46,6 +45,8 @@ from pymavlink import mavutil, mavwp from pymavlink.dialects.v10 import ardupilotmega +from dronekit.util import ErrprinterHandler + class APIException(Exception): """ @@ -3002,7 +3003,9 @@ def connect(ip, For more information see :py:func:`Vehicle.wait_ready `. - :param status_printer: deprecated and unused (STATUSTEXT messages are directed to their own logger) + :param status_printer: (deprecated) method of signature ``def status_printer(txt)`` that prints + STATUS_TEXT messages from the Vehicle and other diagnostic information. + By default the status information is handled by the ``autopilot`` logger. :param Vehicle vehicle_class: The class that will be instantiated by the ``connect()`` method. 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). @@ -3022,6 +3025,9 @@ def connect(ip, It is *good practice* to assign a unique id for every system on the MAVLink network. It is possible to configure the autopilot to only respond to guided-mode commands from a specified GCS ID. + The ``status_printer`` argument is deprecated. To redirect the logging from the library and from the + autopilot, configure the ``dronekit`` and ``autopilot`` loggers using the Python ``logging`` module. + :returns: A connected vehicle of the type defined in ``vehicle_class`` (a superclass of :py:class:`Vehicle`). """ @@ -3034,6 +3040,9 @@ def connect(ip, handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native) vehicle = vehicle_class(handler) + if status_printer: + vehicle._autopilot_logger.addHandler(ErrprinterHandler(status_printer)) + if _initialize: vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout) diff --git a/dronekit/test/sitl/test_errprinter.py b/dronekit/test/sitl/test_errprinter.py new file mode 100644 index 000000000..ce14c0af2 --- /dev/null +++ b/dronekit/test/sitl/test_errprinter.py @@ -0,0 +1,34 @@ +import logging +import time + +from nose.tools import assert_true + +from dronekit import connect +from dronekit.test import with_sitl + + +@with_sitl +def test_115(connpath): + """Provide a custom status_printer function to the Vehicle and check that + the autopilot messages are correctly logged. + """ + + logging_check = {'ok': False} + + def errprinter_fn(msg): + if isinstance(msg, str) and "APM:Copter" in msg: + logging_check['ok'] = True + + vehicle = connect(connpath, wait_ready=False, status_printer=errprinter_fn) + + i = 5 + while not logging_check['ok'] and i > 0: + time.sleep(1) + i -= 1 + + assert_true(logging_check['ok']) + vehicle.close() + + # Cleanup the logger + autopilotLogger = logging.getLogger('autopilot') + autopilotLogger.removeHandler(autopilotLogger.handlers[0]) diff --git a/dronekit/util.py b/dronekit/util.py index f72166b67..4b7bd43a6 100644 --- a/dronekit/util.py +++ b/dronekit/util.py @@ -1,4 +1,6 @@ from __future__ import print_function + +import logging import sys @@ -9,3 +11,15 @@ def errprinter(*args): def logger(*args): print(*args, file=sys.stderr) sys.stderr.flush() + + +class ErrprinterHandler(logging.Handler): + """Logging handler to support the deprecated `errprinter` argument to connect()""" + + def __init__(self, errprinter): + logging.Handler.__init__(self) + self.errprinter = errprinter + + def emit(self, record): + msg = self.format(record) + self.errprinter(msg) From c89175ac941d29f7e0f0b5d42f97f96ec268fd6d Mon Sep 17 00:00:00 2001 From: pietrodn Date: Wed, 14 Nov 2018 18:44:44 +0100 Subject: [PATCH 61/99] param_request_read_send wants bytes, not str --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 6c207297b..99e5c5c94 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1310,7 +1310,7 @@ def listener(_): c = 0 for i, v in enumerate(self._params_set): if v is None: - self._master.mav.param_request_read_send(0, 0, '', i) + self._master.mav.param_request_read_send(0, 0, b'', i) c += 1 if c > 50: break From 28d4fd336f1987f8db318239137f78b7b5e9ce4d Mon Sep 17 00:00:00 2001 From: Hamish Willee Date: Thu, 15 Nov 2018 17:37:58 +1100 Subject: [PATCH 62/99] Explain using native SITL with dk-sitl --- docs/develop/sitl_setup.rst | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/docs/develop/sitl_setup.rst b/docs/develop/sitl_setup.rst index d9131a284..8da0c3871 100644 --- a/docs/develop/sitl_setup.rst +++ b/docs/develop/sitl_setup.rst @@ -29,7 +29,8 @@ the `project on Github `_. .. note:: - DroneKit-SITL is still relatively experimental and there are only a few pre-built vehicles. + DroneKit-SITL is still relatively experimental and there are only a few pre-built vehicles + (some of which are quite old and/or unstable). The binaries are built and tested on Windows 10, Ubuntu Linux, and Mac OS X "El Capitan". Binaries are only available for x86 architectures. ARM builds @@ -74,7 +75,13 @@ There are a number of other useful arguments: dronekit-sitl --reset #Delete all downloaded vehicle binaries. dronekit-sitl ./path [args...] #Start SITL instance at target file location. - + +.. note:: + + You can also use *dronekit-sitl* to start a SITL executable that you have built locally from source. + To do this, put the file path of the target executable in the `SITL_BINARY` environment variable, + or as the first argument when calling the tool. + .. _connecting_dronekit_sitl: From 8a44656737915a851e149f8592e12d5393a29ee5 Mon Sep 17 00:00:00 2001 From: Yuuya Fujiwara Date: Thu, 15 Nov 2018 16:39:08 +0900 Subject: [PATCH 63/99] mission import / export example : Displayed message changed, file names get from argument. --- examples/mission_import_export/mission_import_export.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/mission_import_export/mission_import_export.py b/examples/mission_import_export/mission_import_export.py index d0c77e04c..fc36e7f91 100644 --- a/examples/mission_import_export/mission_import_export.py +++ b/examples/mission_import_export/mission_import_export.py @@ -89,7 +89,7 @@ def upload_mission(aFileName): #Read mission from file missionlist = readmission(aFileName) - print("\nUpload mission from a file: %s" % import_mission_filename) + print("\nUpload mission from a file: %s" % aFileName) #Clear existing mission from vehicle print(' Clear mission') cmds = vehicle.commands @@ -120,7 +120,7 @@ def save_mission(aFileName): Save a mission in the Waypoint file format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format). """ - print("\nSave mission from Vehicle to file: %s" % export_mission_filename) + print("\nSave mission from Vehicle to file: %s" % aFileName) #Download mission from vehicle missionlist = download_mission() #Add file-format information From a80a9bdbcfd7b80ba60a9fa860478cb748a4de16 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 18 Nov 2018 16:52:19 +0100 Subject: [PATCH 64/99] AppVeyor: test on multiple Python versions --- appveyor.yml | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 63fab30ca..b1996b573 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,10 +1,20 @@ environment: SITL_SPEEDUP: 10 SITL_RATE: 200 + PYTHONUNBUFFERED: 1 + + matrix: + - PYTHON: "C:\\Python27" + PYTHON_VERSION: "2.7" + - PYTHON: "C:\\Python37" + PYTHON_VERSION: "3.7" cache: - "c:\\Users\\appveyor\\.pip-wheelhouse" +init: + - cmd: "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" + install: - ps: | New-Item -ItemType Directory -Force -Path c:\Users\appveyor\pip\ @@ -15,17 +25,14 @@ install: [wheel] wheel-dir = c:/Users/appveyor/.pip-wheelhouse '@ | out-file -Encoding ascii -FilePath c:\Users\appveyor\pip\pip.ini - - - cmd: 'SET PATH=%PYTHON%;c:\\Python27\\Scripts;%PATH%' - - cmd: 'SET PYTHONUNBUFFERED=1' - - cmd: 'python -m pip install pip wheel -U' - cmd: 'pip install . -UI' - cmd: 'pip install -r requirements.txt -UI' -build_script: +build: off + +test_script: - cmd: 'nosetests -svx dronekit.test.unit' - cmd: 'nosetests -svx dronekit.test.sitl' clone_depth: 10 -test: 'off' From e412e95d24169c606edcd87fa1dc309af305eb0e Mon Sep 17 00:00:00 2001 From: Huibean Date: Thu, 20 Dec 2018 20:42:30 +0800 Subject: [PATCH 65/99] incase None > int in python3 --- dronekit/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 99e5c5c94..42d1a3991 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1775,7 +1775,7 @@ def is_armable(self): # check that mode is not INITIALSING # check that we have a GPS fix # check that EKF pre-arm is complete - return self.mode != 'INITIALISING' and self.gps_0.fix_type > 1 and self._ekf_predposhorizabs + return self.mode != 'INITIALISING' and (self.gps_0.fix_type is not None and self.gps_0.fix_type > 1) and self._ekf_predposhorizabs @property def system_status(self): From b448fd9c5a3aae58d5cc7c240288e2c226796d7d Mon Sep 17 00:00:00 2001 From: Huibean Date: Tue, 25 Dec 2018 13:00:51 +0800 Subject: [PATCH 66/99] add logging basic config --- dronekit/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 42d1a3991..01536e10c 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -532,6 +532,7 @@ def __ne__(self, other): class HasObservers(object): def __init__(self): + logging.basicConfig() self._logger = logging.getLogger(__name__) # A mapping from attr_name to a list of observers From e07328b2ec41c1864eb0e437ed97f74063956427 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 18 Nov 2018 16:19:16 +0100 Subject: [PATCH 67/99] Add commands and tests for sensor calibration --- dronekit/__init__.py | 119 ++++++++++++++++++ dronekit/test/sitl/__init__.py | 47 +++++++ dronekit/test/sitl/test_sensor_calibration.py | 95 ++++++++++++++ 3 files changed, 261 insertions(+) create mode 100644 dronekit/test/sitl/test_sensor_calibration.py diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 01536e10c..74a8a6302 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2398,6 +2398,125 @@ def reboot(self): self.send_mavlink(reboot_msg) + def calibrate_gyro(self): + """Request gyroscope calibration.""" + + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 1, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 0, # param 2, 1: magnetometer calibration + 0, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 0, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + self.send_mavlink(calibration_command) + + def calibrate_magnetometer(self): + """Request magnetometer calibration.""" + + # APM requires the MAV_CMD_DO_START_MAG_CAL command, only present in the APM MAVLink dialect + if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA: + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_DO_START_MAG_CAL, # command + 0, # confirmation + 0, # param 1, uint8_t bitmask of magnetometers (0 means all). + 1, # param 2, Automatically retry on failure (0=no retry, 1=retry). + 1, # param 3, Save without user input (0=require input, 1=autosave). + 0, # param 4, Delay (seconds). + 1, # param 5, Autoreboot (0=user reboot, 1=autoreboot). + 0, # param 6, Empty. + 0, # param 7, Empty. + ) + else: + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 1, # param 2, 1: magnetometer calibration + 0, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 0, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + + self._logger.critical(calibration_command) + self.send_mavlink(calibration_command) + + def calibrate_accelerometer(self): + """Request accelerometer calibration.""" + + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 0, # param 2, 1: magnetometer calibration + 0, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 1, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + self.send_mavlink(calibration_command) + + def calibrate_accelerometer_simple(self): + """Request simple accelerometer calibration.""" + + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 0, # param 2, 1: magnetometer calibration + 0, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 4, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + self.send_mavlink(calibration_command) + + def calibrate_board_level(self): + """Request board level calibration.""" + + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 0, # param 2, 1: magnetometer calibration + 0, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 2, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + self.send_mavlink(calibration_command) + + def calibrate_barometer(self): + """Request barometer calibration.""" + + calibration_command = self.message_factory.command_long_encode( + 0, 0, # target_system, target_component + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command + 0, # confirmation + 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration + 0, # param 2, 1: magnetometer calibration + 1, # param 3, 1: ground pressure calibration + 0, # param 4, 1: radio RC calibration, 2: RC trim calibration + 0, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 0, # param 6, 2: airspeed calibration + 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration + ) + self.send_mavlink(calibration_command) + class Gimbal(object): """ diff --git a/dronekit/test/sitl/__init__.py b/dronekit/test/sitl/__init__.py index e69de29bb..51b3be828 100644 --- a/dronekit/test/sitl/__init__.py +++ b/dronekit/test/sitl/__init__.py @@ -0,0 +1,47 @@ +import time +from contextlib import contextmanager +from nose.tools import assert_equal +from pymavlink import mavutil + + +@contextmanager +def assert_command_ack( + vehicle, + command_type, + ack_result=mavutil.mavlink.MAV_RESULT_ACCEPTED, + timeout=10 +): + """Context manager to assert that: + + 1) exactly one COMMAND_ACK is received from a Vehicle; + 2) for a specific command type; + 3) with the given result; + 4) within a timeout (in seconds). + + For example: + + .. code-block:: python + + with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): + vehicle.calibrate_gyro() + + """ + + acks = [] + + def on_ack(self, name, message): + if message.command == command_type: + acks.append(message) + + vehicle.add_message_listener('COMMAND_ACK', on_ack) + + yield + + start_time = time.time() + while not acks and time.time() - start_time < timeout: + time.sleep(0.1) + vehicle.remove_message_listener('COMMAND_ACK', on_ack) + + assert_equal(1, len(acks)) # one and only one ACK + assert_equal(command_type, acks[0].command) # for the correct command + assert_equal(ack_result, acks[0].result) # the result must be successful diff --git a/dronekit/test/sitl/test_sensor_calibration.py b/dronekit/test/sitl/test_sensor_calibration.py new file mode 100644 index 000000000..76d51f2e9 --- /dev/null +++ b/dronekit/test/sitl/test_sensor_calibration.py @@ -0,0 +1,95 @@ +from pymavlink import mavutil + +from dronekit import connect +from dronekit.test import with_sitl + +from dronekit.test.sitl import assert_command_ack + + +@with_sitl +def test_gyro_calibration(connpath): + """Request gyroscope calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): + vehicle.calibrate_gyro() + + vehicle.close() + + +@with_sitl +def test_magnetometer_calibration(connpath): + """Request magnetometer calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + with assert_command_ack( + vehicle, + mavutil.mavlink.MAV_CMD_DO_START_MAG_CAL, + timeout=30, + ack_result=mavutil.mavlink.MAV_RESULT_UNSUPPORTED, # TODO: change when APM is upgraded + ): + vehicle.calibrate_magnetometer() + + vehicle.close() + + +@with_sitl +def test_simple_accelerometer_calibration(connpath): + """Request simple accelerometer calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + with assert_command_ack( + vehicle, + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, + timeout=30, + ack_result=mavutil.mavlink.MAV_RESULT_FAILED, # TODO: change when APM is upgraded + ): + vehicle.calibrate_accelerometer_simple() + + vehicle.close() + + +@with_sitl +def test_accelerometer_calibration(connpath): + """Request accelerometer calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + # The calibration is expected to fail because in the SITL we don't tilt the Vehicle. + # We just check that the command isn't denied or unsupported. + with assert_command_ack( + vehicle, + mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, + timeout=30, + ack_result=mavutil.mavlink.MAV_RESULT_FAILED, + ): + vehicle.calibrate_accelerometer() + + vehicle.close() + + +@with_sitl +def test_board_level_calibration(connpath): + """Request board level calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): + vehicle.calibrate_board_level() + + vehicle.close() + + +@with_sitl +def test_barometer_calibration(connpath): + """Request barometer calibration, and check for the COMMAND_ACK.""" + + vehicle = connect(connpath, wait_ready=True) + + with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): + vehicle.calibrate_barometer() + + vehicle.close() From 70822a52c39e440e3870b8c93c3291b0519c2139 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Mon, 19 Nov 2018 08:34:34 +0100 Subject: [PATCH 68/99] Corrections --- dronekit/__init__.py | 38 ++++++------------- dronekit/test/sitl/test_sensor_calibration.py | 6 +-- 2 files changed, 15 insertions(+), 29 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 74a8a6302..57c732685 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2402,7 +2402,7 @@ def calibrate_gyro(self): """Request gyroscope calibration.""" calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command 0, # confirmation 1, # param 1, 1: gyro calibration, 3: gyro temperature calibration @@ -2418,10 +2418,10 @@ def calibrate_gyro(self): def calibrate_magnetometer(self): """Request magnetometer calibration.""" - # APM requires the MAV_CMD_DO_START_MAG_CAL command, only present in the APM MAVLink dialect + # ArduPilot requires the MAV_CMD_DO_START_MAG_CAL command, only present in the ardupilotmega.xml definition if self._autopilot_type == mavutil.mavlink.MAV_AUTOPILOT_ARDUPILOTMEGA: calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_DO_START_MAG_CAL, # command 0, # confirmation 0, # param 1, uint8_t bitmask of magnetometers (0 means all). @@ -2434,7 +2434,7 @@ def calibrate_magnetometer(self): ) else: calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command 0, # confirmation 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration @@ -2449,35 +2449,21 @@ def calibrate_magnetometer(self): self._logger.critical(calibration_command) self.send_mavlink(calibration_command) - def calibrate_accelerometer(self): - """Request accelerometer calibration.""" - - calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component - mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command - 0, # confirmation - 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration - 0, # param 2, 1: magnetometer calibration - 0, # param 3, 1: ground pressure calibration - 0, # param 4, 1: radio RC calibration, 2: RC trim calibration - 1, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration - 0, # param 6, 2: airspeed calibration - 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration - ) - self.send_mavlink(calibration_command) + def calibrate_accelerometer(self, simple=False): + """Request accelerometer calibration. - def calibrate_accelerometer_simple(self): - """Request simple accelerometer calibration.""" + :param simple: if True, perform simple accelerometer calibration + """ calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command 0, # confirmation 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration 0, # param 2, 1: magnetometer calibration 0, # param 3, 1: ground pressure calibration 0, # param 4, 1: radio RC calibration, 2: RC trim calibration - 4, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration + 4 if simple else 1, # param 5, 1: accelerometer calibration, 2: board level calibration, 3: accelerometer temperature calibration, 4: simple accelerometer calibration 0, # param 6, 2: airspeed calibration 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration ) @@ -2487,7 +2473,7 @@ def calibrate_board_level(self): """Request board level calibration.""" calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command 0, # confirmation 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration @@ -2504,7 +2490,7 @@ def calibrate_barometer(self): """Request barometer calibration.""" calibration_command = self.message_factory.command_long_encode( - 0, 0, # target_system, target_component + self._handler.target_system, 0, # target_system, target_component mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, # command 0, # confirmation 0, # param 1, 1: gyro calibration, 3: gyro temperature calibration diff --git a/dronekit/test/sitl/test_sensor_calibration.py b/dronekit/test/sitl/test_sensor_calibration.py index 76d51f2e9..de1a9c90e 100644 --- a/dronekit/test/sitl/test_sensor_calibration.py +++ b/dronekit/test/sitl/test_sensor_calibration.py @@ -45,9 +45,9 @@ def test_simple_accelerometer_calibration(connpath): vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30, - ack_result=mavutil.mavlink.MAV_RESULT_FAILED, # TODO: change when APM is upgraded + ack_result=mavutil.mavlink.MAV_RESULT_FAILED, ): - vehicle.calibrate_accelerometer_simple() + vehicle.calibrate_accelerometer(simple=True) vehicle.close() @@ -66,7 +66,7 @@ def test_accelerometer_calibration(connpath): timeout=30, ack_result=mavutil.mavlink.MAV_RESULT_FAILED, ): - vehicle.calibrate_accelerometer() + vehicle.calibrate_accelerometer(simple=False) vehicle.close() From 1ee6e4853cb2aba6f155b4ba0553520b5bd09a44 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 24 Nov 2018 11:59:03 +0100 Subject: [PATCH 69/99] Rename calibrate_board_level -> calibrate_vehicle level; don't auto-reboot on mag calibration. --- dronekit/__init__.py | 6 +++--- dronekit/test/sitl/test_sensor_calibration.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 57c732685..92f70cfbe 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2428,7 +2428,7 @@ def calibrate_magnetometer(self): 1, # param 2, Automatically retry on failure (0=no retry, 1=retry). 1, # param 3, Save without user input (0=require input, 1=autosave). 0, # param 4, Delay (seconds). - 1, # param 5, Autoreboot (0=user reboot, 1=autoreboot). + 0, # param 5, Autoreboot (0=user reboot, 1=autoreboot). 0, # param 6, Empty. 0, # param 7, Empty. ) @@ -2469,8 +2469,8 @@ def calibrate_accelerometer(self, simple=False): ) self.send_mavlink(calibration_command) - def calibrate_board_level(self): - """Request board level calibration.""" + def calibrate_vehicle_level(self): + """Request vehicle level (accelerometer trim) calibration.""" calibration_command = self.message_factory.command_long_encode( self._handler.target_system, 0, # target_system, target_component diff --git a/dronekit/test/sitl/test_sensor_calibration.py b/dronekit/test/sitl/test_sensor_calibration.py index de1a9c90e..a9bcf13fb 100644 --- a/dronekit/test/sitl/test_sensor_calibration.py +++ b/dronekit/test/sitl/test_sensor_calibration.py @@ -78,7 +78,7 @@ def test_board_level_calibration(connpath): vehicle = connect(connpath, wait_ready=True) with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): - vehicle.calibrate_board_level() + vehicle.calibrate_vehicle_level() vehicle.close() From e4314dedb81a84d5b2b1df13ffefa856c97b5aa7 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sat, 24 Nov 2018 12:27:48 +0100 Subject: [PATCH 70/99] Remove extraneous logging line --- dronekit/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 92f70cfbe..e381baff2 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2446,7 +2446,6 @@ def calibrate_magnetometer(self): 0, # param 7, 1: ESC calibration, 3: barometer temperature calibration ) - self._logger.critical(calibration_command) self.send_mavlink(calibration_command) def calibrate_accelerometer(self, simple=False): From c3cfa7fab0b78273d9af88bc4f8c6a9f80001b8d Mon Sep 17 00:00:00 2001 From: pietrodn Date: Mon, 31 Dec 2018 09:21:51 +0100 Subject: [PATCH 71/99] Rename "calibrate_*" to "send_calibrate_*" (non-blocking methods) --- dronekit/__init__.py | 10 +++++----- dronekit/test/sitl/test_sensor_calibration.py | 12 ++++++------ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index e381baff2..99b91f42d 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2398,7 +2398,7 @@ def reboot(self): self.send_mavlink(reboot_msg) - def calibrate_gyro(self): + def send_calibrate_gyro(self): """Request gyroscope calibration.""" calibration_command = self.message_factory.command_long_encode( @@ -2415,7 +2415,7 @@ def calibrate_gyro(self): ) self.send_mavlink(calibration_command) - def calibrate_magnetometer(self): + def send_calibrate_magnetometer(self): """Request magnetometer calibration.""" # ArduPilot requires the MAV_CMD_DO_START_MAG_CAL command, only present in the ardupilotmega.xml definition @@ -2448,7 +2448,7 @@ def calibrate_magnetometer(self): self.send_mavlink(calibration_command) - def calibrate_accelerometer(self, simple=False): + def send_calibrate_accelerometer(self, simple=False): """Request accelerometer calibration. :param simple: if True, perform simple accelerometer calibration @@ -2468,7 +2468,7 @@ def calibrate_accelerometer(self, simple=False): ) self.send_mavlink(calibration_command) - def calibrate_vehicle_level(self): + def send_calibrate_vehicle_level(self): """Request vehicle level (accelerometer trim) calibration.""" calibration_command = self.message_factory.command_long_encode( @@ -2485,7 +2485,7 @@ def calibrate_vehicle_level(self): ) self.send_mavlink(calibration_command) - def calibrate_barometer(self): + def send_calibrate_barometer(self): """Request barometer calibration.""" calibration_command = self.message_factory.command_long_encode( diff --git a/dronekit/test/sitl/test_sensor_calibration.py b/dronekit/test/sitl/test_sensor_calibration.py index a9bcf13fb..d80aa2343 100644 --- a/dronekit/test/sitl/test_sensor_calibration.py +++ b/dronekit/test/sitl/test_sensor_calibration.py @@ -13,7 +13,7 @@ def test_gyro_calibration(connpath): vehicle = connect(connpath, wait_ready=True) with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): - vehicle.calibrate_gyro() + vehicle.send_calibrate_gyro() vehicle.close() @@ -30,7 +30,7 @@ def test_magnetometer_calibration(connpath): timeout=30, ack_result=mavutil.mavlink.MAV_RESULT_UNSUPPORTED, # TODO: change when APM is upgraded ): - vehicle.calibrate_magnetometer() + vehicle.send_calibrate_magnetometer() vehicle.close() @@ -47,7 +47,7 @@ def test_simple_accelerometer_calibration(connpath): timeout=30, ack_result=mavutil.mavlink.MAV_RESULT_FAILED, ): - vehicle.calibrate_accelerometer(simple=True) + vehicle.send_calibrate_accelerometer(simple=True) vehicle.close() @@ -66,7 +66,7 @@ def test_accelerometer_calibration(connpath): timeout=30, ack_result=mavutil.mavlink.MAV_RESULT_FAILED, ): - vehicle.calibrate_accelerometer(simple=False) + vehicle.send_calibrate_accelerometer(simple=False) vehicle.close() @@ -78,7 +78,7 @@ def test_board_level_calibration(connpath): vehicle = connect(connpath, wait_ready=True) with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): - vehicle.calibrate_vehicle_level() + vehicle.send_calibrate_vehicle_level() vehicle.close() @@ -90,6 +90,6 @@ def test_barometer_calibration(connpath): vehicle = connect(connpath, wait_ready=True) with assert_command_ack(vehicle, mavutil.mavlink.MAV_CMD_PREFLIGHT_CALIBRATION, timeout=30): - vehicle.calibrate_barometer() + vehicle.send_calibrate_barometer() vehicle.close() From e51de971f67d4f154aefb671d8233f095bbed36f Mon Sep 17 00:00:00 2001 From: huibean Date: Wed, 9 Jan 2019 12:49:10 +0800 Subject: [PATCH 72/99] add MOUNT_ORIENTATION support --- dronekit/__init__.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 99b91f42d..b9bfbe015 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -2542,6 +2542,13 @@ def listener(vehicle, name, m): self._yaw = m.pointing_c / 100.0 vehicle.notify_attribute_listeners('gimbal', vehicle.gimbal) + @vehicle.on_message('MOUNT_ORIENTATION') + def listener(vehicle, name, m): + self._pitch = m.pitch + self._roll = m.roll + self._yaw = m.yaw + vehicle.notify_attribute_listeners('gimbal', vehicle.gimbal) + @property def pitch(self): """ From ed132cce3588b5a9b0fa93e50f255a284fb8a0f7 Mon Sep 17 00:00:00 2001 From: Yuuya Fujiwara Date: Fri, 25 Jan 2019 08:44:09 +0900 Subject: [PATCH 73/99] revise URL in comment. --- examples/create_attribute/my_vehicle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/create_attribute/my_vehicle.py b/examples/create_attribute/my_vehicle.py index 01f12cea1..9b129f937 100644 --- a/examples/create_attribute/my_vehicle.py +++ b/examples/create_attribute/my_vehicle.py @@ -17,7 +17,7 @@ class RawIMU(object): The RAW IMU readings for the usual 9DOF sensor setup. This contains the true raw values without any scaling to allow data capture and system debugging. - The message definition is here: https://pixhawk.ethz.ch/mavlink/#RAW_IMU + The message definition is here: https://mavlink.io/en/messages/common.html#RAW_IMU :param time_boot_us: Timestamp (microseconds since system boot). #Note, not milliseconds as per spec :param xacc: X acceleration (mg) From 22ae381f188167d45157b574993bdaaf80778658 Mon Sep 17 00:00:00 2001 From: Afsoon Afzal Date: Thu, 31 Jan 2019 15:42:23 -0500 Subject: [PATCH 74/99] Set a timeout for uploading missions --- dronekit/__init__.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b9bfbe015..0de761bb4 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -3009,7 +3009,7 @@ def add(self, cmd): self._vehicle._wploader.add(cmd, comment='Added by DroneKit') self._vehicle._wpts_dirty = True - def upload(self): + def upload(self, timeout=None): """ Call ``upload()`` after :py:func:`adding ` or :py:func:`clearing ` mission commands. @@ -3018,10 +3018,13 @@ def upload(self): """ if self._vehicle._wpts_dirty: self._vehicle._master.waypoint_clear_all_send() + start_time = time.time() 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()) while False in self._vehicle._wp_uploaded: + if timeout and time.time() - start_time > timeout: + raise TimeoutError time.sleep(0.1) self._vehicle._wp_uploaded = None self._vehicle._wpts_dirty = False From 0eb7715bd9392c36e8ab6901a4546ae20c424918 Mon Sep 17 00:00:00 2001 From: Afsoon Afzal Date: Thu, 31 Jan 2019 15:43:54 -0500 Subject: [PATCH 75/99] updating the comment --- dronekit/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 0de761bb4..37c66de0d 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -3015,6 +3015,8 @@ def upload(self, timeout=None): After the return from ``upload()`` any writes are guaranteed to have completed (or thrown an exception) and future reads will see their effects. + + :param int timeout: The timeout for uploading the mission. No timeout if not provided or set to None. """ if self._vehicle._wpts_dirty: self._vehicle._master.waypoint_clear_all_send() From 4ea3b9f274ac3cf99b6ca91f6a8ae62a8ea01f7b Mon Sep 17 00:00:00 2001 From: Jaime Machuca Date: Fri, 8 Feb 2019 16:20:19 -0700 Subject: [PATCH 76/99] Add Source Component ID parameter to connect function to allow setting a different comp ID than 0. Default to 0 to make it backwards compatible. --- dronekit/__init__.py | 4 +++- dronekit/mavlink.py | 11 ++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 37c66de0d..b6ff96227 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -3094,6 +3094,7 @@ def connect(ip, baud=115200, heartbeat_timeout=30, source_system=255, + source_component=0, use_native=False): """ Returns a :py:class:`Vehicle` object connected to the address specified by string parameter ``ip``. @@ -3130,6 +3131,7 @@ def connect(ip, :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 source_component: The MAVLink Component ID fo the :py:class:`Vehicle` object returned by this method (by default 0). :param bool use_native: Use precompiled MAVLink parser. .. note:: @@ -3154,7 +3156,7 @@ def connect(ip, if not vehicle_class: vehicle_class = Vehicle - handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native) + handler = MAVConnection(ip, baud=baud, source_system=source_system, source_component=source_component, use_native=use_native) vehicle = vehicle_class(handler) if status_printer: diff --git a/dronekit/mavlink.py b/dronekit/mavlink.py index 514f7f7a1..d87f93ae5 100644 --- a/dronekit/mavlink.py +++ b/dronekit/mavlink.py @@ -39,7 +39,7 @@ def read(self): class mavudpin_multi(mavutil.mavfile): '''a UDP mavlink socket''' - def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, use_native=mavutil.default_native): + def __init__(self, device, baud=None, input=True, broadcast=False, source_system=255, source_component=0, use_native=mavutil.default_native): self._logger = logging.getLogger(__name__) a = device.split(':') if len(a) != 2: @@ -59,7 +59,7 @@ def __init__(self, device, baud=None, input=True, broadcast=False, source_system self.broadcast = True mavutil.set_close_on_exec(self.port.fileno()) self.port.setblocking(False) - mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, input=input, use_native=use_native) + mavutil.mavfile.__init__(self, self.port.fileno(), device, source_system=source_system, source_component=source_component, input=input, use_native=use_native) def close(self): self.port.close() @@ -121,13 +121,13 @@ 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, target_system=0, source_system=255, source_component=0, use_native=False): self._logger = logging.getLogger(__name__) if ip.startswith("udpin:"): - self.master = mavudpin_multi(ip[6:], input=True, baud=baud, source_system=source_system) + self.master = mavudpin_multi(ip[6:], input=True, baud=baud, source_system=source_system, source_component=source_component) else: - self.master = mavutil.mavlink_connection(ip, baud=baud, source_system=source_system) + self.master = mavutil.mavlink_connection(ip, baud=baud, source_system=source_system, source_component=source_component) # TODO get rid of "master" object as exposed, # keep it private, expose something smaller for dronekit @@ -135,6 +135,7 @@ def __init__(self, ip, baud=115200, target_system=0, source_system=255, use_nati self.master.mav = mavutil.mavlink.MAVLink( MAVWriter(self.out_queue), srcSystem=self.master.source_system, + srcComponent=self.master.source_component, use_native=use_native) # Monkey-patch MAVLink object for fix_targets. From 4a70a08a40600e41af2caeba2f9a9cfe698a9c87 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 30 Dec 2018 12:56:23 +0100 Subject: [PATCH 77/99] setup.py, requirements.txt, README.md improvements - future is not a direct dependency of dronekit: remove it - README.md: Python 3-compatible "Hello World" - PyPI badge: link to the package page on PyPI - setup.py: add classifier for Python 3 - setup.py: install monotonic only for Python<3.3 - setup.py: automatically discover packages with setuptools --- README.md | 6 +++--- requirements.txt | 1 - setup.py | 56 +++++++++++++++++++++++------------------------- 3 files changed, 30 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 057eef556..014fc2dbb 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![dronekit_python_logo](https://cloud.githubusercontent.com/assets/5368500/10805537/90dd4b14-7e22-11e5-9592-5925348a7df9.png) -![PyPi published version](https://img.shields.io/pypi/v/dronekit.svg) +[![PyPi published version](https://img.shields.io/pypi/v/dronekit.svg)](https://pypi.org/project/dronekit/) [![Windows Build status](https://img.shields.io/appveyor/ci/3drobotics/dronekit-python/master.svg?label=windows)](https://ci.appveyor.com/project/3drobotics/dronekit-python/branch/master) [![OS X Build Status](https://img.shields.io/travis/dronekit/dronekit-python/master.svg?label=os%20x)](https://travis-ci.org/dronekit/dronekit-python) [![Linux Build Status](https://img.shields.io/circleci/project/dronekit/dronekit-python/master.svg?label=linux)](https://circleci.com/gh/dronekit/dronekit-python) @@ -25,12 +25,12 @@ The [Quick Start](http://python.dronekit.io/guide/quick_start.html) guide explai A basic script looks like this: ```python -from dronekit import connect, VehicleMode +from dronekit import connect # Connect to UDP endpoint. vehicle = connect('127.0.0.1:14550', wait_ready=True) # Use returned Vehicle object to query device state - e.g. to get the mode: -print " Mode: %s" % vehicle.mode.name +print("Mode: %s" % vehicle.mode.name) ``` Once you've got DroneKit set up, the [guide](http://python.dronekit.io/guide/index.html) explains how to perform operations like taking off and flying the vehicle. You can also try out most of the tasks by running the [examples](http://python.dronekit.io/examples/index.html). diff --git a/requirements.txt b/requirements.txt index 18f64c791..9e70c79bb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,5 @@ pymavlink>=2.2.20 monotonic>=1.3 -future>=0.15.2 nose>=1.3.7 mock>=2.0.0 dronekit-sitl==3.2.0 diff --git a/setup.py b/setup.py index a31072480..235d2cfb2 100644 --- a/setup.py +++ b/setup.py @@ -1,32 +1,30 @@ -from setuptools import setup, Extension -import platform +import setuptools version = '2.9.1' -setup(name='dronekit', - zip_safe=True, - version=version, - description='Developer Tools for Drones.', - long_description='Python API for communication and control of drones over MAVLink.', - url='https://github.com/dronekit/dronekit-python', - author='3D Robotics', - install_requires=[ - 'pymavlink>=2.2.20', - 'monotonic>=1.2', - 'future>=0.15.2' - ], - author_email='tim@3drobotics.com, kevinh@geeksville.com', - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Science/Research', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2.7', - 'Topic :: Scientific/Engineering', - ], - license='apache', - packages=[ - 'dronekit', 'dronekit.test' - ], - ext_modules=[]) +setuptools.setup( + name='dronekit', + zip_safe=True, + version=version, + description='Developer Tools for Drones.', + long_description='Python API for communication and control of drones over MAVLink.', + url='https://github.com/dronekit/dronekit-python', + author='3D Robotics', + install_requires=[ + 'pymavlink>=2.2.20', + 'monotonic>=1.3 ; python_version<"3.3"', + ], + author_email='tim@3drobotics.com, kevinh@geeksville.com', + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Intended Audience :: Science/Research', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3', + 'Topic :: Scientific/Engineering', + ], + license='apache', + packages=setuptools.find_packages() +) From fa5530c172a6cb3ef9b63b8ea539f7947a8aef29 Mon Sep 17 00:00:00 2001 From: pietrodn Date: Sun, 30 Dec 2018 13:34:27 +0100 Subject: [PATCH 78/99] monotonic is actually needed --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 235d2cfb2..cc24953f8 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ author='3D Robotics', install_requires=[ 'pymavlink>=2.2.20', - 'monotonic>=1.3 ; python_version<"3.3"', + 'monotonic>=1.3', ], author_email='tim@3drobotics.com, kevinh@geeksville.com', classifiers=[ From f85f9cb64a1cf34c02c6d1a16fbf1cee62d9f368 Mon Sep 17 00:00:00 2001 From: Dr Nic Williams Date: Wed, 13 Feb 2019 12:01:32 +1000 Subject: [PATCH 79/99] fix URL to mavproxy documentation New MAVProxy docs are at http://ardupilot.github.io/MAVProxy/html/getting_started/starting.html Signed-off-by: Dr Nic Williams --- docs/guide/connecting_vehicle.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/connecting_vehicle.rst b/docs/guide/connecting_vehicle.rst index 135e29d38..62faa7df1 100644 --- a/docs/guide/connecting_vehicle.rst +++ b/docs/guide/connecting_vehicle.rst @@ -80,7 +80,7 @@ The table below shows *connection strings* you can use for some of the more comm .. tip:: The strings above are the same as are used when connecting the MAVProxy GCS. For other options see the - `MAVProxy documentation `_. + `MAVProxy documentation `_. .. note:: From 10d79fa22ddaed701521d27df19794586b188aa7 Mon Sep 17 00:00:00 2001 From: deb0ch Date: Mon, 8 Jan 2018 10:29:22 +0100 Subject: [PATCH 80/99] improve set_attitude_target example --- .../set_attitude_target.py | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) mode change 100644 => 100755 examples/set_attitude_target/set_attitude_target.py diff --git a/examples/set_attitude_target/set_attitude_target.py b/examples/set_attitude_target/set_attitude_target.py old mode 100644 new mode 100755 index c6ebd0ed3..c3f676f0e --- a/examples/set_attitude_target/set_attitude_target.py +++ b/examples/set_attitude_target/set_attitude_target.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- """ @@ -85,20 +84,18 @@ def arm_and_takeoff_nogps(aTargetAltitude): set_attitude(thrust = thrust) time.sleep(0.2) - -def set_attitude(roll_angle = 0.0, pitch_angle = 0.0, yaw_rate = 0.0, thrust = 0.5, duration = 0): - """ - Note that from AC3.3 the message should be re-sent every second (after about 3 seconds - with no message the velocity will drop back to zero). In AC3.2.1 and earlier the specified - velocity persists until it is canceled. The code below should work on either version - (sending the message multiple times does not cause problems). - """ - +def send_attitude_target(roll_angle = 0.0, pitch_angle = 0.0, + yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False, + thrust = 0.5): """ - The roll and pitch rate cannot be controllbed with rate in radian in AC3.4.4 or earlier, - so you must use quaternion to control the pitch and roll for those vehicles. + use_yaw_rate: the yaw can be controlled using yaw_angle OR yaw_rate. + When one is used, the other is ignored by Ardupilot. + thrust: 0 <= thrust <= 1, as a fraction of maximum vertical thrust. + Note that as of Copter 3.5, thrust = 0.5 triggers a special case in + the code for maintaining current altitude. """ - + if not use_yaw_rate and yaw_angle is None: + yaw_angle = vehicle.attitude.yaw # Thrust > 0.5: Ascend # Thrust == 0.5: Hold the altitude # Thrust < 0.5: Descend @@ -106,19 +103,38 @@ def set_attitude(roll_angle = 0.0, pitch_angle = 0.0, yaw_rate = 0.0, thrust = 0 0, # time_boot_ms 1, # Target system 1, # Target component - 0b00000000, # Type mask: bit 1 is LSB - to_quaternion(roll_angle, pitch_angle), # Quaternion + 0b00000000 if use_yaw_rate else 0b00000100, + to_quaternion(roll_angle, pitch_angle, yaw_angle), # Quaternion 0, # Body roll rate in radian 0, # Body pitch rate in radian - math.radians(yaw_rate), # Body yaw rate in radian + math.radians(yaw_rate), # Body yaw rate in radian/second thrust # Thrust ) vehicle.send_mavlink(msg) +def set_attitude(roll_angle = 0.0, pitch_angle = 0.0, + yaw_angle = None, yaw_rate = 0.0, use_yaw_rate = False, + thrust = 0.5, duration = 0): + """ + Note that from AC3.3 the message should be re-sent more often than every + second, as an ATTITUDE_TARGET order has a timeout of 1s. + In AC3.2.1 and earlier the specified attitude persists until it is canceled. + The code below should work on either version. + Sending the message multiple times is the recommended way. + """ + send_attitude_target(roll_angle, pitch_angle, + yaw_angle, yaw_rate, False, + thrust) start = time.time() while time.time() - start < duration: - vehicle.send_mavlink(msg) + send_attitude_target(roll_angle, pitch_angle, + yaw_angle, yaw_rate, False, + thrust) time.sleep(0.1) + # Reset attitude, or it will persist for 1s more due to the timeout + send_attitude_target(0, 0, + 0, 0, True, + thrust) def to_quaternion(roll = 0.0, pitch = 0.0, yaw = 0.0): """ From 119689e29cb7cc6d98796a19f0e8548db63c0e97 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 14 Mar 2019 16:28:00 +1100 Subject: [PATCH 81/99] examples: set_attitude_target: avoid use of None in to_quaternion --- examples/set_attitude_target/set_attitude_target.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/set_attitude_target/set_attitude_target.py b/examples/set_attitude_target/set_attitude_target.py index c3f676f0e..d182637b1 100755 --- a/examples/set_attitude_target/set_attitude_target.py +++ b/examples/set_attitude_target/set_attitude_target.py @@ -94,7 +94,8 @@ def send_attitude_target(roll_angle = 0.0, pitch_angle = 0.0, Note that as of Copter 3.5, thrust = 0.5 triggers a special case in the code for maintaining current altitude. """ - if not use_yaw_rate and yaw_angle is None: + if yaw_angle is None: + # this value may be unused by the vehicle, depending on use_yaw_rate yaw_angle = vehicle.attitude.yaw # Thrust > 0.5: Ascend # Thrust == 0.5: Hold the altitude From 3cd8bdebd53ef90ec1062e561b4dae91b92b9886 Mon Sep 17 00:00:00 2001 From: mohamed ali rashad Date: Tue, 5 Mar 2019 15:11:07 +0200 Subject: [PATCH 82/99] Adding README to PyPi & minimizing imports Adding the README as a long description in PyPi and minimizing the setuptools import to only setup and find_packages --- setup.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/setup.py b/setup.py index cc24953f8..5b3e90e78 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,17 @@ import setuptools +import os version = '2.9.1' +with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: + LongDescription = f.read() + setuptools.setup( name='dronekit', zip_safe=True, version=version, description='Developer Tools for Drones.', - long_description='Python API for communication and control of drones over MAVLink.', + long_description=LongDescription, url='https://github.com/dronekit/dronekit-python', author='3D Robotics', install_requires=[ From 8d4495ad134fd3ee88c0e4f9f9bc42577d76ed58 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Thu, 14 Mar 2019 16:58:50 +1100 Subject: [PATCH 83/99] Release 2.9.2 notes and version bump --- CHANGELOG.md | 26 ++++++++++++++++++++++++++ setup.py | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 21331ab2e..ca542f26a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,31 @@ # Changelog + +## Version 2.9.2 (2019-03-18) + +### Improvements +* CI integration improvements +* Python3 compatability +* use logging module +* log statustexts +* documentation improvements +* convenience functions added: wait_for, wait_for_armable, arm, disarm, wait_for_mode, wait_for_alt, wait_simple_takeoff +* play_tune method added +* reboot method added +* send_calibrate_gyro, send_calibrate_magnetometer, send_calibrate_magnetometer, send_calibrate_vehicle_level, send_calibrate_barometer all added +* update gimbal orientation from MOUNT_ORIENTATION +* add a still-waiting callback for connect() to provide debug on where the connection is up to +* several new tests added (including, play_tune, reboot and set_attitude_target) + +### Cleanup +* flake8 compliance improvements +* test includes pruned +* examples cleaned up + +### Bug Fixes +* ignore GCS heartbeats for the purposes of link up +* many! + ## Version 2.9.1 (2017-04-21) ### Improvements diff --git a/setup.py b/setup.py index 5b3e90e78..7bcb37b50 100644 --- a/setup.py +++ b/setup.py @@ -1,7 +1,7 @@ import setuptools import os -version = '2.9.1' +version = '2.9.2' with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f: LongDescription = f.read() From 91c147fa61f521f5fff5d0cee06d07ed93614af8 Mon Sep 17 00:00:00 2001 From: Peter Barker Date: Tue, 19 Mar 2019 09:54:36 +1100 Subject: [PATCH 84/99] setup.py: add long_description_content_type --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 7bcb37b50..49d7477e2 100644 --- a/setup.py +++ b/setup.py @@ -11,6 +11,7 @@ zip_safe=True, version=version, description='Developer Tools for Drones.', + long_description_content_type="text/markdown", long_description=LongDescription, url='https://github.com/dronekit/dronekit-python', author='3D Robotics', From f54efe20df0f5ac015b4ec3ef88584d859726a7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Dvo=C5=99=C3=A1k?= Date: Tue, 25 Jun 2019 22:37:27 +0200 Subject: [PATCH 85/99] change of mavlink message name. --- dronekit/__init__.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index b6ff96227..76b1dadd3 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1142,12 +1142,12 @@ def listener(vehicle, name, m): # All keys are strings. self._channels = Channels(self, 8) - @self.on_message('RC_CHANNELS_RAW') + @self.on_message('RC_CHANNELS') def listener(self, name, m): def set_rc(chnum, v): '''Private utility for handling rc channel messages''' # use port to allow ch nums greater than 8 - self._channels._update_channel(str(m.port * 8 + chnum), v) + self._channels._update_channel(str(0 * 8 + chnum), v) set_rc(1, m.chan1_raw) set_rc(2, m.chan2_raw) @@ -1157,6 +1157,16 @@ def set_rc(chnum, v): set_rc(6, m.chan6_raw) set_rc(7, m.chan7_raw) set_rc(8, m.chan8_raw) + set_rc(9, m.chan9_raw) + set_rc(10, m.chan10_raw) + set_rc(11, m.chan11_raw) + set_rc(12, m.chan12_raw) + set_rc(13, m.chan13_raw) + set_rc(14, m.chan14_raw) + set_rc(15, m.chan15_raw) + set_rc(16, m.chan16_raw) + set_rc(17, m.chan17_raw) + set_rc(18, m.chan18_raw) self.notify_attribute_listeners('channels', self.channels) self._voltage = None @@ -2544,7 +2554,7 @@ def listener(vehicle, name, m): @vehicle.on_message('MOUNT_ORIENTATION') def listener(vehicle, name, m): - self._pitch = m.pitch + self._pitch = m.pitch self._roll = m.roll self._yaw = m.yaw vehicle.notify_attribute_listeners('gimbal', vehicle.gimbal) From bf5004aaa06e3456d442adcccd69a5a2a7d7d5ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Dvo=C5=99=C3=A1k?= Date: Wed, 26 Jun 2019 07:28:08 +0200 Subject: [PATCH 86/99] support for booth messages - RC_CHANNELS ad RC_CHANNELS_RAW., clean code. --- dronekit/__init__.py | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 76b1dadd3..200f15272 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1142,31 +1142,18 @@ def listener(vehicle, name, m): # All keys are strings. self._channels = Channels(self, 8) + @self.on_message('RC_CHANNELS_RAW') @self.on_message('RC_CHANNELS') def listener(self, name, m): def set_rc(chnum, v): '''Private utility for handling rc channel messages''' # use port to allow ch nums greater than 8 - self._channels._update_channel(str(0 * 8 + chnum), v) - - set_rc(1, m.chan1_raw) - set_rc(2, m.chan2_raw) - set_rc(3, m.chan3_raw) - set_rc(4, m.chan4_raw) - set_rc(5, m.chan5_raw) - set_rc(6, m.chan6_raw) - set_rc(7, m.chan7_raw) - set_rc(8, m.chan8_raw) - set_rc(9, m.chan9_raw) - set_rc(10, m.chan10_raw) - set_rc(11, m.chan11_raw) - set_rc(12, m.chan12_raw) - set_rc(13, m.chan13_raw) - set_rc(14, m.chan14_raw) - set_rc(15, m.chan15_raw) - set_rc(16, m.chan16_raw) - set_rc(17, m.chan17_raw) - set_rc(18, m.chan18_raw) + port = 0 if name == "RC_CHANNELS" else m.port + self._channels._update_channel(str(port * 8 + chnum), v) + + for i in range(1, (18 if name == "RC_CHANNELS" else 8)+1): + set_rc(i, getattr(m, "chan{}_raw".format(i))) + self.notify_attribute_listeners('channels', self.channels) self._voltage = None From cfb0a9d38e2ef13a5715faea0150f4d2f5b94de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Dvo=C5=99=C3=A1k?= Date: Wed, 26 Jun 2019 08:56:56 +0200 Subject: [PATCH 87/99] message names in list --- dronekit/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 200f15272..4f3613906 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1142,8 +1142,7 @@ def listener(vehicle, name, m): # All keys are strings. self._channels = Channels(self, 8) - @self.on_message('RC_CHANNELS_RAW') - @self.on_message('RC_CHANNELS') + @self.on_message(['RC_CHANNELS_RAW', 'RC_CHANNELS']) def listener(self, name, m): def set_rc(chnum, v): '''Private utility for handling rc channel messages''' From 86d1af472709f2a204cbbb9ec143f5f2a29d43c4 Mon Sep 17 00:00:00 2001 From: Hamish Willee Date: Fri, 5 Jul 2019 10:33:08 +1000 Subject: [PATCH 88/99] Fix up links to point to readthedos --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 014fc2dbb..616ac31f7 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ The API is primarily intended for use in onboard companion computers (to support ## Getting Started -The [Quick Start](http://python.dronekit.io/guide/quick_start.html) guide explains how to set up DroneKit on each of the supported platforms (Linux, Mac OSX, Windows) and how to write a script to connect to a vehicle (real or simulated). +The [Quick Start](https://dronekit-python.readthedocs.io/en/latest/guide/quick_start.html) guide explains how to set up DroneKit on each of the supported platforms (Linux, Mac OSX, Windows) and how to write a script to connect to a vehicle (real or simulated). A basic script looks like this: @@ -33,19 +33,19 @@ vehicle = connect('127.0.0.1:14550', wait_ready=True) print("Mode: %s" % vehicle.mode.name) ``` -Once you've got DroneKit set up, the [guide](http://python.dronekit.io/guide/index.html) explains how to perform operations like taking off and flying the vehicle. You can also try out most of the tasks by running the [examples](http://python.dronekit.io/examples/index.html). +Once you've got DroneKit set up, the [guide](https://dronekit-python.readthedocs.io/en/latest/guide/index.html) explains how to perform operations like taking off and flying the vehicle. You can also try out most of the tasks by running the [examples](https://dronekit-python.readthedocs.io/en/latest/examples/index.html). ## Resources -The project documentation is available at [python.dronekit.io](http://python.dronekit.io/). This includes [guide](http://python.dronekit.io/guide/index.html), [example](http://python.dronekit.io/examples/index.html) and [API Reference](http://python.dronekit.io/automodule.html) material. +The project documentation is available at [https://readthedocs.org/projects/dronekit-python/](https://readthedocs.org/projects/dronekit-python/). This includes [guide](https://dronekit-python.readthedocs.io/en/latest/guide/index.html), [example](https://dronekit-python.readthedocs.io/en/latest/examples/index.html) and [API Reference](https://dronekit-python.readthedocs.io/en/latest/automodule.html) material. The example source code is hosted here on Github as sub-folders of [/dronekit-python/examples](https://github.com/dronekit/dronekit-python/tree/master/examples). The [DroneKit Forums](http://discuss.dronekit.io) are the best place to ask for technical support on how to use the library. You can also check out our [Gitter channel](https://gitter.im/dronekit/dronekit-python?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) though we prefer posts on the forums where possible. -* **Documentation:** [http://python.dronekit.io/](http://python.dronekit.io/) -* **Guides:** [http://python.dronekit.io/guide/index.html](http://python.dronekit.io/guide/index.html) -* **API Reference:** [http://python.dronekit.io/automodule.html](http://python.dronekit.io/automodule.html) +* **Documentation:** [https://dronekit-python.readthedocs.io/en/latest/about/index.html](https://dronekit-python.readthedocs.io/en/latest/about/index.html) +* **Guides:** [https://dronekit-python.readthedocs.io/en/latest/guide/index.html) +* **API Reference:** [https://dronekit-python.readthedocs.io/en/latest/automodule.html) * **Examples:** [/dronekit-python/examples](https://github.com/dronekit/dronekit-python/tree/master/examples) * **Forums:** [http://discuss.dronekit.io/](http://discuss.dronekit.io) * **Gitter:** [https://gitter.im/dronekit/dronekit-python](https://gitter.im/dronekit/dronekit-python?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) though we prefer posts on the forums where possible. @@ -57,7 +57,7 @@ We'd love your [feedback and suggestions](https://github.com/dronekit/dronekit-p If you've created some awesome software that uses this project, [let us know on the forums here](https://discuss.dronekit.io/t/notable-projects-using-dronekit/230)! -If you want to contribute, see our [Contributing](http://python.dronekit.io/contributing/index.html) guidelines, we welcome all types of contributions but mostly contributions that would help us shrink our [issues list](https://github.com/dronekit/dronekit-python/issues). +If you want to contribute, see our [Contributing](https://dronekit-python.readthedocs.io/en/latest/contributing/index.html) guidelines, we welcome all types of contributions but mostly contributions that would help us shrink our [issues list](https://github.com/dronekit/dronekit-python/issues). ## Licence From fe6c62313831c7d4847ae8009af3f6400aea8c5e Mon Sep 17 00:00:00 2001 From: Ross Higa Date: Tue, 12 Nov 2019 12:00:50 -1000 Subject: [PATCH 89/99] Fixed error in code comments The serial example code said it was for a UDP endpoint --- docs/guide/connecting_vehicle.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/connecting_vehicle.rst b/docs/guide/connecting_vehicle.rst index 62faa7df1..af2d68fc2 100644 --- a/docs/guide/connecting_vehicle.rst +++ b/docs/guide/connecting_vehicle.rst @@ -33,7 +33,7 @@ Connecting over a serial device will look something like this: from dronekit import connect - # Connect to the Vehicle (in this case a UDP endpoint) + # Connect to the Vehicle (in this case a serial endpoint) vehicle = connect('/dev/ttyAMA0', wait_ready=True, baud=57600) .. tip:: From bdb20fb028862dc268a8b870917c80c97d93545a Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Thu, 2 Jul 2020 19:28:56 +0200 Subject: [PATCH 90/99] docs: Python 3 is supported Using `sudo` is actually a bad idea --- docs/develop/installation.rst | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/develop/installation.rst b/docs/develop/installation.rst index 97b0229a8..f063bf069 100644 --- a/docs/develop/installation.rst +++ b/docs/develop/installation.rst @@ -5,7 +5,7 @@ Installing DroneKit =================== DroneKit-Python can be installed on a Linux, Mac OSX, or Windows computer that -has *Python 2.7* and can install Python packages from the Internet. +has Python 2.7 or Python 3 installed and can install Python packages from the Internet. It is installed from **pip** on all platforms: @@ -16,11 +16,13 @@ It is installed from **pip** on all platforms: **Installation notes:** -* Mac and Linux require you prefix the command with ``sudo``. +* Install `dronekit` with `pip` inside a virtualenv: .. code-block:: bash - sudo pip install dronekit + python3 -m venv .venv + . .venv/bin/activate + pip install dronekit * On Linux you may need to first install **pip** and **python-dev**: @@ -28,11 +30,11 @@ It is installed from **pip** on all platforms: sudo apt-get install python-pip python-dev - Alternatively, the *easy_install* tool provides another way to install pip: + Alternatively, you can use the `ensurepip` module to install or upgrade Pip on Python 3: .. code-block:: bash - sudo easy_install pip + python -m ensurepip --upgrade * :doc:`companion-computers` are likely to run on stripped down versions of Linux. Ensure you use a variant that supports Python 2.7 and can install Python packages from the Internet. @@ -43,4 +45,4 @@ It is installed from **pip** on all platforms: * `WinPython 2.7 64bit `_ (see `these instructions for installation and registration `_). This is the most tested version. * `ActiveState ActivePython 2.7 `_. -* Python 3 is not supported. +* Python 3 is fully supported. From 27b292b8eb32e465a3682e84bab3a56fb83bba0c Mon Sep 17 00:00:00 2001 From: Pietro De Nicolao Date: Fri, 3 Jul 2020 10:49:13 +0200 Subject: [PATCH 91/99] docs: ensurepip also works for Python 2.7 --- docs/develop/installation.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/develop/installation.rst b/docs/develop/installation.rst index f063bf069..bcfe09f64 100644 --- a/docs/develop/installation.rst +++ b/docs/develop/installation.rst @@ -30,7 +30,8 @@ It is installed from **pip** on all platforms: sudo apt-get install python-pip python-dev - Alternatively, you can use the `ensurepip` module to install or upgrade Pip on Python 3: + Alternatively, you can use the `ensurepip` module to install or upgrade Pip on your system: + .. code-block:: bash From 253eb45ca28519f2d9864bed90489bd1c821ec9d Mon Sep 17 00:00:00 2001 From: ogent Date: Mon, 15 Feb 2021 23:59:03 +0000 Subject: [PATCH 92/99] wind stats --- dronekit/__init__.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 4f3613906..0c5fc16e3 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -220,6 +220,25 @@ def __str__(self): return "GPSInfo:fix=%s,num_sat=%s" % (self.fix_type, self.satellites_visible) +class Wind(object): + """ + Wind information + + An object of this type is returned by :py:attr: `Vehicle.wind`. + + :param wind_direction: Wind direction in degrees + :param wind_speed: Wind speed in m/s + :param wind_speed_z: vertical wind speed in m/s + """ + def __init__(self, wind_direction, wind_speed, wind_speed_z): + self.wind_direction = wind_direction + self.wind_speed = wind_speed + self.wind_speed_z = wind_speed_z + + def __str__(self): + return "Wind: wind direction: {}, wind speed: {}, wind speed z: {}".format(self.wind_direction, self.wind_speed, self.wind_speed_z) + + class Battery(object): """ System battery information. @@ -1057,6 +1076,19 @@ def listener(_, msg): self._vy = None self._vz = None + + self._wind_direction = None + self._wind_speed = None + self._wind_speed_z = None + + @self.on_message('WIND') + def listener(self,name, m): + """ WIND {direction : -180.0, speed : 0.0, speed_z : 0.0} """ + self._wind_direction = m.direction + self._wind_speed = m.speed + self._wind_speed_z = m.speed_z + + @self.on_message('STATUSTEXT') def statustext_listener(self, name, m): # Log the STATUSTEXT on the autopilot logger, with the correct severity @@ -1678,6 +1710,13 @@ def listener(self, attr_name, value): """ return self._location + @property + def wind(self): + """ + Current wind status (:pu:class: `Wind`) + """ + return Wind(self._wind_direction, self._wind_speed, self._wind_speed_z) + @property def battery(self): """ From c7143e0ba94d414416fd36679fd3306ce31a7e69 Mon Sep 17 00:00:00 2001 From: ogent Date: Fri, 19 Feb 2021 00:38:56 +0000 Subject: [PATCH 93/99] wind property, return none if attributes are none --- dronekit/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index 0c5fc16e3..e4a45bd40 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1715,6 +1715,8 @@ def wind(self): """ Current wind status (:pu:class: `Wind`) """ + if self._wind_direction is None or self._wind_speed is None or self._wind_speed_z is None: + return None return Wind(self._wind_direction, self._wind_speed, self._wind_speed_z) @property From 1d89e82807ce543bae5e36426641b717e187c589 Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 16 Dec 2021 02:07:10 +0000 Subject: [PATCH 94/99] Correct import of MutableMapping for Python 3.10 --- dronekit/__init__.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index e4a45bd40..db5e1f3d4 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -32,7 +32,15 @@ ---- """ +import sys import collections + +# Python3.10 removed MutableMapping from collections: +if sys.version_info.major == 3 and sys.version_info.minor >= 10: + from collections.abc import MutableMapping +else: + from collections import MutableMapping + import copy import logging import math @@ -2723,7 +2731,7 @@ def __str__(self): return "Gimbal: pitch={0}, roll={1}, yaw={2}".format(self.pitch, self.roll, self.yaw) -class Parameters(collections.MutableMapping, HasObservers): +class Parameters(MutableMapping, HasObservers): """ This object is used to get and set the values of named parameters for a vehicle. See the following links for information about the supported parameters for each platform: `Copter Parameters `_, From b92a9b049fb9b66b9da93778871e050f05df57d3 Mon Sep 17 00:00:00 2001 From: "Samuel S. Hernandez" <54045450+SamuelSHernandez@users.noreply.github.com> Date: Wed, 15 Jun 2022 17:26:51 -0500 Subject: [PATCH 95/99] Update mission_basic.py outdated documentation links --- examples/mission_basic/mission_basic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/mission_basic/mission_basic.py b/examples/mission_basic/mission_basic.py index 8e394e4db..226d327dd 100644 --- a/examples/mission_basic/mission_basic.py +++ b/examples/mission_basic/mission_basic.py @@ -5,7 +5,7 @@ © Copyright 2015-2016, 3D Robotics. mission_basic.py: Example demonstrating basic mission operations including creating, clearing and monitoring missions. -Full documentation is provided at http://python.dronekit.io/examples/mission_basic.html +Full documentation is provided at https://dronekit-python.readthedocs.io/en/latest/examples/mission_basic.html """ from __future__ import print_function From c7e1b8ef534170db38289da46d6c2d89a3db2dd9 Mon Sep 17 00:00:00 2001 From: Ramon Roche Date: Wed, 7 Jun 2023 21:45:27 -0700 Subject: [PATCH 96/99] Maintainers Needed Hey @hamishwillee, your feedback would be appreciated. --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 616ac31f7..f024a0b6f 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,10 @@ DroneKit-Python helps you create powerful apps for UAVs. +# ⚠️ ATTENTION: MAINTAINERS NEEDED ⚠️ + +Hey it's true this project is not very active, but it could be with your help. We are looking for maintainers interested in keeping the project alive by keep up with CI and PRs. If you are interested in helping please apply by [creating an issue]([url](https://github.com/dronekit/dronekit-python/issues/new)) and listing the reasons why you would like to help, in return we will be granting committer access to folks who are truly interested in helping. + ## Overview From 3ee89b7d83ba1fe676f0b2980a7774b052c29c2f Mon Sep 17 00:00:00 2001 From: John Kesler Date: Fri, 14 Apr 2023 08:10:11 -0500 Subject: [PATCH 97/99] Make HEARTBEAT handler ignore non-vehicle HEARTBEATs --- dronekit/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dronekit/__init__.py b/dronekit/__init__.py index db5e1f3d4..bc05a7098 100644 --- a/dronekit/__init__.py +++ b/dronekit/__init__.py @@ -1249,7 +1249,7 @@ def listener(self, name, m): @self.on_message('HEARTBEAT') def listener(self, name, m): # ignore groundstations - if m.type == mavutil.mavlink.MAV_TYPE_GCS: + if m.type == mavutil.mavlink.MAV_TYPE_GCS or (not self._handler.master.probably_vehicle_heartbeat(m)): return self._armed = (m.base_mode & mavutil.mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0 self.notify_attribute_listeners('armed', self.armed, cache=True) @@ -1413,7 +1413,7 @@ def listener(_): @self.on_message(['HEARTBEAT']) def listener(self, name, msg): # ignore groundstations - if msg.type == mavutil.mavlink.MAV_TYPE_GCS: + if msg.type == mavutil.mavlink.MAV_TYPE_GCS or (not self._handler.master.probably_vehicle_heartbeat(msg)): return self._heartbeat_system = msg.get_srcSystem() self._heartbeat_lastreceived = monotonic.monotonic() From 53ca517bcb4ed1dd2dffad26528a25bf77f9c34b Mon Sep 17 00:00:00 2001 From: muramura Date: Mon, 20 May 2024 06:48:19 +0900 Subject: [PATCH 98/99] examples: Change the reference URL --- docs/examples/guided-set-speed-yaw-demo.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/examples/guided-set-speed-yaw-demo.rst b/docs/examples/guided-set-speed-yaw-demo.rst index 49cefdf23..22554157f 100644 --- a/docs/examples/guided-set-speed-yaw-demo.rst +++ b/docs/examples/guided-set-speed-yaw-demo.rst @@ -189,16 +189,16 @@ The functions for controlling vehicle movement are: DroneKit position controller method. It is called from :ref:`goto ` to fly a triangular path. * :ref:`goto_position_target_global_int() ` is a position controller that uses the - `SET_POSITION_TARGET_GLOBAL_INT `_ command. + `SET_POSITION_TARGET_GLOBAL_INT `_ command. * :ref:`goto_position_target_local_ned() ` - is a position controller that uses `SET_POSITION_TARGET_LOCAL_NED `_ + is a position controller that uses `SET_POSITION_TARGET_LOCAL_NED `_ command (taking values in NED frame, relative to the home position). This is used to fly a square path. The script is put to sleep for a certain time in order to allow the vehicle to reach the specified position. * :ref:`send_ned_velocity() ` is a velocity controller. - It uses `SET_POSITION_TARGET_LOCAL_NED `_ + It uses `SET_POSITION_TARGET_LOCAL_NED `_ to fly a square path using velocity vectors to define the speed in each direction. * :ref:`send_global_velocity() ` is a velocity controller. - It uses `SET_POSITION_TARGET_GLOBAL_INT `_ + It uses `SET_POSITION_TARGET_GLOBAL_INT `_ to fly a diamond-shaped path. The behaviour is essentially the same as for ``send_ned_velocity()`` because the velocity components in both commands are in the NED frame. * :ref:`goto ` is a convenience function for specifying a target location @@ -262,7 +262,7 @@ send_global_velocity() ---------------------- The function ``send_global_velocity()`` generates a -`SET_POSITION_TARGET_GLOBAL_INT `_ +`SET_POSITION_TARGET_GLOBAL_INT `_ MAVLink message which is used to directly specify the speed components of the vehicle in the NED frame. @@ -359,7 +359,7 @@ The ``type_mask`` enables the position parameters (the last three bits of of the .. note:: - The `MAVLink protocol documentation `_ + The `MAVLink protocol documentation `_ lists a number of possible frames of reference. Up until Copter 3.2.1 the actual frame used is always relative to the home location (as indicated by MAV_FRAME_LOCAL_NED). Starting from Copter 3.3 you can specify `other frames `_, From 1dda2a222580b376422ccbc689f5dda1b306b50c Mon Sep 17 00:00:00 2001 From: muramura Date: Mon, 20 May 2024 06:49:27 +0900 Subject: [PATCH 99/99] copter: Change the reference URL --- docs/guide/copter/guided_mode.rst | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/docs/guide/copter/guided_mode.rst b/docs/guide/copter/guided_mode.rst index b96ba3171..e7ec0def5 100644 --- a/docs/guide/copter/guided_mode.rst +++ b/docs/guide/copter/guided_mode.rst @@ -83,8 +83,8 @@ for all positional movement commands until it is set to another value. .. tip:: You can also set the position by sending the MAVLink commands - `SET_POSITION_TARGET_GLOBAL_INT `_ or - `SET_POSITION_TARGET_LOCAL_NED `_, specifying + `SET_POSITION_TARGET_GLOBAL_INT `_ or + `SET_POSITION_TARGET_LOCAL_NED `_, specifying a ``type_mask`` bitmask that enables the position parameters. The main difference between these commands is that the former allows you to specify the location relative to the "global" frames (like ``Vehicle.simple_goto()``), while the later lets you specify the location in NED co-ordinates relative @@ -175,7 +175,7 @@ When moving the vehicle you can send separate commands to control the yaw (and o .. tip:: You can also control the velocity using the - `SET_POSITION_TARGET_GLOBAL_INT `_ + `SET_POSITION_TARGET_GLOBAL_INT `_ MAVLink command, as described in :ref:`example_guided_mode_send_global_velocity`. @@ -189,8 +189,8 @@ ArduPilot does not currently support controlling the vehicle by specifying accel .. note:: - The `SET_POSITION_TARGET_GLOBAL_INT `_ and - `SET_POSITION_TARGET_LOCAL_NED `_ + The `SET_POSITION_TARGET_GLOBAL_INT `_ and + `SET_POSITION_TARGET_LOCAL_NED `_ MAVLink commands allow you to specify the acceleration, force and yaw. However, commands setting these parameters are ignored by the vehicle. @@ -221,7 +221,7 @@ to encode the message and then calling :py:func:`send_mavlink() `_ +`SET_POSITION_TARGET_LOCAL_NED `_ message we call ``message_factory.set_position_target_local_ned_encode()`` with values for all the message fields as arguments: @@ -248,7 +248,7 @@ really intended for a specific component. .. _guided_mode_how_to_send_commands_command_long: -In Copter, the `COMMAND_LONG message `_ can be used send/package +In Copter, the `COMMAND_LONG message `_ can be used send/package *a number* of different `supported MAV_CMD commands `_. The factory function is again the lower case message name with suffix ``_encode`` (``message_factory.command_long_encode``). The message parameters include the actual command to be sent (in the code fragment below ``MAV_CMD_CONDITION_YAW``) and its fields. @@ -474,7 +474,7 @@ Other information ================= * `NED Frame `_ -* `MISSION_ITEM `_ +* `MISSION_ITEM `_ * `GUIDED Mode for Copter `_ (wiki). * `GUIDED mode for Plane `_ (wiki). * `Copter Commands in Guided Mode `_ (wiki).