This repository was archived by the owner on Apr 10, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathzipline.py
More file actions
391 lines (303 loc) · 13.1 KB
/
zipline.py
File metadata and controls
391 lines (303 loc) · 13.1 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#
# zipline.py
# shotmanager
#
# The zipline smart shot controller.
# Runs as a DroneKit-Python script.
#
# Created by Jason Short
# Copyright (c) 2016 3D Robotics.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from dronekit import Vehicle, LocationGlobalRelative, VehicleMode
from pymavlink import mavutil
import os
from os import sys, path
import math
import struct
sys.path.append(os.path.realpath(''))
import app_packet
import camera
import location_helpers
import vectorPathHandler
import shotLogger
import shots
from shotManagerConstants import *
# on host systems these files are located here
sys.path.append(os.path.realpath('../../flightcode/stm32'))
from sololink import btn_msg
SHALLOW_ANGLE_THRESHOLD = -5
ROI_ALT_MAX_DELTA = 50
# States
ZIPLINE_SETUP = 0
ZIPLINE_RUN = 1
# Camera modes
FREE_LOOK = 0
SPOT_LOCK = 1
YAW_SPEED = 60.0
PITCH_SPEED = 60.0
YAW_NUDGE_SPEED = 35.0
FOLLOW_ALT_NUDGE_SPEED = 6
MIN_PADDLE_THRESHOLD = 0.02
ROI_ALT_MARGIN = 5
logger = shotLogger.logger
class ZiplineShot():
def __init__(self, vehicle, shotmgr):
self.vehicle = vehicle
self.shotmgr = shotmgr
# Limit ziplines to a plane parallel with Earth surface
self.is3D = False
# default pathHandler to none
self.pathHandler = None
# track cruise speed between pathHandler instances
self.cruiseSpeed = 0
# tracks the camera control mode
self.camPointing = FREE_LOOK
# ROI will update when this is True
self.needsUpdate = True
# Camera control
self.camYaw = camera.getYaw(self.vehicle)
self.camPitch = camera.getPitch(self.vehicle)
self.camDir = 1
# initialize roi object to none
# roi used to store spot lock location object
self.roi = None
self.state = ZIPLINE_SETUP
# channels are expected to be floating point values in the (-1.0, 1.0) range
def handleRCs(self, channels):
if self.state == ZIPLINE_SETUP:
return
# handle camera per camera mode
if self.camPointing == SPOT_LOCK:
self.handleSpotLock(channels)
else:
# Freelook
self.manualPitch(channels)
self.manualYaw(channels)
self.handleFreeLookPointing()
# Vechicle control on the zipline
if self.pathHandler is not None:
self.pathHandler.move(channels)
def setupZipline(self):
if self.state == ZIPLINE_SETUP:
# enter GUIDED mode
self.vehicle.mode = VehicleMode("GUIDED")
# Take over RC
self.shotmgr.rcMgr.enableRemapping( True )
# default camera mode to FREE LOOK
self.camPointing = -1
self.initCam(FREE_LOOK)
self.state = ZIPLINE_RUN
# re-init Yaw
self.camYaw = camera.getYaw(self.vehicle)
# null pitch if we only want 2D ziplines
if self.is3D == 0:
self.camPitch = 0
# create a new pathHandler obejct with our new points
self.pathHandler = vectorPathHandler.VectorPathHandler(self.vehicle, self.shotmgr, self.camYaw, self.camPitch)
self.pathHandler.setCruiseSpeed(self.cruiseSpeed)
# re-init Pitch
self.camPitch = camera.getPitch(self.vehicle)
# update the app
self.updateAppOptions()
self.updateAppStart()
def setButtonMappings(self):
buttonMgr = self.shotmgr.buttonManager
buttonMgr.setArtooButton(
btn_msg.ButtonA, shots.APP_SHOT_ZIPLINE, btn_msg.ARTOO_BITMASK_ENABLED, "New Zipline\0")
if self.camPointing == SPOT_LOCK:
buttonMgr.setArtooButton(
btn_msg.ButtonB, shots.APP_SHOT_ZIPLINE, btn_msg.ARTOO_BITMASK_ENABLED, "Free Look\0")
else:
buttonMgr.setArtooButton(
btn_msg.ButtonB, shots.APP_SHOT_ZIPLINE, btn_msg.ARTOO_BITMASK_ENABLED, "Spot Lock\0")
def handleButton(self, button, event):
if button == btn_msg.ButtonA and event == btn_msg.ClickRelease:
self.setupZipline()
if button == btn_msg.ButtonB and event == btn_msg.ClickRelease:
# Toggle between free look and spot lock
if self.camPointing is FREE_LOOK:
self.initCam(SPOT_LOCK)
else:
self.initCam(FREE_LOOK)
if button == btn_msg.ButtonLoiter and event == btn_msg.ClickRelease:
if self.pathHandler:
self.pathHandler.togglePause()
self.cruiseSpeed = self.pathHandler.cruiseSpeed
self.updateAppOptions()
def initCam(self, _camPointing):
if _camPointing == self.camPointing:
return
if _camPointing is SPOT_LOCK:
self.spotLock()
self.camPointing = _camPointing
else:
self.manualGimbalTargeting()
self.camPointing = _camPointing
self.setButtonMappings()
self.updateAppOptions()
def updateAppOptions(self):
'''send our current set of options to the app'''
# B = uint_8
if self.pathHandler is None:
return
packet = struct.pack('<IIfBB', app_packet.SOLO_ZIPLINE_OPTIONS, 6, self.pathHandler.cruiseSpeed, self.is3D, self.camPointing)
self.shotmgr.appMgr.sendPacket(packet)
def updateAppStart(self):
'''Let app know we've started'''
if self.pathHandler is None:
return
logger.log("[ZIPLINE]: send App Start")
packet = struct.pack('<II', app_packet.SOLO_ZIPLINE_LOCK, 0)
self.shotmgr.appMgr.sendPacket(packet)
def handlePacket(self, packetType, packetLength, packetValue):
'''handle incoming data from the client app'''
try:
if packetType == app_packet.SOLO_MESSAGE_LOCATION:
(lat, lon, alt) = struct.unpack('<ddf', packetValue)
logger.log("[ZIPLINE]: Location received from app: %f, %f, %f." %( lat, lon, alt ) )
# dont read alt from App - it has no way to set it from UI
self.addLocation(LocationGlobalRelative(lat, lon, self.roi.alt))
elif packetType == app_packet.SOLO_ZIPLINE_OPTIONS:
(self.cruiseSpeed, self.is3D, _camPointing) = struct.unpack('<fBB', packetValue)
logger.log( "[ZIPLINE]: Set cruise speed to %f"% (self.cruiseSpeed,))
logger.log( "[ZIPLINE]: Set 3D path %d"% (self.is3D,))
logger.log( "[ZIPLINE]: Cam pointing %d"% (_camPointing,))
self.setButtonMappings()
self.initCam(_camPointing)
if self.pathHandler:
self.pathHandler.setCruiseSpeed(self.cruiseSpeed)
elif packetType == app_packet.SOLO_ZIPLINE_LOCK:
self.setupZipline()
else:
return False
except Exception as e:
logger.log('[ZIPLINE]: Error handling packet. (%s)' % e)
return False
else:
return True
def addLocation(self, loc):
'''called by shot manager to set new ROI from App'''
# replaces our ROI
self.roi = loc
# send this ROI to the app
packet = struct.pack('<IIddf', app_packet.SOLO_MESSAGE_LOCATION, 20, loc.lat, loc.lon, loc.alt)
self.shotmgr.appMgr.sendPacket(packet)
def spotLock(self):
'''take the angle of the copter and lock onto a ground level target'''
if self.camPointing == SPOT_LOCK:
return
self.needsUpdate = True
# don't use a shallow angle resulting in massively distant ROIs
pitch = min(camera.getPitch(self.vehicle), SHALLOW_ANGLE_THRESHOLD)
# Get ROI for the vehicle to look at
spotLock = location_helpers.getSpotLock(self.vehicle.location.global_relative_frame, pitch, camera.getYaw(self.vehicle))
self.addLocation(spotLock)
def manualGimbalTargeting(self):
'''set gimbal targeting mode to manual'''
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
)
self.vehicle.send_mavlink(msg)
# init the open loop gimbal pointing vars
self.camYaw = camera.getYaw(self.vehicle)
self.camPitch = camera.getPitch(self.vehicle)
def manualPitch(self, channels):
if abs(channels[RAW_PADDLE]) > abs(channels[THROTTLE]):
value = channels[RAW_PADDLE]
else:
value = channels[THROTTLE]
self.camPitch += PITCH_SPEED * UPDATE_TIME * value
if self.camPitch > 0.0:
self.camPitch = 0.0
elif self.camPitch < -90:
self.camPitch = -90
def manualYaw(self, channels):
if channels[YAW] == 0:
return
self.camYaw += channels[YAW] * YAW_SPEED * UPDATE_TIME
if self.camYaw > 360:
self.camYaw -= 360
if self.camYaw < 0:
self.camYaw += 360
# required for gimbals w/o Yaw
if channels[YAW] > 0:
self.camDir = 1
else:
self.camDir = -1
def handleFreeLookPointing(self):
'''Handle free look'''
# if we do have a gimbal, use mount_control to set pitch and yaw
if self.vehicle.mount_status[0] is not None:
msg = self.vehicle.message_factory.mount_control_encode(
0, 1, # Target system, target component
self.camPitch * 100, # Pitch in centidegrees
0.0, # Roll not used
self.camYaw * 100, # Yaw in centidegrees
0 # save position
)
self.vehicle.send_mavlink(msg)
else:
# if we don't have a gimbal, just set CONDITION_YAW
msg = self.vehicle.message_factory.command_long_encode(
0, 1, # target system, target component
mavutil.mavlink.MAV_CMD_CONDITION_YAW, #command
0, # confirmation
self.camYaw, # param 1 - target angle
YAW_SPEED, # param 2 - yaw speed
self.camDir, # param 3 - direction
0.0, # relative offset
0, 0, 0 # params 5-7 (unused)
)
self.vehicle.send_mavlink(msg)
def handleSpotLock(self, channels):
'''handle spot lock'''
# we rotate this value for re-pointing
dist = location_helpers.getDistanceFromPoints(self.vehicle.location.global_relative_frame, self.roi)
# rotate the ROI point
if abs(channels[YAW]) > 0:
self.needsUpdate = True
tmp = self.roi.alt
az = location_helpers.calcAzimuthFromPoints(self.vehicle.location.global_relative_frame, self.roi)
az += (channels[YAW] * YAW_NUDGE_SPEED * UPDATE_TIME)
newRoi = location_helpers.newLocationFromAzimuthAndDistance(self.vehicle.location.global_relative_frame, az, dist)
newRoi.alt = tmp
self.addLocation(newRoi)
self.updateROIAlt(channels[RAW_PADDLE])
# nothing to do if no user interaction
if not self.needsUpdate:
return
# clear update flag
self.needsUpdate = False
# Tell Gimbal ROI Location
msg = self.vehicle.message_factory.command_int_encode(
0, 1, # target system, target component
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT, #frame
mavutil.mavlink.MAV_CMD_DO_SET_ROI, #command
0, #current
0, #autocontinue
0, 0, 0, 0, #params 1-4
self.roi.lat*1.E7,
self.roi.lon*1.E7,
self.roi.alt)
self.vehicle.send_mavlink(msg)
# moves an offset of the ROI altitude up or down
def updateROIAlt(self, rawPaddleValue):
# no gimbal, no reason to change ROI
if self.vehicle.mount_status[0] == None:
return
if abs(rawPaddleValue) > MIN_PADDLE_THRESHOLD:
self.roi.alt += (rawPaddleValue * FOLLOW_ALT_NUDGE_SPEED * UPDATE_TIME)
self.roi.alt = min(self.vehicle.location.global_relative_frame.alt + ROI_ALT_MARGIN, self.roi.alt)
self.roi.alt = max(self.vehicle.location.global_relative_frame.alt - ROI_ALT_MAX_DELTA, self.roi.alt)