-
Notifications
You must be signed in to change notification settings - Fork 900
/
Copy pathswarm.py
298 lines (240 loc) · 9.62 KB
/
swarm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2016 Bitcraze AB
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import time
from collections import namedtuple
from threading import Thread
from cflib.crazyflie import Crazyflie
from cflib.crazyflie.log import LogConfig
from cflib.crazyflie.syncCrazyflie import SyncCrazyflie
from cflib.crazyflie.syncLogger import SyncLogger
SwarmPosition = namedtuple('SwarmPosition', 'x y z')
class _Factory:
"""
Default Crazyflie factory class.
"""
def construct(self, uri):
return SyncCrazyflie(uri)
class CachedCfFactory:
"""
Factory class that creates Crazyflie instances with TOC caching
to reduce connection time.
"""
def __init__(self, ro_cache=None, rw_cache=None):
self.ro_cache = ro_cache
self.rw_cache = rw_cache
def construct(self, uri):
cf = Crazyflie(ro_cache=self.ro_cache, rw_cache=self.rw_cache)
return SyncCrazyflie(uri, cf=cf)
class Swarm:
"""
Runs a swarm of Crazyflies. It implements a functional-ish style of
sequential or parallel actions on all individuals of the swarm.
When the swarm is connected, a link is opened to each Crazyflie through
SyncCrazyflie instances. The instances are maintained by the class and are
passed in as the first argument in swarm wide actions.
"""
def __init__(self, uris, factory=_Factory()):
"""
Constructs a Swarm instance and instances used to connect to the
Crazyflies
:param uris: A set of uris to use when connecting to the Crazyflies in
the swarm
:param factory: A factory class used to create the instances that are
used to open links to the Crazyflies. Mainly used for unit testing.
"""
self._cfs = {}
self._is_open = False
self._positions = dict()
for uri in uris:
self._cfs[uri] = factory.construct(uri)
def open_links(self):
"""
Open links to all individuals in the swarm
"""
if self._is_open:
raise Exception('Already opened')
try:
self.parallel_safe(lambda scf: scf.open_link())
self._is_open = True
except Exception as e:
self.close_links()
raise e
def close_links(self):
"""
Close all open links
"""
for uri, cf in self._cfs.items():
cf.close_link()
self._is_open = False
def __enter__(self):
self.open_links()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close_links()
def __get_estimated_position(self, scf):
log_config = LogConfig(name='stateEstimate', period_in_ms=10)
log_config.add_variable('stateEstimate.x', 'float')
log_config.add_variable('stateEstimate.y', 'float')
log_config.add_variable('stateEstimate.z', 'float')
with SyncLogger(scf, log_config) as logger:
for entry in logger:
x = entry[1]['stateEstimate.x']
y = entry[1]['stateEstimate.y']
z = entry[1]['stateEstimate.z']
self._positions[scf.cf.link_uri] = SwarmPosition(x, y, z)
break
def get_estimated_positions(self):
"""
Return a `dict`, keyed by URI and with the SwarmPosition namedtuples as
value, with the estimated (x, y, z) of each Crazyflie in the swarm.
"""
self.parallel_safe(self.__get_estimated_position)
return self._positions
def __wait_for_position_estimator(self, scf):
log_config = LogConfig(name='Kalman Variance', period_in_ms=500)
log_config.add_variable('kalman.varPX', 'float')
log_config.add_variable('kalman.varPY', 'float')
log_config.add_variable('kalman.varPZ', 'float')
var_y_history = [1000] * 10
var_x_history = [1000] * 10
var_z_history = [1000] * 10
threshold = 0.001
with SyncLogger(scf, log_config) as logger:
for log_entry in logger:
data = log_entry[1]
var_x_history.append(data['kalman.varPX'])
var_x_history.pop(0)
var_y_history.append(data['kalman.varPY'])
var_y_history.pop(0)
var_z_history.append(data['kalman.varPZ'])
var_z_history.pop(0)
min_x = min(var_x_history)
max_x = max(var_x_history)
min_y = min(var_y_history)
max_y = max(var_y_history)
min_z = min(var_z_history)
max_z = max(var_z_history)
if (max_x - min_x) < threshold and (
max_y - min_y) < threshold and (
max_z - min_z) < threshold:
break
def __reset_estimator(self, scf):
cf = scf.cf
cf.param.set_value('kalman.resetEstimation', '1')
time.sleep(0.1)
cf.param.set_value('kalman.resetEstimation', '0')
self.__wait_for_position_estimator(scf)
def reset_estimators(self):
"""
Reset estimator on all members of the swarm and wait for a stable
positions. Blocks until position estimators finds a position.
"""
self.parallel_safe(self.__reset_estimator)
def sequential(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in sequence.
The first argument of the function that is passed in will be a
SyncCrazyflie instance connected to the Crazyflie to operate on.
A list of optional parameters (per Crazyflie) may follow defined by
the `args_dict`. The dictionary is keyed on URI and has a list of
parameters as value.
Example:
```python
def my_function(scf, optional_param0, optional_param1)
...
args_dict = {
URI0: [optional_param0_cf0, optional_param1_cf0],
URI1: [optional_param0_cf1, optional_param1_cf1],
...
}
swarm.sequential(my_function, args_dict)
```
:param func: The function to execute
:param args_dict: Parameters to pass to the function
"""
for uri, cf in self._cfs.items():
args = self._process_args_dict(cf, uri, args_dict)
func(*args)
def parallel(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in parallel.
One thread per Crazyflie is started to execute the function. The
threads are joined at the end. Exceptions raised by the threads are
ignored.
For a more detailed description of the arguments, see `sequential()`
:param func: The function to execute
:param args_dict: Parameters to pass to the function
"""
try:
self.parallel_safe(func, args_dict)
except Exception:
pass
def parallel_safe(self, func, args_dict=None):
"""
Execute a function for all Crazyflies in the swarm, in parallel.
One thread per Crazyflie is started to execute the function. The
threads are joined at the end and if one or more of the threads raised
an exception this function will also raise an exception.
For a more detailed description of the arguments, see `sequential()`
:param func: The function to execute
:param args_dict: Parameters to pass to the function
"""
threads = []
reporter = self.Reporter()
for uri, scf in self._cfs.items():
args = [func, reporter] + \
self._process_args_dict(scf, uri, args_dict)
thread = Thread(target=self._thread_function_wrapper, args=args)
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
if reporter.is_error_reported():
first_error = reporter.errors[0]
raise Exception('One or more threads raised an exception when '
'executing parallel task') from first_error
def _thread_function_wrapper(self, *args):
reporter = None
try:
func = args[0]
reporter = args[1]
func(*args[2:])
except Exception as e:
if reporter:
reporter.report_error(e)
def _process_args_dict(self, scf, uri, args_dict):
args = [scf]
if args_dict:
args += args_dict[uri]
return args
class Reporter:
def __init__(self):
self.error_reported = False
self._errors = []
@property
def errors(self):
return self._errors
def report_error(self, e):
self.error_reported = True
self._errors.append(e)
def is_error_reported(self):
return self.error_reported