INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create DCM from euler angles :param dcm: Matrix3 :returns: array [roll, pitch, yaw] in rad
def _dcm_to_euler(self, dcm): """ Create DCM from euler angles :param dcm: Matrix3 :returns: array [roll, pitch, yaw] in rad """ assert(isinstance(dcm, Matrix3)) return np.array(dcm.to_euler())
work out gps lock times for a log file
def lock_time(logfile): '''work out gps lock times for a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename) locked = False start_time = 0.0 total_time = 0.0 t = None m = mlog.recv_match(type=['GPS_RAW_INT','GPS_RAW'], condition=args.condition) if m is None: return 0 unlock_time = time.mktime(time.localtime(m._timestamp)) while True: m = mlog.recv_match(type=['GPS_RAW_INT','GPS_RAW'], condition=args.condition) if m is None: if locked: total_time += time.mktime(t) - start_time if total_time > 0: print("Lock time : %u:%02u" % (int(total_time)/60, int(total_time)%60)) return total_time t = time.localtime(m._timestamp) if m.fix_type >= 2 and not locked: print("Locked at %s after %u seconds" % (time.asctime(t), time.mktime(t) - unlock_time)) locked = True start_time = time.mktime(t) elif m.fix_type == 1 and locked: print("Lost GPS lock at %s" % time.asctime(t)) locked = False total_time += time.mktime(t) - start_time unlock_time = time.mktime(t) elif m.fix_type == 0 and locked: print("Lost protocol lock at %s" % time.asctime(t)) locked = False total_time += time.mktime(t) - start_time unlock_time = time.mktime(t) return total_time
handle menu selection
def on_menu(self, event): '''handle menu selection''' state = self.state # see if it is a popup menu if state.popup_object is not None: obj = state.popup_object ret = obj.popup_menu.find_selected(event) if ret is not None: ret.call_handler() state.event_queue.put(SlipMenuEvent(state.popup_latlon, event, [SlipObjectSelection(obj.key, 0, obj.layer, obj.selection_info())], ret)) state.popup_object = None state.popup_latlon = None if state.default_popup is not None: ret = state.default_popup.popup.find_selected(event) if ret is not None: ret.call_handler() state.event_queue.put(SlipMenuEvent(state.popup_latlon, event, [], ret)) # otherwise a normal menu ret = self.menu.find_selected(event) if ret is None: return ret.call_handler() if ret.returnkey == 'toggleGrid': state.grid = ret.IsChecked() elif ret.returnkey == 'toggleFollow': state.follow = ret.IsChecked() elif ret.returnkey == 'toggleDownload': state.download = ret.IsChecked() elif ret.returnkey == 'setService': state.mt.set_service(ret.get_choice()) elif ret.returnkey == 'gotoPosition': state.panel.enter_position() elif ret.returnkey == 'increaseBrightness': state.brightness *= 1.25 elif ret.returnkey == 'decreaseBrightness': state.brightness /= 1.25 state.need_redraw = True
follow an object on the map
def follow(self, object): '''follow an object on the map''' state = self.state (px,py) = state.panel.pixmapper(object.latlon) ratio = 0.25 if (px > ratio*state.width and px < (1.0-ratio)*state.width and py > ratio*state.height and py < (1.0-ratio)*state.height): # we're in the mid part of the map already, don't move return if not state.follow: # the user has disabled following return (lat, lon) = object.latlon state.panel.re_center(state.width/2, state.height/2, lat, lon)
add an object to a later
def add_object(self, obj): '''add an object to a later''' state = self.state if not obj.layer in state.layers: # its a new layer state.layers[obj.layer] = {} state.layers[obj.layer][obj.key] = obj state.need_redraw = True
remove an object by key from all layers
def remove_object(self, key): '''remove an object by key from all layers''' state = self.state for layer in state.layers: state.layers[layer].pop(key, None) state.need_redraw = True
prevent the main loop spinning too fast
def on_idle(self, event): '''prevent the main loop spinning too fast''' state = self.state if state.close_window.acquire(False): self.state.app.ExitMainLoop() # receive any display objects from the parent obj = None while not state.object_queue.empty(): obj = state.object_queue.get() if isinstance(obj, SlipObject): self.add_object(obj) if isinstance(obj, SlipPosition): # move an object object = self.find_object(obj.key, obj.layer) if object is not None: object.update_position(obj) if getattr(object, 'follow', False): self.follow(object) state.need_redraw = True if isinstance(obj, SlipDefaultPopup): state.default_popup = obj if isinstance(obj, SlipInformation): # see if its a existing one or a new one if obj.key in state.info: # print('update %s' % str(obj.key)) state.info[obj.key].update(obj) else: # print('add %s' % str(obj.key)) state.info[obj.key] = obj state.need_redraw = True if isinstance(obj, SlipCenter): # move center (lat,lon) = obj.latlon state.panel.re_center(state.width/2, state.height/2, lat, lon) state.need_redraw = True if isinstance(obj, SlipBrightness): # set map brightness state.brightness = obj.brightness state.need_redraw = True if isinstance(obj, SlipClearLayer): # remove all objects from a layer if obj.layer in state.layers: state.layers.pop(obj.layer) state.need_redraw = True if isinstance(obj, SlipRemoveObject): # remove an object by key for layer in state.layers: if obj.key in state.layers[layer]: state.layers[layer].pop(obj.key) state.need_redraw = True if isinstance(obj, SlipHideObject): # hide an object by key for layer in state.layers: if obj.key in state.layers[layer]: state.layers[layer][obj.key].set_hidden(obj.hide) state.need_redraw = True if obj is None: time.sleep(0.05)
return a tuple representing the current view
def current_view(self): '''return a tuple representing the current view''' state = self.state return (state.lat, state.lon, state.width, state.height, state.ground_width, state.mt.tiles_pending())
return coordinates of a pixel in the map
def coordinates(self, x, y): '''return coordinates of a pixel in the map''' state = self.state return state.mt.coord_from_area(x, y, state.lat, state.lon, state.width, state.ground_width)
re-center view for pixel x,y
def re_center(self, x, y, lat, lon): '''re-center view for pixel x,y''' state = self.state if lat is None or lon is None: return (lat2,lon2) = self.coordinates(x, y) distance = mp_util.gps_distance(lat2, lon2, lat, lon) bearing = mp_util.gps_bearing(lat2, lon2, lat, lon) (state.lat, state.lon) = mp_util.gps_newpos(state.lat, state.lon, bearing, distance)
zoom in or out by zoom factor, keeping centered
def change_zoom(self, zoom): '''zoom in or out by zoom factor, keeping centered''' state = self.state if self.mouse_pos: (x,y) = (self.mouse_pos.x, self.mouse_pos.y) else: (x,y) = (state.width/2, state.height/2) (lat,lon) = self.coordinates(x, y) state.ground_width *= zoom # limit ground_width to sane values state.ground_width = max(state.ground_width, 20) state.ground_width = min(state.ground_width, 20000000) self.re_center(x,y, lat, lon)
enter new position
def enter_position(self): '''enter new position''' state = self.state dlg = wx.TextEntryDialog(self, 'Enter new position', 'Position') dlg.SetValue("%f %f" % (state.lat, state.lon)) if dlg.ShowModal() == wx.ID_OK: latlon = dlg.GetValue().split() dlg.Destroy() state.lat = float(latlon[0]) state.lon = float(latlon[1]) self.re_center(state.width/2,state.height/2, state.lat, state.lon) self.redraw_map()
update position text
def update_position(self): '''update position text''' state = self.state pos = self.mouse_pos newtext = '' alt = 0 if pos is not None: (lat,lon) = self.coordinates(pos.x, pos.y) newtext += 'Cursor: %f %f (%s)' % (lat, lon, mp_util.latlon_to_grid((lat, lon))) if state.elevation: alt = self.ElevationMap.GetElevation(lat, lon) if alt is not None: newtext += ' %.1fm' % alt state.mt.set_download(state.download) pending = 0 if state.download: pending = state.mt.tiles_pending() if pending: newtext += ' Map Downloading %u ' % pending if alt == -1: newtext += ' SRTM Downloading ' newtext += '\n' if self.click_pos is not None: newtext += 'Click: %f %f (%s %s) (%s)' % (self.click_pos[0], self.click_pos[1], mp_util.degrees_to_dms(self.click_pos[0]), mp_util.degrees_to_dms(self.click_pos[1]), mp_util.latlon_to_grid(self.click_pos)) if self.last_click_pos is not None: distance = mp_util.gps_distance(self.last_click_pos[0], self.last_click_pos[1], self.click_pos[0], self.click_pos[1]) bearing = mp_util.gps_bearing(self.last_click_pos[0], self.last_click_pos[1], self.click_pos[0], self.click_pos[1]) newtext += ' Distance: %.1fm Bearing %.1f' % (distance, bearing) if newtext != state.oldtext: self.position.Clear() self.position.WriteText(newtext) state.oldtext = newtext
return pixel coordinates in the map image for a (lat,lon) if reverse is set, then return lat/lon for a pixel coordinate
def pixel_coords(self, latlon, reverse=False): '''return pixel coordinates in the map image for a (lat,lon) if reverse is set, then return lat/lon for a pixel coordinate ''' state = self.state if reverse: (x,y) = latlon return self.coordinates(x,y) (lat,lon) = (latlon[0], latlon[1]) return state.mt.coord_to_pixel(state.lat, state.lon, state.width, state.ground_width, lat, lon)
draw objects on the image
def draw_objects(self, objects, bounds, img): '''draw objects on the image''' keys = objects.keys() keys.sort() for k in keys: obj = objects[k] bounds2 = obj.bounds() if bounds2 is None or mp_util.bounds_overlap(bounds, bounds2): obj.draw(img, self.pixmapper, bounds)
redraw the map with current settings
def redraw_map(self): '''redraw the map with current settings''' state = self.state view_same = (self.last_view and self.map_img and self.last_view == self.current_view()) if view_same and not state.need_redraw: return # get the new map self.map_img = state.mt.area_to_image(state.lat, state.lon, state.width, state.height, state.ground_width) if state.brightness != 1.0: cv.ConvertScale(self.map_img, self.map_img, scale=state.brightness) # find display bounding box (lat2,lon2) = self.coordinates(state.width-1, state.height-1) bounds = (lat2, state.lon, state.lat-lat2, lon2-state.lon) # get the image img = cv.CloneImage(self.map_img) # possibly draw a grid if state.grid: SlipGrid('grid', layer=3, linewidth=1, colour=(255,255,0)).draw(img, self.pixmapper, bounds) # draw layer objects keys = state.layers.keys() keys.sort() for k in keys: self.draw_objects(state.layers[k], bounds, img) # draw information objects for key in state.info: state.info[key].draw(state.panel, state.panel.information) # display the image self.img = wx.EmptyImage(state.width,state.height) self.img.SetData(img.tostring()) self.imagePanel.set_image(self.img) self.update_position() self.mainSizer.Fit(self) self.Refresh() self.last_view = self.current_view() self.SetFocus() state.need_redraw = False
handle window size changes
def on_size(self, event): '''handle window size changes''' state = self.state size = event.GetSize() state.width = size.width state.height = size.height self.redraw_map()
return a list of matching objects for a position
def selected_objects(self, pos): '''return a list of matching objects for a position''' state = self.state selected = [] (px, py) = pos for layer in state.layers: for key in state.layers[layer]: obj = state.layers[layer][key] distance = obj.clicked(px, py) if distance is not None: selected.append(SlipObjectSelection(key, distance, layer, extra_info=obj.selection_info())) selected.sort(key=lambda c: c.distance) return selected
show default popup menu
def show_default_popup(self, pos): '''show default popup menu''' state = self.state if state.default_popup.popup is not None: wx_menu = state.default_popup.popup.wx_menu() state.frame.PopupMenu(wx_menu, pos)
clear all thumbnails from the map
def clear_thumbnails(self): '''clear all thumbnails from the map''' state = self.state for l in state.layers: keys = state.layers[l].keys()[:] for key in keys: if (isinstance(state.layers[l][key], SlipThumbnail) and not isinstance(state.layers[l][key], SlipIcon)): state.layers[l].pop(key)
handle keyboard input
def on_key_down(self, event): '''handle keyboard input''' state = self.state # send all key events to the parent if self.mouse_pos: latlon = self.coordinates(self.mouse_pos.x, self.mouse_pos.y) selected = self.selected_objects(self.mouse_pos) state.event_queue.put(SlipKeyEvent(latlon, event, selected)) c = event.GetUniChar() if c == ord('+') or (c == ord('=') and event.ShiftDown()): self.change_zoom(1.0/1.2) event.Skip() elif c == ord('-'): self.change_zoom(1.2) event.Skip() elif c == ord('G'): self.enter_position() event.Skip() elif c == ord('C'): self.clear_thumbnails() event.Skip()
evaluation an expression
def evaluate_expression(expression, vars): '''evaluation an expression''' try: v = eval(expression, globals(), vars) except NameError: return None except ZeroDivisionError: return None return v
Compile style.qrc using rcc, pyside-rcc and pyrcc4
def compile_all(): """ Compile style.qrc using rcc, pyside-rcc and pyrcc4 """ # print("Compiling for Qt: style.qrc -> style.rcc") # os.system("rcc style.qrc -o style.rcc") print("Compiling for PyQt4: style.qrc -> pyqt_style_rc.py") os.system("pyrcc4 -py3 style.qrc -o pyqt_style_rc.py") print("Compiling for PyQt5: style.qrc -> pyqt5_style_rc.py") os.system("pyrcc5 style.qrc -o pyqt5_style_rc.py") print("Compiling for PySide: style.qrc -> pyside_style_rc.py") os.system("pyside-rcc -py3 style.qrc -o pyside_style_rc.py")
plot a set of graphs using date for x axis
def plotit(self, x, y, fields, colors=[]): '''plot a set of graphs using date for x axis''' pylab.ion() fig = pylab.figure(num=1, figsize=(12,6)) ax1 = fig.gca() ax2 = None xrange = 0.0 for i in range(0, len(fields)): if len(x[i]) == 0: continue if self.lowest_x is None or x[i][0] < self.lowest_x: self.lowest_x = x[i][0] if self.highest_x is None or x[i][-1] > self.highest_x: self.highest_x = x[i][-1] if self.highest_x is None or self.lowest_x is None: return xrange = self.highest_x - self.lowest_x xrange *= 24 * 60 * 60 self.formatter = matplotlib.dates.DateFormatter('%H:%M:%S') interval = 1 intervals = [ 1, 2, 5, 10, 15, 30, 60, 120, 240, 300, 600, 900, 1800, 3600, 7200, 5*3600, 10*3600, 24*3600 ] for interval in intervals: if xrange / interval < 15: break locator = matplotlib.dates.SecondLocator(interval=interval) if not self.xaxis: ax1.xaxis.set_major_locator(locator) ax1.xaxis.set_major_formatter(self.formatter) empty = True ax1_labels = [] ax2_labels = [] for i in range(0, len(fields)): if len(x[i]) == 0: print("Failed to find any values for field %s" % fields[i]) continue if i < len(colors): color = colors[i] else: color = 'red' (tz, tzdst) = time.tzname if self.axes[i] == 2: if ax2 == None: ax2 = ax1.twinx() ax2.format_coord = self.make_format(ax2, ax1) ax = ax2 if not self.xaxis: ax2.xaxis.set_major_locator(locator) ax2.xaxis.set_major_formatter(self.formatter) label = fields[i] if label.endswith(":2"): label = label[:-2] ax2_labels.append(label) else: ax1_labels.append(fields[i]) ax = ax1 if self.xaxis: if self.marker is not None: marker = self.marker else: marker = '+' if self.linestyle is not None: linestyle = self.linestyle else: linestyle = 'None' ax.plot(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker) else: if self.marker is not None: marker = self.marker else: marker = 'None' if self.linestyle is not None: linestyle = self.linestyle else: linestyle = '-' ax.plot_date(x[i], y[i], color=color, label=fields[i], linestyle=linestyle, marker=marker, tz=None) empty = False if self.flightmode is not None: for i in range(len(self.modes)-1): c = colourmap[self.flightmode].get(self.modes[i][1], edge_colour) ax1.axvspan(self.modes[i][0], self.modes[i+1][0], fc=c, ec=edge_colour, alpha=0.1) c = colourmap[self.flightmode].get(self.modes[-1][1], edge_colour) ax1.axvspan(self.modes[-1][0], ax1.get_xlim()[1], fc=c, ec=edge_colour, alpha=0.1) if ax1_labels != []: ax1.legend(ax1_labels,loc=self.legend) if ax2_labels != []: ax2.legend(ax2_labels,loc=self.legend2) if empty: print("No data to graph") return
add some data
def add_data(self, t, msg, vars, flightmode): '''add some data''' mtype = msg.get_type() if self.flightmode is not None and (len(self.modes) == 0 or self.modes[-1][1] != flightmode): self.modes.append((t, flightmode)) for i in range(0, len(self.fields)): if mtype not in self.field_types[i]: continue f = self.fields[i] if f.endswith(":2"): self.axes[i] = 2 f = f[:-2] if f.endswith(":1"): self.first_only[i] = True f = f[:-2] v = mavutil.evaluate_expression(f, vars) if v is None: continue if self.xaxis is None: xv = t else: xv = mavutil.evaluate_expression(self.xaxis, vars) if xv is None: continue self.y[i].append(v) self.x[i].append(xv)
process one file
def process_mav(self, mlog, timeshift): '''process one file''' self.vars = {} while True: msg = mlog.recv_msg() if msg is None: break if msg.get_type() not in self.msg_types: continue if self.condition: if not mavutil.evaluate_condition(self.condition, mlog.messages): continue tdays = matplotlib.dates.date2num(datetime.datetime.fromtimestamp(msg._timestamp+timeshift)) self.add_data(tdays, msg, mlog.messages, mlog.flightmode)
process and display graph
def process(self, block=True): '''process and display graph''' self.msg_types = set() self.multiplier = [] self.field_types = [] # work out msg types we are interested in self.x = [] self.y = [] self.modes = [] self.axes = [] self.first_only = [] re_caps = re.compile('[A-Z_][A-Z0-9_]+') for f in self.fields: caps = set(re.findall(re_caps, f)) self.msg_types = self.msg_types.union(caps) self.field_types.append(caps) self.y.append([]) self.x.append([]) self.axes.append(1) self.first_only.append(False) if self.labels is not None: labels = self.labels.split(',') if len(labels) != len(fields)*len(self.mav_list): print("Number of labels (%u) must match number of fields (%u)" % ( len(labels), len(fields)*len(self.mav_list))) return else: labels = None timeshift = self.timeshift for fi in range(0, len(self.mav_list)): mlog = self.mav_list[fi] self.process_mav(mlog, timeshift) timeshift = 0 for i in range(0, len(self.x)): if self.first_only[i] and fi != 0: self.x[i] = [] self.y[i] = [] if labels: lab = labels[fi*len(self.fields):(fi+1)*len(self.fields)] else: lab = self.fields[:] if self.multi: col = colors[:] else: col = colors[fi*len(self.fields):] self.plotit(self.x, self.y, lab, colors=col) for i in range(0, len(self.x)): self.x[i] = [] self.y[i] = [] pylab.draw()
null terminate a string
def null_term(str): '''null terminate a string''' idx = str.find("\0") if idx != -1: str = str[:idx] return str
return True if a file appears to be a valid text log
def DFReader_is_text_log(filename): '''return True if a file appears to be a valid text log''' f = open(filename) ret = (f.read(8000).find('FMT, ') != -1) f.close() return ret
create a binary message buffer for a message
def get_msgbuf(self): '''create a binary message buffer for a message''' values = [] for i in range(len(self.fmt.columns)): if i >= len(self.fmt.msg_mults): continue mul = self.fmt.msg_mults[i] name = self.fmt.columns[i] if name == 'Mode' and 'ModeNum' in self.fmt.columns: name = 'ModeNum' v = self.__getattr__(name) if mul is not None: v /= mul values.append(v) return struct.pack("BBB", 0xA3, 0x95, self.fmt.type) + struct.pack(self.fmt.msg_struct, *values)
work out time basis for the log - even newer style
def find_time_base(self, gps, first_us_stamp): '''work out time basis for the log - even newer style''' t = self._gpsTimeToTime(gps.GWk, gps.GMS) self.set_timebase(t - gps.TimeUS*0.000001) # this ensures FMT messages get appropriate timestamp: self.timestamp = self.timebase + first_us_stamp*0.000001
The TimeMS in some messages is not from *our* clock!
def type_has_good_TimeMS(self, type): '''The TimeMS in some messages is not from *our* clock!''' if type.startswith('ACC'): return False; if type.startswith('GYR'): return False; return True
work out time basis for the log - new style
def find_time_base(self, gps, first_ms_stamp): '''work out time basis for the log - new style''' t = self._gpsTimeToTime(gps.Week, gps.TimeMS) self.set_timebase(t - gps.T*0.001) self.timestamp = self.timebase + first_ms_stamp*0.001
work out time basis for the log - PX4 native
def find_time_base(self, gps): '''work out time basis for the log - PX4 native''' t = gps.GPSTime * 1.0e-6 self.timebase = t - self.px4_timebase
adjust time base from GPS message
def gps_message_arrived(self, m): '''adjust time base from GPS message''' # msec-style GPS message? gps_week = getattr(m, 'Week', None) gps_timems = getattr(m, 'TimeMS', None) if gps_week is None: # usec-style GPS message? gps_week = getattr(m, 'GWk', None) gps_timems = getattr(m, 'GMS', None) if gps_week is None: if getattr(m, 'GPSTime', None) is not None: # PX4-style timestamp; we've only been called # because we were speculatively created in case no # better clock was found. return; t = self._gpsTimeToTime(gps_week, gps_timems) deltat = t - self.timebase if deltat <= 0: return for type in self.counts_since_gps: rate = self.counts_since_gps[type] / deltat if rate > self.msg_rate.get(type, 0): self.msg_rate[type] = rate self.msg_rate['IMU'] = 50.0 self.timebase = t self.counts_since_gps = {}
reset state on rewind
def _rewind(self): '''reset state on rewind''' self.messages = { 'MAV' : self } self.flightmode = "UNKNOWN" self.percent = 0 if self.clock: self.clock.rewind_event()
work out time basis for the log
def init_clock(self): '''work out time basis for the log''' self._rewind() # speculatively create a gps clock in case we don't find anything # better gps_clock = DFReaderClock_gps_interpolated() self.clock = gps_clock px4_msg_time = None px4_msg_gps = None gps_interp_msg_gps1 = None gps_interp_msg_gps2 = None first_us_stamp = None first_ms_stamp = None have_good_clock = False while True: m = self.recv_msg() if m is None: break; type = m.get_type() if first_us_stamp is None: first_us_stamp = getattr(m, "TimeUS", None); if first_ms_stamp is None and (type != 'GPS' and type != 'GPS2'): # Older GPS messages use TimeMS for msecs past start # of gps week first_ms_stamp = getattr(m, "TimeMS", None); if type == 'GPS' or type == 'GPS2': if getattr(m, "TimeUS", 0) != 0 and \ getattr(m, "GWk", 0) != 0: # everything-usec-timestamped self.init_clock_usec() if not self._zero_time_base: self.clock.find_time_base(m, first_us_stamp) have_good_clock = True break if getattr(m, "T", 0) != 0 and \ getattr(m, "Week", 0) != 0: # GPS is msec-timestamped if first_ms_stamp is None: first_ms_stamp = m.T self.init_clock_msec() if not self._zero_time_base: self.clock.find_time_base(m, first_ms_stamp) have_good_clock = True break if getattr(m, "GPSTime", 0) != 0: # px4-style-only px4_msg_gps = m if getattr(m, "Week", 0) != 0: if gps_interp_msg_gps1 is not None and \ (gps_interp_msg_gps1.TimeMS != m.TimeMS or \ gps_interp_msg_gps1.Week != m.Week): # we've received two distinct, non-zero GPS # packets without finding a decent clock to # use; fall back to interpolation. Q: should # we wait a few more messages befoe doing # this? self.init_clock_gps_interpolated(gps_clock) have_good_clock = True break gps_interp_msg_gps1 = m elif type == 'TIME': '''only px4-style logs use TIME''' if getattr(m, "StartTime", None) != None: px4_msg_time = m; if px4_msg_time is not None and px4_msg_gps is not None: self.init_clock_px4(px4_msg_time, px4_msg_gps) have_good_clock = True break # print("clock is " + str(self.clock)) if not have_good_clock: # we failed to find any GPS messages to set a time # base for usec and msec clocks. Also, not a # PX4-style log if first_us_stamp is not None: self.init_clock_usec() elif first_ms_stamp is not None: self.init_clock_msec() self._rewind() return
set time for a message
def _set_time(self, m): '''set time for a message''' # really just left here for profiling m._timestamp = self.timestamp if len(m._fieldnames) > 0 and self.clock is not None: self.clock.set_message_timestamp(m)
add a new message
def _add_msg(self, m): '''add a new message''' type = m.get_type() self.messages[type] = m if self.clock: self.clock.message_arrived(m) if type == 'MSG': if m.Message.find("Rover") != -1: self.mav_type = mavutil.mavlink.MAV_TYPE_GROUND_ROVER elif m.Message.find("Plane") != -1: self.mav_type = mavutil.mavlink.MAV_TYPE_FIXED_WING elif m.Message.find("Copter") != -1: self.mav_type = mavutil.mavlink.MAV_TYPE_QUADROTOR elif m.Message.startswith("Antenna"): self.mav_type = mavutil.mavlink.MAV_TYPE_ANTENNA_TRACKER if type == 'MODE': if isinstance(m.Mode, str): self.flightmode = m.Mode.upper() elif 'ModeNum' in m._fieldnames: mapping = mavutil.mode_mapping_bynumber(self.mav_type) if mapping is not None and m.ModeNum in mapping: self.flightmode = mapping[m.ModeNum] else: self.flightmode = mavutil.mode_string_acm(m.Mode) if type == 'STAT' and 'MainState' in m._fieldnames: self.flightmode = mavutil.mode_string_px4(m.MainState) if type == 'PARM' and getattr(m, 'Name', None) is not None: self.params[m.Name] = m.Value self._set_time(m)
recv the next message that matches the given condition type can be a string or a list of strings
def recv_match(self, condition=None, type=None, blocking=False): '''recv the next message that matches the given condition type can be a string or a list of strings''' if type is not None and not isinstance(type, list): type = [type] while True: m = self.recv_msg() if m is None: return None if type is not None and not m.get_type() in type: continue if not mavutil.evaluate_condition(condition, self.messages): continue return m
convenient function for returning an arbitrary MAVLink parameter with a default
def param(self, name, default=None): '''convenient function for returning an arbitrary MAVLink parameter with a default''' if not name in self.params: return default return self.params[name]
rewind to start of log
def _rewind(self): '''rewind to start of log''' DFReader._rewind(self) self.offset = 0 self.remaining = self.data_len
read one message, returning it as an object
def _parse_next(self): '''read one message, returning it as an object''' if self.data_len - self.offset < 3: return None hdr = self.data[self.offset:self.offset+3] skip_bytes = 0 skip_type = None # skip over bad messages while (ord(hdr[0]) != self.HEAD1 or ord(hdr[1]) != self.HEAD2 or ord(hdr[2]) not in self.formats): if skip_type is None: skip_type = (ord(hdr[0]), ord(hdr[1]), ord(hdr[2])) skip_start = self.offset skip_bytes += 1 self.offset += 1 if self.data_len - self.offset < 3: return None hdr = self.data[self.offset:self.offset+3] msg_type = ord(hdr[2]) if skip_bytes != 0: if self.remaining < 528: return None print("Skipped %u bad bytes in log at offset %u, type=%s" % (skip_bytes, skip_start, skip_type)) self.remaining -= skip_bytes self.offset += 3 self.remaining -= 3 if not msg_type in self.formats: if self.verbose: print("unknown message type %02x" % msg_type) raise Exception("Unknown message type %02x" % msg_type) fmt = self.formats[msg_type] if self.remaining < fmt.len-3: # out of data - can often happen half way through a message if self.verbose: print("out of data") return None body = self.data[self.offset:self.offset+(fmt.len-3)] elements = None try: elements = list(struct.unpack(fmt.msg_struct, body)) except Exception: if self.remaining < 528: # we can have garbage at the end of an APM2 log return None # we should also cope with other corruption; logs # transfered via DataFlash_MAVLink may have blocks of 0s # in them, for example print("Failed to parse %s/%s with len %u (remaining %u)" % (fmt.name, fmt.msg_struct, len(body), self.remaining)) if elements is None: return self._parse_next() name = null_term(fmt.name) if name == 'FMT': # add to formats # name, len, format, headings self.formats[elements[0]] = DFFormat(elements[0], null_term(elements[2]), elements[1], null_term(elements[3]), null_term(elements[4])) self.offset += fmt.len-3 self.remaining -= fmt.len-3 m = DFMessage(fmt, elements, True) self._add_msg(m) self.percent = 100.0 * (self.offset / float(self.data_len)) return m
rewind to start of log
def _rewind(self): '''rewind to start of log''' DFReader._rewind(self) self.line = 0 # find the first valid line while self.line < len(self.lines): if self.lines[self.line].startswith("FMT, "): break self.line += 1
read one message, returning it as an object
def _parse_next(self): '''read one message, returning it as an object''' this_line = self.line while self.line < len(self.lines): s = self.lines[self.line].rstrip() elements = s.split(", ") this_line = self.line # move to next line self.line += 1 if len(elements) >= 2: # this_line is good break if this_line >= len(self.lines): return None # cope with empty structures if len(elements) == 5 and elements[-1] == ',': elements[-1] = '' elements.append('') self.percent = 100.0 * (this_line / float(len(self.lines))) msg_type = elements[0] if not msg_type in self.formats: return self._parse_next() fmt = self.formats[msg_type] if len(elements) < len(fmt.format)+1: # not enough columns return self._parse_next() elements = elements[1:] name = fmt.name.rstrip('\0') if name == 'FMT': # add to formats # name, len, format, headings self.formats[elements[2]] = DFFormat(int(elements[0]), elements[2], int(elements[1]), elements[3], elements[4]) try: m = DFMessage(fmt, elements, False) except ValueError: return self._parse_next() self._add_msg(m) return m
Translates from JderobotTypes CMDVel to ROS Twist. @param vel: JderobotTypes CMDVel to translate @type img: JdeRobotTypes.CMDVel @return a Twist translated from vel
def cmdvel2PosTarget(vel): ''' Translates from JderobotTypes CMDVel to ROS Twist. @param vel: JderobotTypes CMDVel to translate @type img: JdeRobotTypes.CMDVel @return a Twist translated from vel ''' msg=PositionTarget( header=Header( stamp=rospy.Time.now(), frame_id=''), ) msg.coordinate_frame = 8 msg.type_mask = 1475 msg.position.x = vel.px msg.position.y = vel.py msg.position.z = vel.pz msg.velocity.x = vel.vx msg.velocity.y = vel.vy msg.velocity.z = vel.vz msg.acceleration_or_force.x = vel.ax msg.acceleration_or_force.y = vel.ay msg.acceleration_or_force.z = vel.az msg.yaw = vel.yaw msg.yaw_rate = vel.yaw_rate return msg
Function to publish cmdvel.
def publish (self): ''' Function to publish cmdvel. ''' #print(self) #self.using_event.wait() self.lock.acquire() msg = cmdvel2PosTarget(self.vel) self.lock.release() self.pub.publish(msg)
Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel
def sendCMD (self, vel): ''' Sends CMDVel. @param vel: CMDVel to publish @type vel: CMDVel ''' self.lock.acquire() self.vel = vel self.lock.release()
work out signal loss times for a log file
def mavloss(logfile): '''work out signal loss times for a log file''' print("Processing log %s" % filename) mlog = mavutil.mavlink_connection(filename, planner_format=args.planner, notimestamps=args.notimestamps, dialect=args.dialect, robust_parsing=args.robust) # Track the reasons for MAVLink parsing errors and print them all out at the end. reason_ids = set() reasons = [] while True: m = mlog.recv_match(condition=args.condition) # Stop parsing the file once we've reached the end if m is None: break # Save the parsing failure reason for this message if it's a new one if m.get_type() == 'BAD_DATA': reason_id = ''.join(m.reason.split(' ')[0:3]) if reason_id not in reason_ids: reason_ids.add(reason_id) reasons.append(m.reason) # Print out the final packet loss results print("%u packets, %u lost %.1f%%" % ( mlog.mav_count, mlog.mav_loss, mlog.packet_loss())) # Also print out the reasons why losses occurred if len(reasons) > 0: print("Packet loss at least partially attributed to the following:") for r in reasons: print(" * " + r)
Sensor and DSC control loads. sensLoad : Sensor DSC Load (uint8_t) ctrlLoad : Control DSC Load (uint8_t) batVolt : Battery Voltage in millivolts (uint16_t)
def cpu_load_send(self, sensLoad, ctrlLoad, batVolt, force_mavlink1=False): ''' Sensor and DSC control loads. sensLoad : Sensor DSC Load (uint8_t) ctrlLoad : Control DSC Load (uint8_t) batVolt : Battery Voltage in millivolts (uint16_t) ''' return self.send(self.cpu_load_encode(sensLoad, ctrlLoad, batVolt), force_mavlink1=force_mavlink1)
Accelerometer and gyro biases. axBias : Accelerometer X bias (m/s) (float) ayBias : Accelerometer Y bias (m/s) (float) azBias : Accelerometer Z bias (m/s) (float) gxBias : Gyro X bias (rad/s) (float) gyBias : Gyro Y bias (rad/s) (float) gzBias : Gyro Z bias (rad/s) (float)
def sensor_bias_encode(self, axBias, ayBias, azBias, gxBias, gyBias, gzBias): ''' Accelerometer and gyro biases. axBias : Accelerometer X bias (m/s) (float) ayBias : Accelerometer Y bias (m/s) (float) azBias : Accelerometer Z bias (m/s) (float) gxBias : Gyro X bias (rad/s) (float) gyBias : Gyro Y bias (rad/s) (float) gzBias : Gyro Z bias (rad/s) (float) ''' return MAVLink_sensor_bias_message(axBias, ayBias, azBias, gxBias, gyBias, gzBias)
Accelerometer and gyro biases. axBias : Accelerometer X bias (m/s) (float) ayBias : Accelerometer Y bias (m/s) (float) azBias : Accelerometer Z bias (m/s) (float) gxBias : Gyro X bias (rad/s) (float) gyBias : Gyro Y bias (rad/s) (float) gzBias : Gyro Z bias (rad/s) (float)
def sensor_bias_send(self, axBias, ayBias, azBias, gxBias, gyBias, gzBias, force_mavlink1=False): ''' Accelerometer and gyro biases. axBias : Accelerometer X bias (m/s) (float) ayBias : Accelerometer Y bias (m/s) (float) azBias : Accelerometer Z bias (m/s) (float) gxBias : Gyro X bias (rad/s) (float) gyBias : Gyro Y bias (rad/s) (float) gzBias : Gyro Z bias (rad/s) (float) ''' return self.send(self.sensor_bias_encode(axBias, ayBias, azBias, gxBias, gyBias, gzBias), force_mavlink1=force_mavlink1)
Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t)
def diagnostic_encode(self, diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3): ''' Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t) ''' return MAVLink_diagnostic_message(diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3)
Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t)
def diagnostic_send(self, diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3, force_mavlink1=False): ''' Configurable diagnostic messages. diagFl1 : Diagnostic float 1 (float) diagFl2 : Diagnostic float 2 (float) diagFl3 : Diagnostic float 3 (float) diagSh1 : Diagnostic short 1 (int16_t) diagSh2 : Diagnostic short 2 (int16_t) diagSh3 : Diagnostic short 3 (int16_t) ''' return self.send(self.diagnostic_encode(diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3), force_mavlink1=force_mavlink1)
Data used in the navigation algorithm. u_m : Measured Airspeed prior to the nav filter in m/s (float) phi_c : Commanded Roll (float) theta_c : Commanded Pitch (float) psiDot_c : Commanded Turn rate (float) ay_body : Y component of the body acceleration (float) totalDist : Total Distance to Run on this leg of Navigation (float) dist2Go : Remaining distance to Run on this leg of Navigation (float) fromWP : Origin WP (uint8_t) toWP : Destination WP (uint8_t) h_c : Commanded altitude in 0.1 m (uint16_t)
def slugs_navigation_encode(self, u_m, phi_c, theta_c, psiDot_c, ay_body, totalDist, dist2Go, fromWP, toWP, h_c): ''' Data used in the navigation algorithm. u_m : Measured Airspeed prior to the nav filter in m/s (float) phi_c : Commanded Roll (float) theta_c : Commanded Pitch (float) psiDot_c : Commanded Turn rate (float) ay_body : Y component of the body acceleration (float) totalDist : Total Distance to Run on this leg of Navigation (float) dist2Go : Remaining distance to Run on this leg of Navigation (float) fromWP : Origin WP (uint8_t) toWP : Destination WP (uint8_t) h_c : Commanded altitude in 0.1 m (uint16_t) ''' return MAVLink_slugs_navigation_message(u_m, phi_c, theta_c, psiDot_c, ay_body, totalDist, dist2Go, fromWP, toWP, h_c)
Data used in the navigation algorithm. u_m : Measured Airspeed prior to the nav filter in m/s (float) phi_c : Commanded Roll (float) theta_c : Commanded Pitch (float) psiDot_c : Commanded Turn rate (float) ay_body : Y component of the body acceleration (float) totalDist : Total Distance to Run on this leg of Navigation (float) dist2Go : Remaining distance to Run on this leg of Navigation (float) fromWP : Origin WP (uint8_t) toWP : Destination WP (uint8_t) h_c : Commanded altitude in 0.1 m (uint16_t)
def slugs_navigation_send(self, u_m, phi_c, theta_c, psiDot_c, ay_body, totalDist, dist2Go, fromWP, toWP, h_c, force_mavlink1=False): ''' Data used in the navigation algorithm. u_m : Measured Airspeed prior to the nav filter in m/s (float) phi_c : Commanded Roll (float) theta_c : Commanded Pitch (float) psiDot_c : Commanded Turn rate (float) ay_body : Y component of the body acceleration (float) totalDist : Total Distance to Run on this leg of Navigation (float) dist2Go : Remaining distance to Run on this leg of Navigation (float) fromWP : Origin WP (uint8_t) toWP : Destination WP (uint8_t) h_c : Commanded altitude in 0.1 m (uint16_t) ''' return self.send(self.slugs_navigation_encode(u_m, phi_c, theta_c, psiDot_c, ay_body, totalDist, dist2Go, fromWP, toWP, h_c), force_mavlink1=force_mavlink1)
Configurable data log probes to be used inside Simulink fl_1 : Log value 1 (float) fl_2 : Log value 2 (float) fl_3 : Log value 3 (float) fl_4 : Log value 4 (float) fl_5 : Log value 5 (float) fl_6 : Log value 6 (float)
def data_log_encode(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6): ''' Configurable data log probes to be used inside Simulink fl_1 : Log value 1 (float) fl_2 : Log value 2 (float) fl_3 : Log value 3 (float) fl_4 : Log value 4 (float) fl_5 : Log value 5 (float) fl_6 : Log value 6 (float) ''' return MAVLink_data_log_message(fl_1, fl_2, fl_3, fl_4, fl_5, fl_6)
Configurable data log probes to be used inside Simulink fl_1 : Log value 1 (float) fl_2 : Log value 2 (float) fl_3 : Log value 3 (float) fl_4 : Log value 4 (float) fl_5 : Log value 5 (float) fl_6 : Log value 6 (float)
def data_log_send(self, fl_1, fl_2, fl_3, fl_4, fl_5, fl_6, force_mavlink1=False): ''' Configurable data log probes to be used inside Simulink fl_1 : Log value 1 (float) fl_2 : Log value 2 (float) fl_3 : Log value 3 (float) fl_4 : Log value 4 (float) fl_5 : Log value 5 (float) fl_6 : Log value 6 (float) ''' return self.send(self.data_log_encode(fl_1, fl_2, fl_3, fl_4, fl_5, fl_6), force_mavlink1=force_mavlink1)
Pilot console PWM messges. year : Year reported by Gps (uint8_t) month : Month reported by Gps (uint8_t) day : Day reported by Gps (uint8_t) hour : Hour reported by Gps (uint8_t) min : Min reported by Gps (uint8_t) sec : Sec reported by Gps (uint8_t) clockStat : Clock Status. See table 47 page 211 OEMStar Manual (uint8_t) visSat : Visible satellites reported by Gps (uint8_t) useSat : Used satellites in Solution (uint8_t) GppGl : GPS+GLONASS satellites in Solution (uint8_t) sigUsedMask : GPS and GLONASS usage mask (bit 0 GPS_used? bit_4 GLONASS_used?) (uint8_t) percentUsed : Percent used GPS (uint8_t)
def gps_date_time_encode(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed): ''' Pilot console PWM messges. year : Year reported by Gps (uint8_t) month : Month reported by Gps (uint8_t) day : Day reported by Gps (uint8_t) hour : Hour reported by Gps (uint8_t) min : Min reported by Gps (uint8_t) sec : Sec reported by Gps (uint8_t) clockStat : Clock Status. See table 47 page 211 OEMStar Manual (uint8_t) visSat : Visible satellites reported by Gps (uint8_t) useSat : Used satellites in Solution (uint8_t) GppGl : GPS+GLONASS satellites in Solution (uint8_t) sigUsedMask : GPS and GLONASS usage mask (bit 0 GPS_used? bit_4 GLONASS_used?) (uint8_t) percentUsed : Percent used GPS (uint8_t) ''' return MAVLink_gps_date_time_message(year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed)
Pilot console PWM messges. year : Year reported by Gps (uint8_t) month : Month reported by Gps (uint8_t) day : Day reported by Gps (uint8_t) hour : Hour reported by Gps (uint8_t) min : Min reported by Gps (uint8_t) sec : Sec reported by Gps (uint8_t) clockStat : Clock Status. See table 47 page 211 OEMStar Manual (uint8_t) visSat : Visible satellites reported by Gps (uint8_t) useSat : Used satellites in Solution (uint8_t) GppGl : GPS+GLONASS satellites in Solution (uint8_t) sigUsedMask : GPS and GLONASS usage mask (bit 0 GPS_used? bit_4 GLONASS_used?) (uint8_t) percentUsed : Percent used GPS (uint8_t)
def gps_date_time_send(self, year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed, force_mavlink1=False): ''' Pilot console PWM messges. year : Year reported by Gps (uint8_t) month : Month reported by Gps (uint8_t) day : Day reported by Gps (uint8_t) hour : Hour reported by Gps (uint8_t) min : Min reported by Gps (uint8_t) sec : Sec reported by Gps (uint8_t) clockStat : Clock Status. See table 47 page 211 OEMStar Manual (uint8_t) visSat : Visible satellites reported by Gps (uint8_t) useSat : Used satellites in Solution (uint8_t) GppGl : GPS+GLONASS satellites in Solution (uint8_t) sigUsedMask : GPS and GLONASS usage mask (bit 0 GPS_used? bit_4 GLONASS_used?) (uint8_t) percentUsed : Percent used GPS (uint8_t) ''' return self.send(self.gps_date_time_encode(year, month, day, hour, min, sec, clockStat, visSat, useSat, GppGl, sigUsedMask, percentUsed), force_mavlink1=force_mavlink1)
Mid Level commands sent from the GS to the autopilot. These are only sent when being operated in mid-level commands mode from the ground. target : The system setting the commands (uint8_t) hCommand : Commanded Altitude in meters (float) uCommand : Commanded Airspeed in m/s (float) rCommand : Commanded Turnrate in rad/s (float)
def mid_lvl_cmds_encode(self, target, hCommand, uCommand, rCommand): ''' Mid Level commands sent from the GS to the autopilot. These are only sent when being operated in mid-level commands mode from the ground. target : The system setting the commands (uint8_t) hCommand : Commanded Altitude in meters (float) uCommand : Commanded Airspeed in m/s (float) rCommand : Commanded Turnrate in rad/s (float) ''' return MAVLink_mid_lvl_cmds_message(target, hCommand, uCommand, rCommand)
Mid Level commands sent from the GS to the autopilot. These are only sent when being operated in mid-level commands mode from the ground. target : The system setting the commands (uint8_t) hCommand : Commanded Altitude in meters (float) uCommand : Commanded Airspeed in m/s (float) rCommand : Commanded Turnrate in rad/s (float)
def mid_lvl_cmds_send(self, target, hCommand, uCommand, rCommand, force_mavlink1=False): ''' Mid Level commands sent from the GS to the autopilot. These are only sent when being operated in mid-level commands mode from the ground. target : The system setting the commands (uint8_t) hCommand : Commanded Altitude in meters (float) uCommand : Commanded Airspeed in m/s (float) rCommand : Commanded Turnrate in rad/s (float) ''' return self.send(self.mid_lvl_cmds_encode(target, hCommand, uCommand, rCommand), force_mavlink1=force_mavlink1)
This message sets the control surfaces for selective passthrough mode. target : The system setting the commands (uint8_t) bitfieldPt : Bitfield containing the passthrough configuration, see CONTROL_SURFACE_FLAG ENUM. (uint16_t)
def ctrl_srfc_pt_send(self, target, bitfieldPt, force_mavlink1=False): ''' This message sets the control surfaces for selective passthrough mode. target : The system setting the commands (uint8_t) bitfieldPt : Bitfield containing the passthrough configuration, see CONTROL_SURFACE_FLAG ENUM. (uint16_t) ''' return self.send(self.ctrl_srfc_pt_encode(target, bitfieldPt), force_mavlink1=force_mavlink1)
Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount to pan: -1 left, 0 No pan motion, +1 right (int8_t) tilt : Order the mount to tilt: -1 down, 0 No tilt motion, +1 up (int8_t) zoom : Order the zoom values 0 to 10 (int8_t) moveHome : Orders the camera mount to move home. The other fields are ignored when this field is set. 1: move home, 0 ignored (int8_t)
def slugs_camera_order_encode(self, target, pan, tilt, zoom, moveHome): ''' Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount to pan: -1 left, 0 No pan motion, +1 right (int8_t) tilt : Order the mount to tilt: -1 down, 0 No tilt motion, +1 up (int8_t) zoom : Order the zoom values 0 to 10 (int8_t) moveHome : Orders the camera mount to move home. The other fields are ignored when this field is set. 1: move home, 0 ignored (int8_t) ''' return MAVLink_slugs_camera_order_message(target, pan, tilt, zoom, moveHome)
Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount to pan: -1 left, 0 No pan motion, +1 right (int8_t) tilt : Order the mount to tilt: -1 down, 0 No tilt motion, +1 up (int8_t) zoom : Order the zoom values 0 to 10 (int8_t) moveHome : Orders the camera mount to move home. The other fields are ignored when this field is set. 1: move home, 0 ignored (int8_t)
def slugs_camera_order_send(self, target, pan, tilt, zoom, moveHome, force_mavlink1=False): ''' Orders generated to the SLUGS camera mount. target : The system reporting the action (uint8_t) pan : Order the mount to pan: -1 left, 0 No pan motion, +1 right (int8_t) tilt : Order the mount to tilt: -1 down, 0 No tilt motion, +1 up (int8_t) zoom : Order the zoom values 0 to 10 (int8_t) moveHome : Orders the camera mount to move home. The other fields are ignored when this field is set. 1: move home, 0 ignored (int8_t) ''' return self.send(self.slugs_camera_order_encode(target, pan, tilt, zoom, moveHome), force_mavlink1=force_mavlink1)
Control for surface; pending and order to origin. target : The system setting the commands (uint8_t) idSurface : ID control surface send 0: throttle 1: aileron 2: elevator 3: rudder (uint8_t) mControl : Pending (float) bControl : Order to origin (float)
def control_surface_encode(self, target, idSurface, mControl, bControl): ''' Control for surface; pending and order to origin. target : The system setting the commands (uint8_t) idSurface : ID control surface send 0: throttle 1: aileron 2: elevator 3: rudder (uint8_t) mControl : Pending (float) bControl : Order to origin (float) ''' return MAVLink_control_surface_message(target, idSurface, mControl, bControl)
Control for surface; pending and order to origin. target : The system setting the commands (uint8_t) idSurface : ID control surface send 0: throttle 1: aileron 2: elevator 3: rudder (uint8_t) mControl : Pending (float) bControl : Order to origin (float)
def control_surface_send(self, target, idSurface, mControl, bControl, force_mavlink1=False): ''' Control for surface; pending and order to origin. target : The system setting the commands (uint8_t) idSurface : ID control surface send 0: throttle 1: aileron 2: elevator 3: rudder (uint8_t) mControl : Pending (float) bControl : Order to origin (float) ''' return self.send(self.control_surface_encode(target, idSurface, mControl, bControl), force_mavlink1=force_mavlink1)
Transmits the last known position of the mobile GS to the UAV. Very relevant when Track Mobile is enabled target : The system reporting the action (uint8_t) latitude : Mobile Latitude (float) longitude : Mobile Longitude (float)
def slugs_mobile_location_send(self, target, latitude, longitude, force_mavlink1=False): ''' Transmits the last known position of the mobile GS to the UAV. Very relevant when Track Mobile is enabled target : The system reporting the action (uint8_t) latitude : Mobile Latitude (float) longitude : Mobile Longitude (float) ''' return self.send(self.slugs_mobile_location_encode(target, latitude, longitude), force_mavlink1=force_mavlink1)
Control for camara. target : The system setting the commands (uint8_t) idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR 4: backlight (uint8_t) order : 1: up/on 2: down/off 3: auto/reset/no action (uint8_t)
def slugs_configuration_camera_send(self, target, idOrder, order, force_mavlink1=False): ''' Control for camara. target : The system setting the commands (uint8_t) idOrder : ID 0: brightness 1: aperture 2: iris 3: ICR 4: backlight (uint8_t) order : 1: up/on 2: down/off 3: auto/reset/no action (uint8_t) ''' return self.send(self.slugs_configuration_camera_encode(target, idOrder, order), force_mavlink1=force_mavlink1)
Transmits the position of watch target : The system reporting the action (uint8_t) latitude : ISR Latitude (float) longitude : ISR Longitude (float) height : ISR Height (float) option1 : Option 1 (uint8_t) option2 : Option 2 (uint8_t) option3 : Option 3 (uint8_t)
def isr_location_encode(self, target, latitude, longitude, height, option1, option2, option3): ''' Transmits the position of watch target : The system reporting the action (uint8_t) latitude : ISR Latitude (float) longitude : ISR Longitude (float) height : ISR Height (float) option1 : Option 1 (uint8_t) option2 : Option 2 (uint8_t) option3 : Option 3 (uint8_t) ''' return MAVLink_isr_location_message(target, latitude, longitude, height, option1, option2, option3)
Transmits the position of watch target : The system reporting the action (uint8_t) latitude : ISR Latitude (float) longitude : ISR Longitude (float) height : ISR Height (float) option1 : Option 1 (uint8_t) option2 : Option 2 (uint8_t) option3 : Option 3 (uint8_t)
def isr_location_send(self, target, latitude, longitude, height, option1, option2, option3, force_mavlink1=False): ''' Transmits the position of watch target : The system reporting the action (uint8_t) latitude : ISR Latitude (float) longitude : ISR Longitude (float) height : ISR Height (float) option1 : Option 1 (uint8_t) option2 : Option 2 (uint8_t) option3 : Option 3 (uint8_t) ''' return self.send(self.isr_location_encode(target, latitude, longitude, height, option1, option2, option3), force_mavlink1=force_mavlink1)
Transmits the readings from the voltage and current sensors r2Type : It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM (uint8_t) voltage : Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V (uint16_t) reading2 : Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value (uint16_t)
def volt_sensor_send(self, r2Type, voltage, reading2, force_mavlink1=False): ''' Transmits the readings from the voltage and current sensors r2Type : It is the value of reading 2: 0 - Current, 1 - Foreward Sonar, 2 - Back Sonar, 3 - RPM (uint8_t) voltage : Voltage in uS of PWM. 0 uS = 0V, 20 uS = 21.5V (uint16_t) reading2 : Depends on the value of r2Type (0) Current consumption in uS of PWM, 20 uS = 90Amp (1) Distance in cm (2) Distance in cm (3) Absolute value (uint16_t) ''' return self.send(self.volt_sensor_encode(r2Type, voltage, reading2), force_mavlink1=force_mavlink1)
Transmits the actual Pan, Tilt and Zoom values of the camera unit zoom : The actual Zoom Value (uint8_t) pan : The Pan value in 10ths of degree (int16_t) tilt : The Tilt value in 10ths of degree (int16_t)
def ptz_status_send(self, zoom, pan, tilt, force_mavlink1=False): ''' Transmits the actual Pan, Tilt and Zoom values of the camera unit zoom : The actual Zoom Value (uint8_t) pan : The Pan value in 10ths of degree (int16_t) tilt : The Tilt value in 10ths of degree (int16_t) ''' return self.send(self.ptz_status_encode(zoom, pan, tilt), force_mavlink1=force_mavlink1)
Transmits the actual status values UAV in flight target : The ID system reporting the action (uint8_t) latitude : Latitude UAV (float) longitude : Longitude UAV (float) altitude : Altitude UAV (float) speed : Speed UAV (float) course : Course UAV (float)
def uav_status_encode(self, target, latitude, longitude, altitude, speed, course): ''' Transmits the actual status values UAV in flight target : The ID system reporting the action (uint8_t) latitude : Latitude UAV (float) longitude : Longitude UAV (float) altitude : Altitude UAV (float) speed : Speed UAV (float) course : Course UAV (float) ''' return MAVLink_uav_status_message(target, latitude, longitude, altitude, speed, course)
Transmits the actual status values UAV in flight target : The ID system reporting the action (uint8_t) latitude : Latitude UAV (float) longitude : Longitude UAV (float) altitude : Altitude UAV (float) speed : Speed UAV (float) course : Course UAV (float)
def uav_status_send(self, target, latitude, longitude, altitude, speed, course, force_mavlink1=False): ''' Transmits the actual status values UAV in flight target : The ID system reporting the action (uint8_t) latitude : Latitude UAV (float) longitude : Longitude UAV (float) altitude : Altitude UAV (float) speed : Speed UAV (float) course : Course UAV (float) ''' return self.send(self.uav_status_encode(target, latitude, longitude, altitude, speed, course), force_mavlink1=force_mavlink1)
This contains the status of the GPS readings csFails : Number of times checksum has failed (uint16_t) gpsQuality : The quality indicator, 0=fix not available or invalid, 1=GPS fix, 2=C/A differential GPS, 6=Dead reckoning mode, 7=Manual input mode (fixed position), 8=Simulator mode, 9= WAAS a (uint8_t) msgsType : Indicates if GN, GL or GP messages are being received (uint8_t) posStatus : A = data valid, V = data invalid (uint8_t) magVar : Magnetic variation, degrees (float) magDir : Magnetic variation direction E/W. Easterly variation (E) subtracts from True course and Westerly variation (W) adds to True course (int8_t) modeInd : Positioning system mode indicator. A - Autonomous;D-Differential; E-Estimated (dead reckoning) mode;M-Manual input; N-Data not valid (uint8_t)
def status_gps_encode(self, csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd): ''' This contains the status of the GPS readings csFails : Number of times checksum has failed (uint16_t) gpsQuality : The quality indicator, 0=fix not available or invalid, 1=GPS fix, 2=C/A differential GPS, 6=Dead reckoning mode, 7=Manual input mode (fixed position), 8=Simulator mode, 9= WAAS a (uint8_t) msgsType : Indicates if GN, GL or GP messages are being received (uint8_t) posStatus : A = data valid, V = data invalid (uint8_t) magVar : Magnetic variation, degrees (float) magDir : Magnetic variation direction E/W. Easterly variation (E) subtracts from True course and Westerly variation (W) adds to True course (int8_t) modeInd : Positioning system mode indicator. A - Autonomous;D-Differential; E-Estimated (dead reckoning) mode;M-Manual input; N-Data not valid (uint8_t) ''' return MAVLink_status_gps_message(csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd)
This contains the status of the GPS readings csFails : Number of times checksum has failed (uint16_t) gpsQuality : The quality indicator, 0=fix not available or invalid, 1=GPS fix, 2=C/A differential GPS, 6=Dead reckoning mode, 7=Manual input mode (fixed position), 8=Simulator mode, 9= WAAS a (uint8_t) msgsType : Indicates if GN, GL or GP messages are being received (uint8_t) posStatus : A = data valid, V = data invalid (uint8_t) magVar : Magnetic variation, degrees (float) magDir : Magnetic variation direction E/W. Easterly variation (E) subtracts from True course and Westerly variation (W) adds to True course (int8_t) modeInd : Positioning system mode indicator. A - Autonomous;D-Differential; E-Estimated (dead reckoning) mode;M-Manual input; N-Data not valid (uint8_t)
def status_gps_send(self, csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd, force_mavlink1=False): ''' This contains the status of the GPS readings csFails : Number of times checksum has failed (uint16_t) gpsQuality : The quality indicator, 0=fix not available or invalid, 1=GPS fix, 2=C/A differential GPS, 6=Dead reckoning mode, 7=Manual input mode (fixed position), 8=Simulator mode, 9= WAAS a (uint8_t) msgsType : Indicates if GN, GL or GP messages are being received (uint8_t) posStatus : A = data valid, V = data invalid (uint8_t) magVar : Magnetic variation, degrees (float) magDir : Magnetic variation direction E/W. Easterly variation (E) subtracts from True course and Westerly variation (W) adds to True course (int8_t) modeInd : Positioning system mode indicator. A - Autonomous;D-Differential; E-Estimated (dead reckoning) mode;M-Manual input; N-Data not valid (uint8_t) ''' return self.send(self.status_gps_encode(csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd), force_mavlink1=force_mavlink1)
Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus : solution Status. See table 44 page 197 (uint8_t) posType : position type. See table 43 page 196 (uint8_t) velType : velocity type. See table 43 page 196 (uint8_t) posSolAge : Age of the position solution in seconds (float) csFails : Times the CRC has failed since boot (uint16_t)
def novatel_diag_encode(self, timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails): ''' Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus : solution Status. See table 44 page 197 (uint8_t) posType : position type. See table 43 page 196 (uint8_t) velType : velocity type. See table 43 page 196 (uint8_t) posSolAge : Age of the position solution in seconds (float) csFails : Times the CRC has failed since boot (uint16_t) ''' return MAVLink_novatel_diag_message(timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails)
Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus : solution Status. See table 44 page 197 (uint8_t) posType : position type. See table 43 page 196 (uint8_t) velType : velocity type. See table 43 page 196 (uint8_t) posSolAge : Age of the position solution in seconds (float) csFails : Times the CRC has failed since boot (uint16_t)
def novatel_diag_send(self, timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails, force_mavlink1=False): ''' Transmits the diagnostics data from the Novatel OEMStar GPS timeStatus : The Time Status. See Table 8 page 27 Novatel OEMStar Manual (uint8_t) receiverStatus : Status Bitfield. See table 69 page 350 Novatel OEMstar Manual (uint32_t) solStatus : solution Status. See table 44 page 197 (uint8_t) posType : position type. See table 43 page 196 (uint8_t) velType : velocity type. See table 43 page 196 (uint8_t) posSolAge : Age of the position solution in seconds (float) csFails : Times the CRC has failed since boot (uint16_t) ''' return self.send(self.novatel_diag_encode(timeStatus, receiverStatus, solStatus, posType, velType, posSolAge, csFails), force_mavlink1=force_mavlink1)
Diagnostic data Sensor MCU float1 : Float field 1 (float) float2 : Float field 2 (float) int1 : Int 16 field 1 (int16_t) char1 : Int 8 field 1 (int8_t)
def sensor_diag_encode(self, float1, float2, int1, char1): ''' Diagnostic data Sensor MCU float1 : Float field 1 (float) float2 : Float field 2 (float) int1 : Int 16 field 1 (int16_t) char1 : Int 8 field 1 (int8_t) ''' return MAVLink_sensor_diag_message(float1, float2, int1, char1)
Diagnostic data Sensor MCU float1 : Float field 1 (float) float2 : Float field 2 (float) int1 : Int 16 field 1 (int16_t) char1 : Int 8 field 1 (int8_t)
def sensor_diag_send(self, float1, float2, int1, char1, force_mavlink1=False): ''' Diagnostic data Sensor MCU float1 : Float field 1 (float) float2 : Float field 2 (float) int1 : Int 16 field 1 (int16_t) char1 : Int 8 field 1 (int8_t) ''' return self.send(self.sensor_diag_encode(float1, float2, int1, char1), force_mavlink1=force_mavlink1)
The boot message indicates that a system is starting. The onboard software version allows to keep track of onboard soft/firmware revisions. This message allows the sensor and control MCUs to communicate version numbers on startup. version : The onboard software version (uint32_t)
def boot_send(self, version, force_mavlink1=False): ''' The boot message indicates that a system is starting. The onboard software version allows to keep track of onboard soft/firmware revisions. This message allows the sensor and control MCUs to communicate version numbers on startup. version : The onboard software version (uint32_t) ''' return self.send(self.boot_encode(version), force_mavlink1=force_mavlink1)
Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) name : The name of the mission script, NULL terminated. (char)
def script_item_encode(self, target_system, target_component, seq, name): ''' Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) name : The name of the mission script, NULL terminated. (char) ''' return MAVLink_script_item_message(target_system, target_component, seq, name)
Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) name : The name of the mission script, NULL terminated. (char)
def script_item_send(self, target_system, target_component, seq, name, force_mavlink1=False): ''' Message encoding a mission script item. This message is emitted upon a request for the next script item. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) name : The name of the mission script, NULL terminated. (char) ''' return self.send(self.script_item_encode(target_system, target_component, seq, name), force_mavlink1=force_mavlink1)
Request script item with the sequence number seq. The response of the system to this message should be a SCRIPT_ITEM message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t)
def script_request_send(self, target_system, target_component, seq, force_mavlink1=False): ''' Request script item with the sequence number seq. The response of the system to this message should be a SCRIPT_ITEM message. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) seq : Sequence (uint16_t) ''' return self.send(self.script_request_encode(target_system, target_component, seq), force_mavlink1=force_mavlink1)
Request the overall list of mission items from the system/component. target_system : System ID (uint8_t) target_component : Component ID (uint8_t)
def script_request_list_send(self, target_system, target_component, force_mavlink1=False): ''' Request the overall list of mission items from the system/component. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.script_request_list_encode(target_system, target_component), force_mavlink1=force_mavlink1)
This message is emitted as response to SCRIPT_REQUEST_LIST by the MAV to get the number of mission scripts. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) count : Number of script items in the sequence (uint16_t)
def script_count_send(self, target_system, target_component, count, force_mavlink1=False): ''' This message is emitted as response to SCRIPT_REQUEST_LIST by the MAV to get the number of mission scripts. target_system : System ID (uint8_t) target_component : Component ID (uint8_t) count : Number of script items in the sequence (uint16_t) ''' return self.send(self.script_count_encode(target_system, target_component, count), force_mavlink1=force_mavlink1)
This message informs about the currently active SCRIPT. seq : Active Sequence (uint16_t)
def script_current_send(self, seq, force_mavlink1=False): ''' This message informs about the currently active SCRIPT. seq : Active Sequence (uint16_t) ''' return self.send(self.script_current_encode(seq), force_mavlink1=force_mavlink1)
generate version.h
def generate_version_h(directory, xml): '''generate version.h''' f = open(os.path.join(directory, "version.h"), mode='w') t.write(f,''' /** @file * @brief MAVLink comm protocol built from ${basename}.xml * @see http://mavlink.org */ #pragma once #ifndef MAVLINK_VERSION_H #define MAVLINK_VERSION_H #define MAVLINK_BUILD_DATE "${parse_time}" #define MAVLINK_WIRE_PROTOCOL_VERSION "${wire_protocol_version}" #define MAVLINK_MAX_DIALECT_PAYLOAD_SIZE ${largest_payload} #endif // MAVLINK_VERSION_H ''', xml) f.close()
generate main header per XML file
def generate_main_h(directory, xml): '''generate main header per XML file''' f = open(os.path.join(directory, xml.basename + ".h"), mode='w') t.write(f, ''' /** @file * @brief MAVLink comm protocol generated from ${basename}.xml * @see http://mavlink.org */ #pragma once #ifndef MAVLINK_${basename_upper}_H #define MAVLINK_${basename_upper}_H #ifndef MAVLINK_H #error Wrong include order: MAVLINK_${basename_upper}.H MUST NOT BE DIRECTLY USED. Include mavlink.h from the same directory instead or set ALL AND EVERY defines from MAVLINK.H manually accordingly, including the #define MAVLINK_H call. #endif #undef MAVLINK_THIS_XML_IDX #define MAVLINK_THIS_XML_IDX ${xml_idx} #ifdef __cplusplus extern "C" { #endif // MESSAGE LENGTHS AND CRCS #ifndef MAVLINK_MESSAGE_LENGTHS #define MAVLINK_MESSAGE_LENGTHS {${message_lengths_array}} #endif #ifndef MAVLINK_MESSAGE_CRCS #define MAVLINK_MESSAGE_CRCS {${message_crcs_array}} #endif #include "../protocol.h" #define MAVLINK_ENABLED_${basename_upper} // ENUM DEFINITIONS ${{enum: /** @brief ${description} */ #ifndef HAVE_ENUM_${name} #define HAVE_ENUM_${name} typedef enum ${name} { ${{entry: ${name}=${value}, /* ${description} |${{param:${description}| }} */ }} } ${name}; #endif }} // MAVLINK VERSION #ifndef MAVLINK_VERSION #define MAVLINK_VERSION ${version} #endif #if (MAVLINK_VERSION == 0) #undef MAVLINK_VERSION #define MAVLINK_VERSION ${version} #endif // MESSAGE DEFINITIONS ${{message:#include "./mavlink_msg_${name_lower}.h" }} // base include ${{include_list:#include "../${base}/${base}.h" }} #undef MAVLINK_THIS_XML_IDX #define MAVLINK_THIS_XML_IDX ${xml_idx} #if MAVLINK_THIS_XML_IDX == MAVLINK_PRIMARY_XML_IDX # define MAVLINK_MESSAGE_INFO {${message_info_array}} # if MAVLINK_COMMAND_24BIT # include "../mavlink_get_info.h" # endif #endif #ifdef __cplusplus } #endif // __cplusplus #endif // MAVLINK_${basename_upper}_H ''', xml) f.close()
generate per-message header for a XML file
def generate_message_h(directory, m): '''generate per-message header for a XML file''' f = open(os.path.join(directory, 'mavlink_msg_%s.h' % m.name_lower), mode='w') t.write(f, ''' #pragma once // MESSAGE ${name} PACKING #define MAVLINK_MSG_ID_${name} ${id} MAVPACKED( typedef struct __mavlink_${name_lower}_t { ${{ordered_fields: ${type} ${name}${array_suffix}; /*< ${description}*/ }} }) mavlink_${name_lower}_t; #define MAVLINK_MSG_ID_${name}_LEN ${wire_length} #define MAVLINK_MSG_ID_${name}_MIN_LEN ${wire_min_length} #define MAVLINK_MSG_ID_${id}_LEN ${wire_length} #define MAVLINK_MSG_ID_${id}_MIN_LEN ${wire_min_length} #define MAVLINK_MSG_ID_${name}_CRC ${crc_extra} #define MAVLINK_MSG_ID_${id}_CRC ${crc_extra} ${{array_fields:#define MAVLINK_MSG_${msg_name}_FIELD_${name_upper}_LEN ${array_length} }} #if MAVLINK_COMMAND_24BIT #define MAVLINK_MESSAGE_INFO_${name} { \\ ${id}, \\ "${name}", \\ ${num_fields}, \\ { ${{ordered_fields: { "${name}", ${c_print_format}, MAVLINK_TYPE_${type_upper}, ${array_length}, ${wire_offset}, offsetof(mavlink_${name_lower}_t, ${name}) }, \\ }} } \\ } #else #define MAVLINK_MESSAGE_INFO_${name} { \\ "${name}", \\ ${num_fields}, \\ { ${{ordered_fields: { "${name}", ${c_print_format}, MAVLINK_TYPE_${type_upper}, ${array_length}, ${wire_offset}, offsetof(mavlink_${name_lower}_t, ${name}) }, \\ }} } \\ } #endif /** * @brief Pack a ${name_lower} message * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * ${{arg_fields: * @param ${name} ${description} }} * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_${name_lower}_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, ${{arg_fields: ${array_const}${type} ${array_prefix}${name},}}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_${name}_LEN]; ${{scalar_fields: _mav_put_${type}(buf, ${wire_offset}, ${putname}); }} ${{array_fields: _mav_put_${type}_array(buf, ${wire_offset}, ${name}, ${array_length}); }} memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_${name}_LEN); #else mavlink_${name_lower}_t packet; ${{scalar_fields: packet.${name} = ${putname}; }} ${{array_fields: mav_array_memcpy(packet.${name}, ${name}, sizeof(${type})*${array_length}); }} memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_${name}_LEN); #endif msg->msgid = MAVLINK_MSG_ID_${name}; return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); } /** * @brief Pack a ${name_lower} message on a channel * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into ${{arg_fields: * @param ${name} ${description} }} * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_${name_lower}_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, ${{arg_fields:${array_const}${type} ${array_prefix}${name},}}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_${name}_LEN]; ${{scalar_fields: _mav_put_${type}(buf, ${wire_offset}, ${putname}); }} ${{array_fields: _mav_put_${type}_array(buf, ${wire_offset}, ${name}, ${array_length}); }} memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_${name}_LEN); #else mavlink_${name_lower}_t packet; ${{scalar_fields: packet.${name} = ${putname}; }} ${{array_fields: mav_array_memcpy(packet.${name}, ${name}, sizeof(${type})*${array_length}); }} memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_${name}_LEN); #endif msg->msgid = MAVLINK_MSG_ID_${name}; return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); } /** * @brief Encode a ${name_lower} struct * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * @param ${name_lower} C-struct to read the message contents from */ static inline uint16_t mavlink_msg_${name_lower}_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_${name_lower}_t* ${name_lower}) { return mavlink_msg_${name_lower}_pack(system_id, component_id, msg,${{arg_fields: ${name_lower}->${name},}}); } /** * @brief Encode a ${name_lower} struct on a channel * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into * @param ${name_lower} C-struct to read the message contents from */ static inline uint16_t mavlink_msg_${name_lower}_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_${name_lower}_t* ${name_lower}) { return mavlink_msg_${name_lower}_pack_chan(system_id, component_id, chan, msg,${{arg_fields: ${name_lower}->${name},}}); } /** * @brief Send a ${name_lower} message * @param chan MAVLink channel to send the message * ${{arg_fields: * @param ${name} ${description} }} */ #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS static inline void mavlink_msg_${name_lower}_send(mavlink_channel_t chan,${{arg_fields: ${array_const}${type} ${array_prefix}${name},}}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_${name}_LEN]; ${{scalar_fields: _mav_put_${type}(buf, ${wire_offset}, ${putname}); }} ${{array_fields: _mav_put_${type}_array(buf, ${wire_offset}, ${name}, ${array_length}); }} _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_${name}, buf, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); #else mavlink_${name_lower}_t packet; ${{scalar_fields: packet.${name} = ${putname}; }} ${{array_fields: mav_array_memcpy(packet.${name}, ${name}, sizeof(${type})*${array_length}); }} _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_${name}, (const char *)&packet, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); #endif } /** * @brief Send a ${name_lower} message * @param chan MAVLink channel to send the message * @param struct The MAVLink struct to serialize */ static inline void mavlink_msg_${name_lower}_send_struct(mavlink_channel_t chan, const mavlink_${name_lower}_t* ${name_lower}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS mavlink_msg_${name_lower}_send(chan,${{arg_fields: ${name_lower}->${name},}}); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_${name}, (const char *)${name_lower}, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); #endif } #if MAVLINK_MSG_ID_${name}_LEN <= MAVLINK_MAX_PAYLOAD_LEN /* This varient of _send() can be used to save stack space by re-using memory from the receive buffer. The caller provides a mavlink_message_t which is the size of a full mavlink message. This is usually the receive buffer for the channel, and allows a reply to an incoming message with minimum stack space usage. */ static inline void mavlink_msg_${name_lower}_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, ${{arg_fields: ${array_const}${type} ${array_prefix}${name},}}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char *buf = (char *)msgbuf; ${{scalar_fields: _mav_put_${type}(buf, ${wire_offset}, ${putname}); }} ${{array_fields: _mav_put_${type}_array(buf, ${wire_offset}, ${name}, ${array_length}); }} _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_${name}, buf, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); #else mavlink_${name_lower}_t *packet = (mavlink_${name_lower}_t *)msgbuf; ${{scalar_fields: packet->${name} = ${putname}; }} ${{array_fields: mav_array_memcpy(packet->${name}, ${name}, sizeof(${type})*${array_length}); }} _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_${name}, (const char *)packet, MAVLINK_MSG_ID_${name}_MIN_LEN, MAVLINK_MSG_ID_${name}_LEN, MAVLINK_MSG_ID_${name}_CRC); #endif } #endif #endif // MESSAGE ${name} UNPACKING ${{fields: /** * @brief Get field ${name} from ${name_lower} message * * @return ${description} */ static inline ${return_type} mavlink_msg_${name_lower}_get_${name}(const mavlink_message_t* msg${get_arg}) { return _MAV_RETURN_${type}${array_tag}(msg, ${array_return_arg} ${wire_offset}); } }} /** * @brief Decode a ${name_lower} message into a struct * * @param msg The message to decode * @param ${name_lower} C-struct to decode the message contents into */ static inline void mavlink_msg_${name_lower}_decode(const mavlink_message_t* msg, mavlink_${name_lower}_t* ${name_lower}) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS ${{ordered_fields: ${decode_left}mavlink_msg_${name_lower}_get_${name}(msg${decode_right}); }} #else uint8_t len = msg->len < MAVLINK_MSG_ID_${name}_LEN? msg->len : MAVLINK_MSG_ID_${name}_LEN; memset(${name_lower}, 0, MAVLINK_MSG_ID_${name}_LEN); memcpy(${name_lower}, _MAV_PAYLOAD(msg), len); #endif } ''', m) f.close()
copy the fixed protocol headers to the target directory
def copy_fixed_headers(directory, xml): '''copy the fixed protocol headers to the target directory''' import shutil, filecmp hlist = { "0.9": [ 'protocol.h', 'mavlink_helpers.h', 'mavlink_types.h', 'checksum.h' ], "1.0": [ 'protocol.h', 'mavlink_helpers.h', 'mavlink_types.h', 'checksum.h', 'mavlink_conversions.h' ], "2.0": [ 'protocol.h', 'mavlink_helpers.h', 'mavlink_types.h', 'checksum.h', 'mavlink_conversions.h', 'mavlink_get_info.h', 'mavlink_sha256.h' ] } basepath = os.path.dirname(os.path.realpath(__file__)) srcpath = os.path.join(basepath, 'C/include_v%s' % xml.wire_protocol_version) print("Copying fixed headers for protocol %s to %s" % (xml.wire_protocol_version, directory)) for h in hlist[xml.wire_protocol_version]: src = os.path.realpath(os.path.join(srcpath, h)) dest = os.path.realpath(os.path.join(directory, h)) if src == dest or (os.path.exists(dest) and filecmp.cmp(src, dest)): continue shutil.copy(src, dest)
generate headers for one XML file
def generate_one(basename, xml): '''generate headers for one XML file''' directory = os.path.join(basename, xml.basename) print("Generating C implementation in directory %s" % directory) mavparse.mkdir_p(directory) if xml.little_endian: xml.mavlink_endian = "MAVLINK_LITTLE_ENDIAN" else: xml.mavlink_endian = "MAVLINK_BIG_ENDIAN" if xml.crc_extra: xml.crc_extra_define = "1" else: xml.crc_extra_define = "0" if xml.command_24bit: xml.command_24bit_define = "1" else: xml.command_24bit_define = "0" if xml.sort_fields: xml.aligned_fields_define = "1" else: xml.aligned_fields_define = "0" # work out the included headers xml.include_list = [] for i in xml.include: base = i[:-4] xml.include_list.append(mav_include(base)) # form message lengths array xml.message_lengths_array = '' if not xml.command_24bit: for msgid in range(256): mlen = xml.message_min_lengths.get(msgid, 0) xml.message_lengths_array += '%u, ' % mlen xml.message_lengths_array = xml.message_lengths_array[:-2] # and message CRCs array xml.message_crcs_array = '' if xml.command_24bit: # we sort with primary key msgid for msgid in sorted(xml.message_crcs.keys()): xml.message_crcs_array += '{%u, %u, %u, %u, %u, %u}, ' % (msgid, xml.message_crcs[msgid], xml.message_min_lengths[msgid], xml.message_flags[msgid], xml.message_target_system_ofs[msgid], xml.message_target_component_ofs[msgid]) else: for msgid in range(256): crc = xml.message_crcs.get(msgid, 0) xml.message_crcs_array += '%u, ' % crc xml.message_crcs_array = xml.message_crcs_array[:-2] # form message info array xml.message_info_array = '' if xml.command_24bit: # we sort with primary key msgid for msgid in sorted(xml.message_names.keys()): name = xml.message_names[msgid] xml.message_info_array += 'MAVLINK_MESSAGE_INFO_%s, ' % name else: for msgid in range(256): name = xml.message_names.get(msgid, None) if name is not None: xml.message_info_array += 'MAVLINK_MESSAGE_INFO_%s, ' % name else: # Several C compilers don't accept {NULL} for # multi-dimensional arrays and structs # feed the compiler a "filled" empty message xml.message_info_array += '{"EMPTY",0,{{"","",MAVLINK_TYPE_CHAR,0,0,0}}}, ' xml.message_info_array = xml.message_info_array[:-2] # add some extra field attributes for convenience with arrays for m in xml.message: m.msg_name = m.name if xml.crc_extra: m.crc_extra_arg = ", %s" % m.crc_extra else: m.crc_extra_arg = "" for f in m.fields: if f.print_format is None: f.c_print_format = 'NULL' else: f.c_print_format = '"%s"' % f.print_format if f.array_length != 0: f.array_suffix = '[%u]' % f.array_length f.array_prefix = '*' f.array_tag = '_array' f.array_arg = ', %u' % f.array_length f.array_return_arg = '%s, %u, ' % (f.name, f.array_length) f.array_const = 'const ' f.decode_left = '' f.decode_right = ', %s->%s' % (m.name_lower, f.name) f.return_type = 'uint16_t' f.get_arg = ', %s *%s' % (f.type, f.name) if f.type == 'char': f.c_test_value = '"%s"' % f.test_value else: test_strings = [] for v in f.test_value: test_strings.append(str(v)) f.c_test_value = '{ %s }' % ', '.join(test_strings) else: f.array_suffix = '' f.array_prefix = '' f.array_tag = '' f.array_arg = '' f.array_return_arg = '' f.array_const = '' f.decode_left = "%s->%s = " % (m.name_lower, f.name) f.decode_right = '' f.get_arg = '' f.return_type = f.type if f.type == 'char': f.c_test_value = "'%s'" % f.test_value elif f.type == 'uint64_t': f.c_test_value = "%sULL" % f.test_value elif f.type == 'int64_t': f.c_test_value = "%sLL" % f.test_value else: f.c_test_value = f.test_value # cope with uint8_t_mavlink_version for m in xml.message: m.arg_fields = [] m.array_fields = [] m.scalar_fields = [] for f in m.ordered_fields: if f.array_length != 0: m.array_fields.append(f) else: m.scalar_fields.append(f) for f in m.fields: if not f.omit_arg: m.arg_fields.append(f) f.putname = f.name else: f.putname = f.const_value generate_mavlink_h(directory, xml) generate_version_h(directory, xml) generate_main_h(directory, xml) for m in xml.message: generate_message_h(directory, m) generate_testsuite_h(directory, xml)
generate complete MAVLink C implemenation
def generate(basename, xml_list): '''generate complete MAVLink C implemenation''' for idx in range(len(xml_list)): xml = xml_list[idx] xml.xml_idx = idx generate_one(basename, xml) copy_fixed_headers(basename, xml_list[0])
Updates Pose3d.
def update(self): ''' Updates Pose3d. ''' pos = Pose3d() if self.hasproxy(): pose = self.proxy.getPose3DData() pos.yaw = self.quat2Yaw(pose.q0, pose.q1, pose.q2, pose.q3) pos.pitch = self.quat2Pitch(pose.q0, pose.q1, pose.q2, pose.q3) pos.roll = self.quat2Roll(pose.q0, pose.q1, pose.q2, pose.q3) pos.x = pose.x pos.y = pose.y pos.z = pose.z pos.h = pose.h pos.q = [pose.q0, pose.q1, pose.q2, pose.q3] self.lock.acquire() self.pose = pos self.lock.release()
Returns last Pose3d. @return last JdeRobotTypes Pose3d saved
def getPose3d(self): ''' Returns last Pose3d. @return last JdeRobotTypes Pose3d saved ''' self.lock.acquire() pose = self.pose self.lock.release() return pose
Translates from Quaternion to Roll. @param qw,qx,qy,qz: Quaternion values @type qw,qx,qy,qz: float @return Roll value translated from Quaternion
def quat2Roll (self, qw, qx, qy, qz): ''' Translates from Quaternion to Roll. @param qw,qx,qy,qz: Quaternion values @type qw,qx,qy,qz: float @return Roll value translated from Quaternion ''' rotateXa0=2.0*(qy*qz + qw*qx) rotateXa1=qw*qw - qx*qx - qy*qy + qz*qz rotateX=0.0 if(rotateXa0 != 0.0 and rotateXa1 != 0.0): rotateX=atan2(rotateXa0, rotateXa1) return rotateX
kill speech dispatcher processs
def kill_speech_dispatcher(self): '''kill speech dispatcher processs''' if not 'HOME' in os.environ: return pidpath = os.path.join(os.environ['HOME'], '.speech-dispatcher', 'pid', 'speech-dispatcher.pid') if os.path.exists(pidpath): try: import signal pid = int(open(pidpath).read()) if pid > 1 and os.kill(pid, 0) is None: print("Killing speech dispatcher pid %u" % pid) os.kill(pid, signal.SIGINT) time.sleep(1) except Exception as e: pass
unload module
def unload(self): '''unload module''' self.settings.set('speech', 0) if self.mpstate.functions.say == self.mpstate.functions.say: self.mpstate.functions.say = self.old_mpstate_say_function self.kill_speech_dispatcher()
speak some text
def say_speechd(self, text, priority='important'): '''speak some text''' ''' http://cvs.freebsoft.org/doc/speechd/ssip.html see 4.3.1 for priorities''' import speechd self.speech = speechd.SSIPClient('MAVProxy%u' % os.getpid()) self.speech.set_output_module('festival') self.speech.set_language('en') self.speech.set_priority(priority) self.speech.set_punctuation(speechd.PunctuationMode.SOME) self.speech.speak(text) self.speech.close()