Skip to content

Commit 14d431f

Browse files
authored
Merge pull request #568 from mavlink/pr-example-cleanup
Examples cleanup
2 parents 1871ffa + 942834e commit 14d431f

22 files changed

+204
-273
lines changed

.github/workflows/main.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ jobs:
2828
- name: Install pip
2929
run: sudo apt-get install -y python3-pip
3030

31+
- name: Check style
32+
run: |
33+
python3 -m pip install pycodestyle
34+
export PATH=$PATH:$HOME/.local/bin
35+
pycodestyle examples/*
36+
3137
- name: Install prerequisites
3238
run: |
3339
python3 -m pip install -r requirements.txt -r requirements-dev.txt -r requirements-docs.txt

examples/all_params.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import asyncio
44
from mavsdk import System
55

6+
67
async def run():
78
# Connect to the drone
89
drone = System()

examples/camera_params.py

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
current_settings = []
2020
possible_setting_options = []
2121

22+
2223
async def run():
2324
drone = System()
2425
await drone.connect(system_address="udp://:14540")
@@ -27,7 +28,7 @@ async def run():
2728
asyncio.ensure_future(observe_camera_mode(drone))
2829
asyncio.ensure_future(observe_possible_setting_options(drone))
2930

30-
while(True):
31+
while True:
3132
entered_input = await ainput(usage_str)
3233

3334
if (entered_input == "p"):
@@ -61,7 +62,8 @@ async def run():
6162
print_possible_settings(possible_setting_options)
6263

6364
try:
64-
index_setting = await make_user_choose_setting(possible_setting_options)
65+
index_setting = await \
66+
make_user_choose_setting(possible_setting_options)
6567
except ValueError:
6668
print("Invalid index")
6769
continue
@@ -75,20 +77,32 @@ async def run():
7577
print(f"Options:")
7678
try:
7779
print_possible_options(possible_options)
78-
index_option = await make_user_choose_option(possible_options)
80+
index_option = await \
81+
make_user_choose_option(possible_options)
7982
selected_option = possible_options[index_option - 1]
8083

81-
print(f"Setting {selected_setting.setting_id} to {selected_option.option_description}!")
82-
setting = Setting(selected_setting.setting_id, "", selected_option, selected_setting.is_range)
84+
print(f"Setting {selected_setting.setting_id} "
85+
f"to {selected_option.option_description}!")
86+
setting = Setting(
87+
selected_setting.setting_id,
88+
"",
89+
selected_option,
90+
selected_setting.is_range)
8391
except ValueError:
8492
print("Invalid index")
8593
continue
8694
else:
8795
try:
88-
selected_value = await make_user_choose_option_range(possible_options)
89-
90-
print(f"Setting {selected_setting.setting_id} to {selected_value}!")
91-
setting = Setting(selected_setting.setting_id, "", Option(selected_value, ""), selected_setting.is_range)
96+
selected_value = await \
97+
make_user_choose_option_range(possible_options)
98+
99+
print(f"Setting {selected_setting.setting_id}"
100+
f" to {selected_value}!")
101+
setting = Setting(
102+
selected_setting.setting_id,
103+
"",
104+
Option(selected_value, ""),
105+
selected_setting.is_range)
92106
except ValueError:
93107
print("Invalid value")
94108
continue
@@ -102,21 +116,25 @@ async def run():
102116
print("Invalid input!")
103117
continue
104118

119+
105120
async def observe_camera_mode(drone):
106121
global camera_mode
107122
async for mode in drone.camera.mode():
108123
camera_mode = mode
109124

125+
110126
async def observe_current_settings(drone):
111127
global current_settings
112128
async for settings in drone.camera.current_settings():
113129
current_settings = settings
114130

131+
115132
async def observe_possible_setting_options(drone):
116133
global possible_setting_options
117134
async for settings in drone.camera.possible_setting_options():
118135
possible_setting_options = settings
119136

137+
120138
def print_current_settings():
121139
print(f"* CAM_MODE: {camera_mode}")
122140
for setting in current_settings:
@@ -126,6 +144,7 @@ def print_current_settings():
126144
else:
127145
print(f" -> {setting.option.option_description}")
128146

147+
129148
async def make_user_choose_camera_mode():
130149
index_mode_str = await ainput(f"\nWhich mode do you want? [1..2] >>> ")
131150
index_mode = int(index_mode_str)
@@ -134,38 +153,46 @@ async def make_user_choose_camera_mode():
134153

135154
return index_mode
136155

156+
137157
def print_possible_settings(possible_settings):
138158
i = 1
139159
for setting in possible_settings:
140160
print(f"{i}. {setting.setting_id}: {setting.setting_description}")
141161
i += 1
142162

163+
143164
async def make_user_choose_setting(possible_settings):
144165
n_settings = len(possible_settings)
145-
index_setting_str = await ainput(f"\nWhich setting do you want to change? [1..{n_settings}] >>> ")
166+
index_setting_str = await \
167+
ainput(f"\nWhich setting do you want to change?"
168+
f" [1..{n_settings}] >>> ")
146169

147170
index_setting = int(index_setting_str)
148171
if (index_setting < 1 or index_setting > n_settings):
149172
raise ValueError()
150173

151174
return index_setting
152175

176+
153177
def print_possible_options(possible_options):
154178
i = 1
155179
for possible_option in possible_options:
156180
print(f"{i}. {possible_option.option_description}")
157181
i += 1
158182

183+
159184
async def make_user_choose_option(possible_options):
160185
n_options = len(possible_options)
161-
index_option_str = await ainput(f"\nWhich option do you want? [1..{n_options}] >>> ")
186+
index_option_str = await \
187+
ainput(f"\nWhich option do you want? [1..{n_options}] >>> ")
162188

163189
index_option = int(index_option_str)
164190
if (index_option < 1 or index_option > n_options):
165191
raise ValueError()
166192

167193
return index_option
168194

195+
169196
async def make_user_choose_option_range(possible_options):
170197
min_value = float(possible_options[0].option_id)
171198
max_value = float(possible_options[1].option_id)
@@ -175,7 +202,9 @@ async def make_user_choose_option_range(possible_options):
175202
interval_value = float(possible_options[2].option_id)
176203
interval_text = f"interval: {interval_value}"
177204

178-
value_str = await ainput(f"\nWhat value do you want? [{min_value}, {max_value}] {interval_text} >>> ")
205+
value_str = await \
206+
ainput(f"\nWhat value do you want?"
207+
f" [{min_value}, {max_value}] {interval_text} >>> ")
179208

180209
value = float(value_str)
181210
if (value < min_value or value > max_value):

examples/failure_injection.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from mavsdk import System
66
from mavsdk.failure import FailureType, FailureUnit
77

8+
89
async def run():
910
drone = System()
1011
await drone.connect(system_address="udp://:14540")
@@ -44,13 +45,14 @@ async def run():
4445
break
4546

4647
print("-- Flying up")
47-
flying_alt = goto_alt + 20.0 # To fly drone 20m above the ground plane
48+
flying_alt = goto_alt + 20.0 # To fly drone 20m above the ground plane
4849
await drone.action.goto_location(goto_lat, goto_lon, flying_alt, 0)
4950

5051
await asyncio.sleep(5)
5152

5253
print("-- Injecting GPS failure")
53-
await drone.failure.inject(FailureUnit.SENSOR_GPS, FailureType.OFF, instance=0)
54+
await drone.failure.inject(
55+
FailureUnit.SENSOR_GPS, FailureType.OFF, instance=0)
5456

5557
print("-- Waiting 20s before exiting script...")
5658
await asyncio.sleep(20)

examples/follow_me_example.py

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,27 @@
11
#!/usr/bin/env python3
22

3-
#This example shows how to use the follow me plugin
3+
# This example shows how to use the follow me plugin
44

55
import asyncio
66
from mavsdk import System
77
from mavsdk.follow_me import (Config, FollowMeError, TargetLocation)
88

9-
default_height = 8.0 #in Meters
10-
follow_distance = 2.0 #in Meters, this is the distance that the drone will remain away from Target while following it
11-
#Direction relative to the Target
12-
#Options are NONE, FRONT, FRONT_LEFT, FRONT_RIGHT, BEHIND
9+
10+
default_height = 8.0 # in meters
11+
# distance between drone and target
12+
follow_distance = 2.0 # in meters
13+
14+
# Direction relative to the Target
15+
# Options are NONE, FRONT, FRONT_LEFT, FRONT_RIGHT, BEHIND
1316
direction = Config.FollowDirection.BEHIND
14-
responsiveness = 0.02
17+
responsiveness = 0.02
18+
19+
# This list contains fake location coordinates
20+
# (These coordinates are obtained from mission.py example)
21+
fake_location = [[47.398039859999997, 8.5455725400000002],
22+
[47.398036222362471, 8.5450146439425509],
23+
[47.397825620791885, 8.5450092830163271]]
1524

16-
#This list contains fake location coordinates (These coordinates are obtained from mission.py example)
17-
fake_location = [[47.398039859999997,8.5455725400000002],[47.398036222362471,8.5450146439425509],[47.397825620791885,8.5450092830163271]]
1825

1926
async def fly_drone():
2027
drone = System()
@@ -32,35 +39,37 @@ async def fly_drone():
3239
print("-- Global position estimate OK")
3340
break
3441

35-
#Arming the drone
36-
print ("-- Arming")
42+
# Arming the drone
43+
print("-- Arming")
3744
await drone.action.arm()
3845

39-
#Follow me Mode requires some configuration to be done before starting the mode
46+
# Follow me Mode requires some configuration to be done before starting
47+
# the mode
4048
conf = Config(default_height, follow_distance, direction, responsiveness)
4149
await drone.follow_me.set_config(conf)
4250

43-
print ("-- Taking Off")
51+
print("-- Taking Off")
4452
await drone.action.takeoff()
4553
await asyncio.sleep(8)
46-
print ("-- Starting Follow Me Mode")
54+
print("-- Starting Follow Me Mode")
4755
await drone.follow_me.start()
4856
await asyncio.sleep(8)
4957

50-
#This for loop provides fake coordinates from the fake_location list for the follow me mode to work
51-
#In a simulator it won't make much sense though
52-
for latitude,longitude in fake_location:
58+
# This for loop provides fake coordinates from the fake_location list for
59+
# the follow me mode to work.
60+
# In a simulator it won't make much sense though
61+
for latitude, longitude in fake_location:
5362
target = TargetLocation(latitude, longitude, 0, 0, 0, 0)
54-
print ("-- Following Target")
63+
print("-- Following Target")
5564
await drone.follow_me.set_target_location(target)
5665
await asyncio.sleep(2)
5766

58-
#Stopping the follow me mode
59-
print ("-- Stopping Follow Me Mode")
67+
# Stopping the follow me mode
68+
print("-- Stopping Follow Me Mode")
6069
await drone.follow_me.stop()
6170
await asyncio.sleep(5)
6271

63-
print ("-- Landing")
72+
print("-- Landing")
6473
await drone.action.land()
6574

6675
if __name__ == "__main__":

examples/geofence.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
"""
88
This example shows how to use the geofence plugin.
99
10-
Note: The behavior when your vehicle hits the geofence is NOT configured in this example.
10+
Note: The behavior when your vehicle hits the geofence is NOT configured
11+
in this example.
1112
1213
"""
1314

@@ -25,7 +26,8 @@ async def run():
2526
print(f"-- Connected to drone!")
2627
break
2728

28-
# Fetch the home location coordinates, in order to set a boundary around the home location
29+
# Fetch the home location coordinates, in order to set a boundary around
30+
# the home location.
2931
print("Fetching home location coordinates...")
3032
async for terrain_info in drone.telemetry.home():
3133
latitude = terrain_info.latitude_deg

examples/gimbal.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,15 @@
44
from mavsdk import System
55
from mavsdk.gimbal import GimbalMode, ControlMode
66

7+
78
async def run():
89
# Init the drone
910
drone = System()
1011
await drone.connect(system_address="udp://:14540")
1112

1213
# Start printing gimbal position updates
13-
print_gimbal_position_task = asyncio.ensure_future(print_gimbal_position(drone))
14+
print_gimbal_position_task = \
15+
asyncio.ensure_future(print_gimbal_position(drone))
1416

1517
print("Taking control of gimbal")
1618
await drone.gimbal.take_control(ControlMode.PRIMARY)

examples/manual_control.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33
"""
44
This example shows how to use the manual controls plugin.
55
6-
Note: Manual inputs are taken from a test set in this example to decrease complexity. Manual inputs
7-
can be received from devices such as a joystick using third-party python extensions
6+
Note: Manual inputs are taken from a test set in this example to decrease
7+
complexity. Manual inputs can be received from devices such as a joystick
8+
using third-party python extensions.
89
9-
Note: Taking off the drone is not necessary before enabling manual inputs. It is acceptable to send
10-
positive throttle input to leave the ground. Takeoff is used in this example to decrease complexity
10+
Note: Taking off the drone is not necessary before enabling manual inputs.
11+
It is acceptable to send positive throttle input to leave the ground.
12+
Takeoff is used in this example to decrease complexity
1113
"""
1214

1315
import asyncio
@@ -80,12 +82,14 @@ async def manual_controls():
8082
roll = float(input_list[0])
8183
# get current state of pitch axis (between -1 and 1)
8284
pitch = float(input_list[1])
83-
# get current state of throttle axis (between -1 and 1, but between 0 and 1 is expected)
85+
# get current state of throttle axis
86+
# (between -1 and 1, but between 0 and 1 is expected)
8487
throttle = float(input_list[2])
8588
# get current state of yaw axis (between -1 and 1)
8689
yaw = float(input_list[3])
8790

88-
await drone.manual_control.set_manual_control_input(roll, pitch, throttle, yaw)
91+
await drone.manual_control.set_manual_control_input(
92+
roll, pitch, throttle, yaw)
8993

9094
await asyncio.sleep(0.1)
9195

examples/mission_import.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@ async def run():
1616
print(f"-- Connected to drone!")
1717
break
1818

19-
mission_import_data = await drone.mission_raw.import_qgroundcontrol_mission("example-mission.plan")
19+
mission_import_data = await \
20+
drone.mission_raw.import_qgroundcontrol_mission(
21+
"example-mission.plan")
2022
print(f"{len(mission_import_data.mission_items)} mission items imported")
2123
await drone.mission_raw.upload_mission(mission_import_data.mission_items)
2224
print("Mission uploaded")
2325

2426

25-
2627
if __name__ == "__main__":
2728
# Run the asyncio loop
2829
asyncio.run(run())

0 commit comments

Comments
 (0)