id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
6,900
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
MAVProxy.modules.mavproxy_magical.magical_ui.ReportDialog.CompassPanel
class CompassPanel(Panel): def __init__(self, parent, m, *k, **kw): super(ReportDialog.CompassPanel, self).__init__(parent, *k, **kw) self.InitUI() self.compass_text.SetLabel('Compass %d' % m.compass_id) if m.cal_status == mavlink.MAG_CAL_SUCCESS: self.status_icon.Success(True) self.status_text.SetLabel('SUCCESS') else: self.status_icon.Success(False) self.status_text.SetLabel('FAILURE') self.fitness_value_text.SetLabel('%.3f' % m.fitness) texts = ( self.offsets_texts, self.diagonals_texts, self.offdiagonals_texts, ) params = ( (m.ofs_x, m.ofs_y, m.ofs_z), (m.diag_x, m.diag_y, m.diag_z), (m.offdiag_x, m.offdiag_y, m.offdiag_z), ) for targets, values in zip(texts, params): for target, value in zip(targets, values): target.SetLabel('%.2f' % value) def InitUI(self): color = wx.Colour() color.SetFromString(LIGHT_BACKGROUND) self.SetBackgroundColour(scale_color(color, 0.95)) font = self.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) font.SetPointSize(24) self.SetFont(font) self.SetMinSize((400, -1)) self.compass_text = wx.StaticText(self) self.fitness_value_text = wx.StaticText(self) font.SetWeight(wx.FONTWEIGHT_NORMAL) self.fitness_value_text.SetFont(font) self.parameters_sizer = self.CalibrationParameters() fitness_sizer = wx.BoxSizer(wx.HORIZONTAL) text = wx.StaticText(self, label='Fitness') text.SetFont(self.fitness_value_text.GetFont()) fitness_sizer.Add(text, proportion=1, flag=wx.EXPAND) fitness_sizer.Add(self.fitness_value_text) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) sizer.AddSpacer(16) sizer.Add(self.compass_text, border=16, flag=wx.LEFT | wx.RIGHT) sizer.AddSpacer(16) sizer.Add(self.StatusPanel(), flag=wx.EXPAND) sizer.AddSpacer(16) sizer.Add(fitness_sizer, border=16, flag=wx.LEFT | wx.RIGHT | wx.EXPAND) sizer.AddSpacer(16) sizer.Add(self.parameters_sizer, border=16, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND) sizer.Hide(self.parameters_sizer) def StatusPanel(self): panel = Panel(self) panel.SetBackgroundColour(ReportDialog.light_background) self.status_icon = ReportDialog.StatusIcon(panel, size=(44, 44)) self.status_text = wx.StaticText(panel) sizer = wx.BoxSizer(wx.HORIZONTAL) panel.SetSizer(sizer) sizer.AddSpacer(16) sizer.Add(self.status_icon, border=5, flag=wx.TOP | wx.BOTTOM) sizer.AddSpacer(16) sizer.Add(self.status_text, flag=wx.ALIGN_CENTER) sizer.AddSpacer(16) return panel def CalibrationParameters(self): self.offsets_texts = tuple(wx.StaticText(self) for _ in range(3)) self.diagonals_texts = tuple(wx.StaticText(self) for _ in range(3)) self.offdiagonals_texts = tuple( wx.StaticText(self) for _ in range(3)) table = ( ('Offsets', self.offsets_texts), ('Diagonals', self.diagonals_texts), ('Off-diagonals', self.offdiagonals_texts), ) sizer = wx.FlexGridSizer(len(table) + 1, 4, 4, 10) sizer.AddGrowableCol(0) font = self.GetFont() font.SetPointSize(14) font.MakeItalic() text = wx.StaticText(self, label='Parameter') text.SetFont(font) sizer.Add(text) for label in ('X', 'Y', 'Z'): text = wx.StaticText(self, label=label) text.SetFont(font) sizer.Add(text, flag=wx.ALIGN_CENTER) font.SetWeight(wx.FONTWEIGHT_NORMAL) for label, (x, y, z) in table: text = wx.StaticText(self) text.SetLabel(label) text.SetFont(font) x.SetFont(font) y.SetFont(font) z.SetFont(font) sizer.Add(text) sizer.Add(x, flag=wx.ALIGN_RIGHT) sizer.Add(y, flag=wx.ALIGN_RIGHT) sizer.Add(z, flag=wx.ALIGN_RIGHT) return sizer def ShowCompassParameters(self, show): sizer = self.GetSizer() if show: sizer.Show(self.parameters_sizer) else: sizer.Hide(self.parameters_sizer)
class CompassPanel(Panel): def __init__(self, parent, m, *k, **kw): pass def InitUI(self): pass def StatusPanel(self): pass def CalibrationParameters(self): pass def ShowCompassParameters(self, show): pass
6
0
27
5
21
0
2
0
1
6
2
0
5
8
5
6
138
30
108
32
102
0
94
32
88
4
2
2
11
6,901
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_link.py
MAVProxy.modules.mavproxy_link.LinkModule.master_msg_handling.PendingText
class PendingText(object): def __init__(self): self.expected_count = None self.severity = None self.chunks = {} self.start_time = time.time() self.last_chunk_time = time.time() def add_chunk(self, m): # m is a statustext message self.severity = m.severity self.last_chunk_time = time.time() if hasattr(m, 'chunk_seq'): # mavlink extensions are present. chunk_seq = m.chunk_seq mid = m.id else: # Note that m.id may still exist! It will # contain the value 253, STATUSTEXT's mavlink # message id. Thus our reliance on the # presence of chunk_seq. chunk_seq = 0 mid = 0 self.chunks[chunk_seq] = m.text if len(m.text) != 50 or mid == 0: self.expected_count = chunk_seq + 1 def complete(self): return (self.expected_count is not None and self.expected_count == len(self.chunks)) def accumulated_statustext(self): next_expected_chunk = 0 out = "" for chunk_seq in sorted(self.chunks.keys()): if chunk_seq != next_expected_chunk: out += " ... " next_expected_chunk = chunk_seq if isinstance(self.chunks[chunk_seq], str): out += self.chunks[chunk_seq] else: out += self.chunks[chunk_seq].decode( errors="ignore") next_expected_chunk += 1 return out
class PendingText(object): def __init__(self): pass def add_chunk(self, m): pass def complete(self): pass def accumulated_statustext(self): pass
5
0
10
1
9
2
2
0.17
1
1
0
0
4
5
4
4
45
5
35
15
30
6
32
15
27
4
1
2
9
6,902
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_smartcamera/ssdp.py
MAVProxy.modules.mavproxy_smartcamera.ssdp.SSDPResponse._FakeSocket
class _FakeSocket(StringIO.StringIO): def makefile(self, *args, **kw): return self
class _FakeSocket(StringIO.StringIO): def makefile(self, *args, **kw): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
1
0
1
6,903
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/lib/rline.py
MAVProxy.modules.lib.rline.mystate
class mystate(object): def __init__(self): self.settings = MPSettings( [MPSetting('foo', int, 1, 'foo int', tab='Link', range=(0, 4), increment=1), MPSetting('bar', float, 4, 'bar float', range=(-1, 20), increment=1)]) self.completions = { "script": ["(FILENAME)"], "set": ["(SETTING)"] } self.command_map = { 'script': (None, 'run a script of MAVProxy commands'), 'set': (None, 'mavproxy settings'), } self.aliases = {}
class mystate(object): def __init__(self): pass
2
0
13
0
13
0
1
0
1
4
2
0
1
4
1
1
14
0
14
6
12
0
6
6
4
1
1
0
1
6,904
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/lib/rline.py
MAVProxy.modules.lib.rline.MAVPromptCompleter
class MAVPromptCompleter(Completer): '''Completion generator for commands''' def __init__(self, ): # global rline_mpstate # self.mpstate = rline_mpstate self.last_clist = None # other modules can add their own completion functions def get_completions(self, document, complete_event): '''yield all the possible completion strings''' global rline_mpstate text = document.text_before_cursor # cmd = text.split(' ') cmd = re.split(" +", text) final_completor = cmd[-1] if len(cmd) != 0 and cmd[0] in rline_mpstate.completions: # we have a completion rule for this command self.last_clist = complete_rules( rline_mpstate.completions[cmd[0]], cmd[1:]) elif len(cmd) == 0 or len(cmd) == 1: # if on first part then complete on commands and aliases self.last_clist = complete_command(text) + complete_alias(text) else: # assume completion by filename self.last_clist = glob.glob(text+'*') ret = [] for c in self.last_clist: if c.startswith(final_completor) or c.startswith(final_completor.upper()): ret.append(c) if len(ret) == 0: # if we had no matches then try case insensitively final_completor = final_completor.lower() for c in self.last_clist: if c.lower().startswith(final_completor): ret.append(c) for c in ret: yield Completion(c, start_position=-len(final_completor))
class MAVPromptCompleter(Completer): '''Completion generator for commands''' def __init__(self, ): pass def get_completions(self, document, complete_event): '''yield all the possible completion strings''' pass
3
2
18
2
12
4
5
0.4
1
1
0
0
2
1
2
24
39
4
25
10
21
10
23
10
19
9
4
3
10
6,905
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/lib/mav_fft.py
MAVProxy.modules.lib.mav_fft.mavfft_display.PlotData
class PlotData(object): def __init__(self, ffth): self.seqno = -1 self.fftnum = ffth.N self.sensor_type = ffth.type self.instance = ffth.instance self.sample_rate_hz = ffth.smp_rate self.multiplier = ffth.mul self.data = {} self.data["X"] = [] self.data["Y"] = [] self.data["Z"] = [] self.holes = False self.freq = None def add_fftd(self, fftd): if fftd.N != self.fftnum: print("Skipping ISBD with wrong fftnum (%u vs %u)\n" % (fftd.fftnum, self.fftnum)) return if self.holes: print("Skipping ISBD(%u) for ISBH(%u) with holes in it" % (fftd.seqno, self.fftnum)) return if fftd.seqno != self.seqno+1: print("ISBH(%u) has holes in it" % fftd.N) self.holes = True return self.seqno += 1 self.data["X"].extend(fftd.x) self.data["Y"].extend(fftd.y) self.data["Z"].extend(fftd.z) def prefix(self): if self.sensor_type == 0: return "Accel" elif self.sensor_type == 1: return "Gyro" else: return "?Unknown Sensor Type?" def tag(self): return str(self) def __str__(self): return "%s[%u]" % (self.prefix(), self.instance)
class PlotData(object): def __init__(self, ffth): pass def add_fftd(self, fftd): pass def prefix(self): pass def tag(self): pass def __str__(self): pass
6
0
8
0
8
0
2
0
1
1
0
0
5
9
5
5
44
4
40
15
34
0
38
15
32
4
1
1
10
6,906
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/mavproxy.py
MAVProxy.mavproxy.MPStatus.ByteCounter
class ByteCounter(object): def __init__(self): self.total_count = 0 self.current_count = 0 self.buckets = [] self.max_buckets = 10 # 10 seconds def update(self, bytecount): self.total_count += bytecount self.current_count += bytecount def rotate(self): '''move current count into a bucket, zero count''' # huge assumption made that we're called rapidly enough to # not need to rotate multiple buckets. self.buckets.append(self.current_count) self.current_count = 0 if len(self.buckets) > self.max_buckets: self.buckets = self.buckets[-self.max_buckets:] def rate(self): if len(self.buckets) == 0: return 0 total = 0 for bucket in self.buckets: total += bucket return total/float(len(self.buckets)) def total(self): return self.total_count
class ByteCounter(object): def __init__(self): pass def update(self, bytecount): pass def rotate(self): '''move current count into a bucket, zero count''' pass def rate(self): pass def total(self): pass
6
1
5
0
4
1
2
0.17
1
1
0
0
5
4
5
5
30
4
23
12
17
4
23
12
17
3
1
1
8
6,907
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/tools/MAVExplorer.py
MAVExplorer.ftp_decode.Transfer
class Transfer(object): def __init__(self, filename): self.filename = filename self.blocks = [] def extract(self): self.blocks.sort(key=lambda x: x.offset) data = bytes() for b in self.blocks: if b.offset < len(data): continue if b.offset > len(data): print("gap at %u" % len(data)) return None data += bytes(b.data) return data
class Transfer(object): def __init__(self, filename): pass def extract(self): pass
3
0
7
0
7
0
3
0
1
1
0
0
2
2
2
2
16
1
15
7
12
0
15
7
12
4
1
2
5
6,908
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/tools/MAVExplorer.py
MAVExplorer.ftp_decode.Block
class Block(object): def __init__(self, offset, size, data): self.offset = offset self.size = size self.data = data
class Block(object): def __init__(self, offset, size, data): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
3
1
1
5
0
5
5
3
0
5
5
3
1
1
0
1
6,909
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_paramedit/param_editor.py
MAVProxy.modules.mavproxy_paramedit.param_editor.ParamEditorMain.child_task.CloseWindowSemaphoreWatcher
class CloseWindowSemaphoreWatcher(threading.Thread): def __init__(self, task, sem): threading.Thread.__init__(self) self.task = task self.sem = sem def run(self): self.sem.acquire(True) self.task.app.ExitMainLoop()
class CloseWindowSemaphoreWatcher(threading.Thread): def __init__(self, task, sem): pass def run(self): pass
3
0
4
0
4
0
1
0
1
0
0
0
2
2
2
27
9
1
8
5
5
0
8
5
5
1
1
0
2
6,910
ArduPilot/MAVProxy
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_link.py
MAVProxy.modules.mavproxy_link.LinkModule.TimeSyncRequest
class TimeSyncRequest(): '''send and receive TIMESYNC mavlink messages, printing results''' def __init__(self, master, max_attempts=1, console=None): self.attempts_remaining = max_attempts self.last_sent_ns = 0 self.sent_on_timestamps = [] self.mav = master self.max_lifetime = 20 # seconds self.response_received = False self.console = console def age_limit_exceeded(self): '''true if this object should be reaped''' if len(self.sent_on_timestamps) == 0: return False return int(time.time() * 1e9) - self.sent_on_timestamps[0] > self.max_lifetime*1e9 def update(self): '''send timesync requests at intervals''' now_ns = int(time.time() * 1e9) if now_ns - self.last_sent_ns < 1e9: # ping at 1s intervals return if self.attempts_remaining == 0: return self.attempts_remaining -= 1 self.last_sent_ns = now_ns # encode outbound link in bottom 4 bits now_ns = now_ns & ~ 0b1111 now_ns = now_ns | self.mav.linknum self.sent_on_timestamps.append(now_ns) self.mav.mav.timesync_send(0, now_ns) def handle_TIMESYNC(self, m, master): '''handle TIMESYNC message m received on link master''' if m.ts1 not in self.sent_on_timestamps: # we didn't send this one return now_ns = time.time() * 1e9 out_link = m.ts1 & 0b1111 # out link encoded in bottom four bits if self.console is not None: self.console.writeln(f"ping response: {(now_ns-m.ts1)*1e-6:.3f}ms from={m.get_srcSystem()}/{m.get_srcComponent()} in-link={master.linknum} out-link={out_link}")
class TimeSyncRequest(): '''send and receive TIMESYNC mavlink messages, printing results''' def __init__(self, master, max_attempts=1, console=None): pass def age_limit_exceeded(self): '''true if this object should be reaped''' pass def update(self): '''send timesync requests at intervals''' pass def handle_TIMESYNC(self, m, master): '''handle TIMESYNC message m received on link master''' pass
5
4
9
0
8
2
2
0.31
0
1
0
0
4
7
4
4
41
3
32
15
27
10
32
15
27
3
0
1
9
6,911
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/msgstats.py
MAVProxy.modules.lib.msgstats.MPMsgStats
class MPMsgStats(MPDataLogChildTask): '''A class used launch `show_stats` in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- mlog : DFReader A dataflash or telemetry log ''' super(MPMsgStats, self).__init__(*args, **kwargs) # @override def child_task(self): '''Launch `show_stats`''' # run the fft tool show_stats(self.mlog)
class MPMsgStats(MPDataLogChildTask): '''A class used launch `show_stats` in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- mlog : DFReader A dataflash or telemetry log ''' pass def child_task(self): '''Launch `show_stats`''' pass
3
3
7
1
2
4
1
2
1
1
0
0
2
0
2
18
19
4
5
3
2
10
5
3
2
1
3
0
2
6,912
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_ui.py
MAVProxy.modules.mavproxy_map.mp_slipmap_ui.MPSlipMapFrame
class MPSlipMapFrame(wx.Frame): """ The main frame of the viewer """ def __init__(self, state): wx.Frame.__init__(self, None, wx.ID_ANY, state.title) try: self.SetIcon(icon.SimpleIcon("MAP").get_ico()) except Exception: pass self.state = state state.frame = self state.grid = True state.follow = True state.download = True state.popup_objects = None state.popup_latlon = None state.popup_started = False state.default_popup = None state.panel = MPSlipMapPanel(self, state) self.last_layout_send = time.time() self.Bind(wx.EVT_IDLE, self.on_idle) self.Bind(wx.EVT_SIZE, state.panel.on_size) self.legend_checkbox_menuitem_added = False # create the View menu self.menu = MPMenuTop([ MPMenuSubMenu('View', items=[ MPMenuCheckbox('Follow\tCtrl+F', 'Follow Aircraft', 'toggleFollow', checked=state.follow), MPMenuCheckbox('Grid\tCtrl+G', 'Enable Grid', 'toggleGrid', checked=state.grid), MPMenuItem('Goto\tCtrl+P', 'Goto Position', 'gotoPosition'), MPMenuItem('Brightness +\tCtrl+B', 'Increase Brightness', 'increaseBrightness'), MPMenuItem('Brightness -\tCtrl+Shift+B', 'Decrease Brightness', 'decreaseBrightness'), MPMenuItem('Zoom +\t+', 'Zoom In', 'zoomIn'), MPMenuItem('Zoom -\t-', 'Zoom Out', 'zoomOut'), MPMenuCheckbox('Download Tiles\tCtrl+D', 'Enable Tile Download', 'toggleDownload', checked=state.download), MPMenuRadio('Tile Service', 'Select map tile service', returnkey='setService', selected=state.mt.get_service(), items=state.mt.get_service_list()), MPMenuRadio('Terrain Service', 'Select terrain service', returnkey='setServiceTerrain', selected=state.elevation, items=sorted(TERRAIN_SERVICES.keys()))])]) self.SetMenuBar(self.menu.wx_menu()) self.Bind(wx.EVT_MENU, self.on_menu) def on_menu(self, event): '''handle menu selection''' state = self.state # see if it is a popup menu if state.popup_objects is not None: for obj in state.popup_objects: 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)) break state.popup_objects = 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 == 'toggleLegend': state.legend = 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 == 'setServiceTerrain': state.elevation = ret.get_choice() state.ElevationMap = mp_elevation.ElevationModel(database=state.elevation) # Send to MAVProxy main process, so the terrain module can be updated too state.event_queue.put(SlipMenuEvent(None, event, [], ret)) elif ret.returnkey == 'gotoPosition': state.panel.enter_position() elif ret.returnkey == 'increaseBrightness': state.brightness += 20 if state.brightness > 255: state.brightness = 255 elif ret.returnkey == 'decreaseBrightness': state.brightness -= 20 if state.brightness < -255: state.brightness = -255 elif ret.returnkey == 'zoomIn': state.panel.change_zoom(1.0/1.2) elif ret.returnkey == 'zoomOut': state.panel.change_zoom(1.2) state.need_redraw = True def find_object(self, key, layers): '''find an object to be modified''' state = self.state if layers is None or layers == '': layers = state.layers.keys() for layer in layers: if key in state.layers[layer]: return state.layers[layer][key] return None 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) def add_legend_checkbox_menuitem(self): self.menu.add_to_submenu(['View'], [MPMenuCheckbox('Legend\tCtrl+L', 'Enable Legend', 'toggleLegend', checked=self.state.legend) ]) def add_object(self, obj): '''add an object to a layer''' 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 if (not self.legend_checkbox_menuitem_added and isinstance(obj, SlipFlightModeLegend)): self.add_legend_checkbox_menuitem() self.legend_checkbox_menuitem_added = True self.SetMenuBar(self.menu.wx_menu()) 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 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() now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now state.event_queue.put(win_layout.get_wx_window_layout(self)) # receive any display objects from the parent obj = None while not state.object_queue.empty(): obj = state.object_queue.get() if isinstance(obj, win_layout.WinLayout): win_layout.set_wx_window_layout(self, obj) 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) if obj.label is not None: object.label = obj.label if obj.colour is not None: object.colour = obj.colour 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, SlipZoom): # change zoom state.panel.set_ground_width(obj.ground_width) state.need_redraw = True if isinstance(obj, SlipFollow): # enable/disable follow state.follow = obj.enable if isinstance(obj, SlipFollowObject): # enable/disable follow on an object for layer in state.layers: if obj.key in state.layers[layer]: if hasattr(state.layers[layer][obj.key], 'follow'): state.layers[layer][obj.key].follow = obj.enable 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 state.timelim_pipe is not None: while state.timelim_pipe[1].poll(): try: obj = state.timelim_pipe[1].recv() except Exception: state.timelim_pipe = None break for layer in state.layers: for key in state.layers[layer].keys(): state.layers[layer][key].set_time_range(obj) state.need_redraw = True if obj is None: time.sleep(0.05)
class MPSlipMapFrame(wx.Frame): ''' The main frame of the viewer ''' def __init__(self, state): pass def on_menu(self, event): '''handle menu selection''' pass def find_object(self, key, layers): '''find an object to be modified''' pass def follow(self, object): '''follow an object on the map''' pass def add_legend_checkbox_menuitem(self): pass def add_object(self, obj): '''add an object to a layer''' pass def remove_object(self, key): '''remove an object by key from all layers''' pass def on_idle(self, event): '''prevent the main loop spinning too fast''' pass
9
7
35
3
29
3
9
0.12
1
25
24
0
8
4
8
8
291
31
232
32
223
28
175
32
166
36
1
5
71
6,913
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/live_graph_ui.py
MAVProxy.modules.lib.live_graph_ui.GraphFrame
class GraphFrame(wx.Frame): """ The main frame of the application """ def __init__(self, state): wx.Frame.__init__(self, None, -1, state.title) try: self.SetIcon(icon.SimpleIcon().get_ico()) except Exception: pass self.state = state self.data = [] for i in range(len(state.fields)): self.data.append([]) self.paused = False self.create_main_panel() self.Bind(wx.EVT_IDLE, self.on_idle) self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(int(1000*self.state.tickresolution)) self.last_yrange = (None, None) def create_main_panel(self): import platform if platform.system() == 'Darwin': from MAVProxy.modules.lib.MacOS import backend_wxagg FigCanvas = backend_wxagg.FigureCanvasWxAgg else: from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) self.close_button = wx.Button(self.panel, -1, "Close") self.Bind(wx.EVT_BUTTON, self.on_close_button, self.close_button) self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.close_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.hbox1.AddSpacer(1) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) self.vbox.Fit(self) def init_plot(self): self.dpi = 100 from matplotlib.figure import Figure self.fig = Figure((6.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) try: self.axes.set_facecolor('white') except AttributeError as e: # this was removed in matplotlib 2.2.0: self.axes.set_axis_bgcolor('white') pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = [] if len(self.data[0]) == 0: max_y = min_y = 0 else: max_y = min_y = self.data[0][0] num_labels = 0 if not self.state.labels else len(self.state.labels) labels = [] for i in range(len(self.data)): if i < num_labels and self.state.labels[i] is not None: label = self.state.labels[i] else: label = self.state.fields[i] labels.append(label) p = self.axes.plot( self.data[i], linewidth=1, color=self.state.colors[i], label=label )[0] self.plot_data.append(p) if len(self.data[i]) != 0: min_y = min(min_y, min(self.data[i])) max_y = max(max_y, max(self.data[i])) # create X data self.xdata = numpy.arange(-self.state.timespan, 0, self.state.tickresolution) self.axes.set_xbound(lower=self.xdata[0], upper=0) if min_y == max_y: self.axes.set_ybound(min_y, max_y+0.1) self.axes.legend(labels, loc='upper left', bbox_to_anchor=(0, 1.1)) def draw_plot(self): """ Redraws the plot """ state = self.state if len(self.data[0]) == 0: print("no data to plot") return vhigh = max(self.data[0]) vlow = min(self.data[0]) for i in range(1,len(self.plot_data)): vhigh = max(vhigh, max(self.data[i])) vlow = min(vlow, min(self.data[i])) ymin = vlow - 0.05*(vhigh-vlow) ymax = vhigh + 0.05*(vhigh-vlow) if ymin == ymax: ymax = ymin + 0.1 * ymin ymin = ymin - 0.1 * ymin if (ymin, ymax) != self.last_yrange: self.last_yrange = (ymin, ymax) if ymax == ymin: ymin = ymin-0.5 ymax = ymin+1 self.axes.set_ybound(lower=ymin, upper=ymax) #self.axes.ticklabel_format(useOffset=False, style='plain') self.axes.grid(True, color='gray') pylab.setp(self.axes.get_xticklabels(), visible=True) pylab.setp(self.axes.get_legend().get_texts(), fontsize='small') for i in range(len(self.plot_data)): ydata = numpy.array(self.data[i]) xdata = self.xdata if len(ydata) < len(self.xdata): xdata = xdata[-len(ydata):] self.plot_data[i].set_xdata(xdata) self.plot_data[i].set_ydata(ydata) self.canvas.draw() self.canvas.Refresh() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_close_button(self, event): self.redraw_timer.Stop() self.Destroy() def on_idle(self, event): time.sleep(self.state.tickresolution*0.5) def on_redraw_timer(self, event): # if paused do not add data, but still redraw the plot # (to respond to scale modifications, grid change, etc.) # state = self.state if state.close_graph.wait(0.001): self.redraw_timer.Stop() self.Destroy() return while state.child_pipe.poll(): state.values = state.child_pipe.recv() if self.paused: return for i in range(len(self.plot_data)): if (type(state.values[i]) == list): print("ERROR: Cannot plot array of length %d. Use 'graph %s[index]' instead"%(len(state.values[i]), state.fields[i])) self.redraw_timer.Stop() self.Destroy() return if state.values[i] is not None: self.data[i].append(state.values[i]) while len(self.data[i]) > len(self.xdata): self.data[i].pop(0) for i in range(len(self.plot_data)): if state.values[i] is None or len(self.data[i]) < 2: return self.draw_plot()
class GraphFrame(wx.Frame): ''' The main frame of the application ''' def __init__(self, state): pass def create_main_panel(self): pass def init_plot(self): pass def draw_plot(self): ''' Redraws the plot ''' pass def on_pause_button(self, event): pass def on_update_pause_button(self, event): pass def on_close_button(self, event): pass def on_idle(self, event): pass def on_redraw_timer(self, event): pass
10
2
20
3
16
1
4
0.09
1
7
1
0
9
16
9
9
194
33
148
50
134
13
140
49
126
10
1
3
36
6,914
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/live_graph.py
MAVProxy.modules.lib.live_graph.LiveGraph
class LiveGraph(): ''' a live graph object using wx and matplotlib All of the GUI work is done in a child process to provide some insulation from the parent mavproxy instance and prevent instability in the GCS New data is sent to the LiveGraph instance via a pipe ''' def __init__(self, fields, title='MAVProxy: LiveGraph', timespan=20.0, tickresolution=0.2, colors=[ 'red', 'green', 'blue', 'orange', 'olive', 'cyan', 'magenta', 'brown', 'violet', 'purple', 'grey', 'black'], labels=None): self.fields = fields self.labels = labels self.colors = colors self.title = title self.timespan = timespan self.tickresolution = tickresolution self.values = [None]*len(self.fields) self.parent_pipe,self.child_pipe = multiproc.Pipe() self.close_graph = multiproc.Event() self.close_graph.clear() self.child = multiproc.Process(target=self.child_task) self.child.start() def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() import matplotlib, platform if platform.system() != "Darwin": # on MacOS we can't set WxAgg here as it conflicts with the MacOS version matplotlib.use('WXAgg') from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx app = wx.App(False) from MAVProxy.modules.lib import live_graph_ui app.frame = live_graph_ui.GraphFrame(state=self) app.frame.Show() app.MainLoop() def add_values(self, values): '''add some data to the graph''' if self.child.is_alive(): self.parent_pipe.send(values) def close(self): '''close the graph''' self.close_graph.set() if self.is_alive(): self.child.join(2) def is_alive(self): '''check if graph is still going''' return self.child.is_alive()
class LiveGraph(): ''' a live graph object using wx and matplotlib All of the GUI work is done in a child process to provide some insulation from the parent mavproxy instance and prevent instability in the GCS New data is sent to the LiveGraph instance via a pipe ''' def __init__(self, fields, title='MAVProxy: LiveGraph', timespan=20.0, tickresolution=0.2, colors=[ 'red', 'green', 'blue', 'orange', 'olive', 'cyan', 'magenta', 'brown', 'violet', 'purple', 'grey', 'black'], labels=None): pass def child_task(self): '''child process - this holds all the GUI elements''' pass def add_values(self, values): '''add some data to the graph''' pass def close(self): '''close the graph''' pass def is_alive(self): '''check if graph is still going''' pass
6
5
10
1
8
1
2
0.26
0
1
1
0
5
11
5
5
61
8
42
28
25
11
35
21
25
2
0
1
8
6,915
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/icon.py
MAVProxy.modules.lib.icon.SimpleIcon
class SimpleIcon(): """ Generate icons with Matplotlib. """ def __init__(self, text=None): LIGHT_BLUE_BACKGROUND = "#afceff" VIOLET_FONT = "#4800f0" t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) def f(t): return np.exp(-t) * np.cos(2*np.pi*t) fig = Figure(figsize=(1.28, 1.28), facecolor=LIGHT_BLUE_BACKGROUND) spec = GridSpec(nrows=2, ncols=1, wspace=0, hspace=0.0, height_ratios=[1, 2]) ax = fig.add_subplot(spec[0]) ax.text(0, 0.8, 'MAV', style='italic', fontsize=20, weight='bold', color=VIOLET_FONT) if text is None: text = "GRAPH" ax.text(0, 0.1, text.upper(), style='italic', fontsize=14, weight='bold', color=VIOLET_FONT) ax.axis('off') ax = fig.add_subplot(spec[1], facecolor=LIGHT_BLUE_BACKGROUND) if text == "GRAPH" or text == "EXPLORER": ax.plot(t1, f(t1), color='tab:green', marker='o') ax.plot(t2, f(t2), color='red') ax.set_xticks(t1, minor=True) ax.grid(True, which='both', linestyle="--") if text == "CONSOLE": ax.plot([0, 2.5], [2.5, 1.25], color='red', linewidth=4) ax.plot([0, 2.5], [0, 1.25], color='red', linewidth=4) ax.plot([3, 5], [0, 0], color='red', linewidth=4) ax.axis('off') if text == "MAP": path_data = [ (mpath.Path.MOVETO, [2.5, 0]), (mpath.Path.LINETO, [1.25, 2.5]), (mpath.Path.CURVE3, [2.5, 5]), (mpath.Path.CURVE3, [3.75, 2.5]), (mpath.Path.LINETO, [3.75, 2.5]), (mpath.Path.CLOSEPOLY, [2.5, 0])] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='red', lw=2) ax.add_patch(patch) circle_neg = mpatches.Circle((2.5, 2.5), 0.5, color='white') ax.add_patch(circle_neg) ax.plot([0, 5/3.0, 10/3.0, 5], [5, 4, 5, 4], color='black', linewidth=2) ax.plot([0, 5/3.0, 10/3.0, 5], [-1, -2, -1, -2], color='black', linewidth=2) ax.plot([0, 0], [-1, 5], color='black', linewidth=2) ax.plot([5/3.0, 5/3.0], [-2, 4], color='black', linewidth=2) ax.plot([10/3.0, 10/3.0], [-1, 5], color='black', linewidth=2) ax.plot([5, 5], [-2, 4], color='black', linewidth=2) ax.set_xlim(-0.5, 5.5) ax.set_ylim(-2.5, 5.5) ax.axis('off') buf = BytesIO() fig.savefig(buf, format='png') buf.seek(0) svgimg = wx.Image(buf, wx.BITMAP_TYPE_PNG) self.img = svgimg def get_ico(self): """Get the ico from the image bitmap. need to be call after the wx.app is created.""" return wx.Icon(wx.Bitmap(self.img))
class SimpleIcon(): ''' Generate icons with Matplotlib. ''' def __init__(self, text=None): pass def f(t): pass def get_ico(self): '''Get the ico from the image bitmap. need to be call after the wx.app is created.''' pass
4
2
22
2
19
1
2
0.12
0
1
0
0
2
1
2
2
69
7
57
19
53
7
51
19
47
5
0
1
7
6,916
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/grapher.py
MAVProxy.modules.lib.grapher.MilliFormatter
class MilliFormatter(matplotlib.dates.AutoDateFormatter): '''tick formatter that shows millisecond resolution''' def __init__(self, locator): super().__init__(locator) # don't show day until much wider range self.scaled[1.0/(24*60)] = self.scaled[1.0/(24*60*60)] def __call__(self, x, pos=0): """Return the label for time x at position pos.""" v = super().__call__(x,pos=pos) if v.endswith("000"): return v[:-3] return v
class MilliFormatter(matplotlib.dates.AutoDateFormatter): '''tick formatter that shows millisecond resolution''' def __init__(self, locator): pass def __call__(self, x, pos=0): '''Return the label for time x at position pos.''' pass
3
2
5
0
4
1
2
0.33
1
1
0
0
2
0
2
2
13
1
9
4
6
3
9
4
6
2
1
1
3
6,917
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/grapher.py
MAVProxy.modules.lib.grapher.MavGraph
class MavGraph(object): def __init__(self, flightmode_colourmap=None): self.lowest_x = None self.highest_x = None self.mav_list = [] self.fields = [] self.condition = None self.xaxis = None self.marker = None self.linestyle = None self.show_flightmode = True self.legend = 'upper left' self.legend2 = 'upper right' self.legend_flightmode = 'lower left' self.timeshift = 0 self.labels = None self.multi = False self.modes_plotted = {} self.flightmode_colour_index = 0 if flightmode_colourmap: self.flightmode_colourmap = flightmode_colourmap else: self.flightmode_colourmap = {} self.flightmode_list = None self.ax1 = None self.locator = None global graph_num self.graph_num = graph_num self.start_time = None graph_num += 1 self.draw_events = 0 self.closing = False self.xlim_pipe = None self.xlim = None self.tday_base = None self.tday_basetime = None self.title = None self.grid = False self.xlim_t = None if sys.version_info[0] >= 3: self.text_types = frozenset([str,]) else: self.text_types = frozenset([unicode, str]) self.max_message_rate = 0 def set_max_message_rate(self, rate_hz): '''set maximum rate we will graph any message''' self.max_message_rate = rate_hz self.last_message_t = {} def add_field(self, field): '''add another field to plot''' self.fields.append(field) def add_mav(self, mav): '''add another data source to plot''' self.mav_list.append(mav) def set_condition(self, condition): '''set graph condition''' self.condition = condition def set_xaxis(self, xaxis): '''set graph xaxis''' self.xaxis = xaxis def set_title(self, title): '''set graph title''' self.title = title def set_grid(self, enable): '''enable grid''' self.grid = enable def set_marker(self, marker): '''set graph marker''' self.marker = marker def set_timeshift(self, timeshift): '''set graph timeshift''' self.timeshift = timeshift def set_legend2(self, legend2): '''set graph legend2''' self.legend2 = legend2 def set_legend(self, legend): '''set graph legend''' self.legend = legend def set_show_flightmode(self, value): '''set to true if flightmodes are to be shown''' self.show_flightmode = value def set_linestyle(self, linestyle): '''set graph linestyle''' self.linestyle = linestyle def set_multi(self, multi): '''set multiple graph option''' self.multi = multi def make_format(self, current, other): # current and other are axes def format_coord(x, y): # x, y are data coordinates # convert to display coords display_coord = current.transData.transform((x,y)) inv = other.transData.inverted() # convert back to data coords with respect to ax ax_coord = inv.transform(display_coord) xstr = self.formatter(x) y2 = ax_coord[1] if self.xaxis: return ('x=%.3f Left=%.3f Right=%.3f' % (x, y2, y)) else: return ('x=%s Left=%.3f Right=%.3f' % (xstr, y2, y)) return format_coord def next_flightmode_colour(self): '''allocate a colour to be used for a flight mode''' if self.flightmode_colour_index > len(flightmode_colours): print("Out of colours; reusing") self.flightmode_colour_index = 0 ret = flightmode_colours[self.flightmode_colour_index] self.flightmode_colour_index += 1 return ret def flightmode_colour(self, flightmode): '''return colour to be used for rendering a flight mode background''' if flightmode not in self.flightmode_colourmap: self.flightmode_colourmap[flightmode] = self.next_flightmode_colour() return self.flightmode_colourmap[flightmode] def xlim_changed(self, axsubplot): '''called when x limits are changed''' xrange = axsubplot.get_xbound() xlim = axsubplot.get_xlim() if self.draw_events == 0: # ignore limit change before first draw event return if self.xlim_pipe is not None and axsubplot == self.ax1 and xlim != self.xlim: self.xlim = xlim #print('send', self.graph_num, xlim) self.xlim_pipe[1].send(xlim) def draw_event(self, evt): '''called on draw events''' self.draw_events += 1 def close_event(self, evt): '''called on close events''' self.closing = True def rescale_yaxis(self, axis): '''rescale Y axes to fit''' ylim = [None,None] for line in axis.lines: xdata = line.get_xdata() xlim = axis.get_xlim() xidx1 = np.argmax(xdata > xlim[0]) xidx2 = np.argmax(xdata > xlim[1]) if xidx2 == 0: xidx2 = len(xdata)-1 ydata = line.get_ydata()[xidx1:xidx2] min_v = np.amin(ydata) max_v = np.amax(ydata) if ylim[0] is None or min_v < ylim[0]: ylim[0] = min_v if ylim[1] is None or max_v > ylim[1]: ylim[1] = max_v rng = ylim[1] - ylim[0] pad = 0.05 * rng if pad == 0: pad = 0.001 * ylim[0] axis.set_ylim((ylim[0]-pad,ylim[1]+pad)) def button_click(self, event): '''handle button clicks''' if getattr(event, 'dblclick', False) and event.button==1: self.rescale_yaxis(self.ax1) if self.ax2: self.rescale_yaxis(self.ax2) def plotit(self, x, y, fields, colors=[], title=None, interactive=True): '''plot a set of graphs using date for x axis''' if interactive: plt.ion() self.fig = plt.figure(num=1, figsize=(12,6)) self.ax1 = self.fig.gca() self.ax2 = None 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 self.locator = matplotlib.dates.AutoDateLocator() self.ax1.xaxis.set_major_locator(self.locator) self.formatter = MilliFormatter(self.locator) if not self.xaxis: self.ax1.xaxis.set_major_formatter(self.formatter) self.ax1.callbacks.connect('xlim_changed', self.xlim_changed) self.fig.canvas.mpl_connect('draw_event', self.draw_event) self.fig.canvas.mpl_connect('close_event', self.close_event) self.fig.canvas.mpl_connect('button_press_event', self.button_click) self.fig.canvas.get_default_filename = lambda: ''.join("graph" if self.title is None else (x if x.isalnum() else '_' for x in self.title)) + '.png' empty = True ax1_labels = [] ax2_labels = [] for i in range(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 self.ax2 is None: self.ax2 = self.ax1.twinx() if self.grid: self.ax2.grid(None) self.ax1.grid(True) self.ax2.format_coord = self.make_format(self.ax2, self.ax1) ax = self.ax2 if not self.xaxis: self.ax2.xaxis.set_major_locator(self.locator) self.ax2.xaxis.set_major_formatter(self.formatter) label = fields[i] if label.endswith(":2"): label = label[:-2] ax2_labels.append(label) if self.custom_labels[i] is not None: ax2_labels[-1] = self.custom_labels[i] else: ax1_labels.append(fields[i]) if self.custom_labels[i] is not None: ax1_labels[-1] = self.custom_labels[i] ax = self.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 = '-' if len(y[i]) > 0 and type(y[i][0]) in self.text_types: # assume this is a piece of text to be rendered at a point in time last_text_time = -1 last_text = None for n in range(0, len(x[i])): this_text_time = round(x[i][n], 6) this_text = y[i][n] if last_text is None: last_text = "[" + this_text + "]" last_text_time = this_text_time elif this_text_time == last_text_time: last_text += ("[" + this_text + "]") else: ax.text(last_text_time, 10, last_text, rotation=90, alpha=0.6, verticalalignment='center') last_text = this_text last_text_time = this_text_time if last_text is not None: ax.text(last_text_time, 10, last_text, rotation=90, alpha=0.6, verticalalignment='center') else: ax.plot_date(x[i], y[i], fmt=color, label=fields[i], linestyle=linestyle, marker=marker, tz=None) empty = False if self.grid: plt.grid() if self.show_flightmode != 0: alpha = 0.3 xlim = self.ax1.get_xlim() for i in range(len(self.flightmode_list)): (mode_name,t0,t1) = self.flightmode_list[i] c = self.flightmode_colour(mode_name) tday0 = timestamp_to_days(t0, self.timeshift) tday1 = timestamp_to_days(t1, self.timeshift) if tday0 > xlim[1] or tday1 < xlim[0]: continue tday0 = max(tday0, xlim[0]) tday1 = min(tday1, xlim[1]) self.ax1.axvspan(tday0, tday1, fc=c, ec=edge_colour, alpha=alpha) self.modes_plotted[mode_name] = (c, alpha) if empty: print("No data to graph") return if title is not None: plt.title(title) else: title = fields[0] if self.fig.canvas.manager is not None: self.fig.canvas.manager.set_window_title(title) else: self.fig.canvas.set_window_title(title) if self.show_flightmode != 0: mode_patches = [] for mode in self.modes_plotted.keys(): (color, alpha) = self.modes_plotted[mode] mode_patches.append(matplotlib.patches.Patch(color=color, label=mode, alpha=alpha*1.5)) labels = [patch.get_label() for patch in mode_patches] if ax1_labels != [] and self.show_flightmode != 2: patches_legend = plt.legend(mode_patches, labels, loc=self.legend_flightmode) self.fig.gca().add_artist(patches_legend) else: plt.legend(mode_patches, labels) if ax1_labels != []: self.ax1.legend(ax1_labels,loc=self.legend) if ax2_labels != []: self.ax2.legend(ax2_labels,loc=self.legend2) def add_data(self, t, msg, vars): '''add some data''' mtype = msg.get_type() for i in range(0, len(self.fields)): if mtype not in self.field_types[i]: continue f = self.fields[i] has_instance = False ins_value = None if mtype in self.instance_types[i]: instance_field = getattr(msg,'instance_field',None) if instance_field is None and hasattr(msg,'fmt'): instance_field = getattr(msg.fmt,'instance_field') if instance_field is not None: ins_value = getattr(msg,instance_field,None) if ins_value is None or not str(ins_value) in self.instance_types[i][mtype]: continue if not mtype in vars or not isinstance(vars[mtype], dict): vars[mtype] = dict() vars[mtype][ins_value] = msg if isinstance(ins_value, str): mtype_instance = '%s[%s]' % (mtype, ins_value) mtype_instance_str = '%s["%s"]' % (mtype, getattr(msg, instance_field)) f = f.replace(mtype_instance, mtype_instance_str) has_instance = True # allow for capping the displayed message rate if self.max_message_rate > 0: mtype_ins = (mtype,ins_value,f) mt = msg._timestamp if mtype_ins in self.last_message_t: dt = mt - self.last_message_t[mtype_ins] if dt < 1.0 / self.max_message_rate: continue self.last_message_t[mtype_ins] = mt simple = self.simple_field[i] v = None if simple is not None and not has_instance: try: v = getattr(vars[simple[0]], simple[1]) except Exception as ex: if MAVGRAPH_DEBUG: print(ex) if v is None: try: v = mavutil.evaluate_expression(f, vars) except Exception as ex: if MAVGRAPH_DEBUG: print(ex) 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) def process_mav(self, mlog, flightmode_selections): '''process one file''' self.vars = {} idx = 0 all_false = True for s in flightmode_selections: if s: all_false = False self.num_fields = len(self.fields) self.custom_labels = [None] * self.num_fields for i in range(self.num_fields): if self.fields[i].endswith(">"): a2 = self.fields[i].rfind("<") if a2 != -1: self.custom_labels[i] = self.fields[i][a2+1:-1] self.fields[i] = self.fields[i][:a2] # pre-calc right/left axes for i in range(self.num_fields): 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] self.fields[i] = f # see which fields are simple self.simple_field = [] for i in range(0, self.num_fields): f = self.fields[i] m = re.match('^([A-Z][A-Z0-9_]*)[.]([A-Za-z_][A-Za-z0-9_]*)$', f) if m is None: self.simple_field.append(None) else: self.simple_field.append((m.group(1),m.group(2))) if len(self.flightmode_list) > 0: # prime the timestamp conversion timestamp_to_days(self.flightmode_list[0][1], self.timeshift) try: reset_state_data() except Exception: pass all_messages = {} while True: msg = mlog.recv_match(type=self.msg_types) if msg is None: break mtype = msg.get_type() if not mtype in all_messages or not isinstance(all_messages[mtype],dict): all_messages[mtype] = msg if mtype not in self.msg_types: continue if self.condition: if not mavutil.evaluate_condition(self.condition, all_messages): continue tdays = timestamp_to_days(msg._timestamp, self.timeshift) if all_false or len(flightmode_selections) == 0: self.add_data(tdays, msg, all_messages) else: if idx < len(self.flightmode_list) and msg._timestamp >= self.flightmode_list[idx][2]: idx += 1 elif (idx < len(flightmode_selections) and flightmode_selections[idx]): self.add_data(tdays, msg, all_messages) def xlim_change_check(self, idx): '''handle xlim change requests from queue''' try: if not self.xlim_pipe[1].poll(): return xlim = self.xlim_pipe[1].recv() if xlim is None: return except Exception: return #print("recv: ", self.graph_num, xlim) if self.ax1 is not None and xlim != self.xlim: self.xlim = xlim self.fig.canvas.toolbar.push_current() #print("setting: ", self.graph_num, xlim) self.ax1.set_xlim(xlim) def xlim_timer(self): '''called every 0.1s to check for xlim change''' if self.closing: return self.xlim_change_check(0) def process(self, flightmode_selections, _flightmodes, block=True): '''process and display graph''' self.msg_types = set() self.multiplier = [] self.field_types = [] self.instance_types = [] self.xlim = None self.flightmode_list = _flightmodes # 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_]+') re_instance = re.compile(r'([A-Z_][A-Z0-9_]+)\[([0-9A-Z_]+)\]') 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) instances = set(re.findall(re_instance, f)) itypes = dict() for (itype,ivalue) in instances: if not itype in itypes: itypes[itype] = set() itypes[itype].add(ivalue) self.instance_types.append(itypes) self.y.append([]) self.x.append([]) self.axes.append(1) self.first_only.append(False) timeshift = self.timeshift for fi in range(0, len(self.mav_list)): mlog = self.mav_list[fi] self.process_mav(mlog, flightmode_selections) def show(self, lenmavlist, block=True, xlim_pipe=None, output=None): '''show graph''' if self.closing: return if xlim_pipe is not None: xlim_pipe[0].close() self.xlim_pipe = xlim_pipe if self.labels is not None: labels = self.labels.split(',') if len(labels) != len(fields)*lenmavlist: print("Number of labels (%u) must match number of fields (%u)" % ( len(labels), len(fields)*lenmavlist)) return else: labels = None for fi in range(0, lenmavlist): 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):] interactive = True if output is not None: interactive = False self.plotit(self.x, self.y, lab, colors=col, title=self.title, interactive=interactive) for i in range(0, len(self.x)): self.x[i] = [] self.y[i] = [] if self.xlim_pipe is not None and output is None: import matplotlib.animation self.ani = matplotlib.animation.FuncAnimation(self.fig, self.xlim_change_check, frames=10, interval=20000, repeat=True, blit=False) if self.xlim_t is None: self.xlim_t = self.fig.canvas.new_timer(interval=100) self.xlim_t.add_callback(self.xlim_timer) self.xlim_t.start() if output is None: plt.draw() plt.show(block=block) elif output.endswith(".html"): import mpld3 html = mpld3.fig_to_html(self.fig) f_out = open(output, 'w') f_out.write(html) f_out.close() else: plt.savefig(output, bbox_inches='tight', dpi=200)
class MavGraph(object): def __init__(self, flightmode_colourmap=None): pass def set_max_message_rate(self, rate_hz): '''set maximum rate we will graph any message''' pass def add_field(self, field): '''add another field to plot''' pass def add_mav(self, mav): '''add another data source to plot''' pass def set_condition(self, condition): '''set graph condition''' pass def set_xaxis(self, xaxis): '''set graph xaxis''' pass def set_title(self, title): '''set graph title''' pass def set_grid(self, enable): '''enable grid''' pass def set_marker(self, marker): '''set graph marker''' pass def set_timeshift(self, timeshift): '''set graph timeshift''' pass def set_legend2(self, legend2): '''set graph legend2''' pass def set_legend2(self, legend2): '''set graph legend''' pass def set_show_flightmode(self, value): '''set to true if flightmodes are to be shown''' pass def set_linestyle(self, linestyle): '''set graph linestyle''' pass def set_multi(self, multi): '''set multiple graph option''' pass def make_format(self, current, other): pass def format_coord(x, y): pass def next_flightmode_colour(self): '''allocate a colour to be used for a flight mode''' pass def flightmode_colour(self, flightmode): '''return colour to be used for rendering a flight mode background''' pass def xlim_changed(self, axsubplot): '''called when x limits are changed''' pass def draw_event(self, evt): '''called on draw events''' pass def close_event(self, evt): '''called on close events''' pass def rescale_yaxis(self, axis): '''rescale Y axes to fit''' pass def button_click(self, event): '''handle button clicks''' pass def plotit(self, x, y, fields, colors=[], title=None, interactive=True): '''plot a set of graphs using date for x axis''' pass def add_data(self, t, msg, vars): '''add some data''' pass def process_mav(self, mlog, flightmode_selections): '''process one file''' pass def xlim_change_check(self, idx): '''handle xlim change requests from queue''' pass def xlim_timer(self): '''called every 0.1s to check for xlim change''' pass def process_mav(self, mlog, flightmode_selections): '''process and display graph''' pass def show(self, lenmavlist, block=True, xlim_pipe=None, output=None): '''show graph''' pass
32
28
19
1
17
1
5
0.08
1
8
1
0
30
52
30
30
608
59
506
177
471
43
465
176
430
40
1
5
149
6,918
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/graphdefinition.py
MAVProxy.modules.lib.graphdefinition.GraphDefinition
class GraphDefinition(object): '''a pre-defined graph''' def __init__(self, name, expression, description, expressions, filename): self.name = name self.expression = expression self.description = description self.expressions = expressions self.filename = filename
class GraphDefinition(object): '''a pre-defined graph''' def __init__(self, name, expression, description, expressions, filename): pass
2
1
6
0
6
0
1
0.14
1
0
0
0
1
5
1
1
8
0
7
7
5
1
7
7
5
1
1
0
1
6,919
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/graph_ui.py
MAVProxy.modules.lib.graph_ui.Graph_UI
class Graph_UI(object): """docstring for ClassName""" def __init__(self, mestate): self.mestate = mestate self.xlim = None global graph_count self.count = graph_count graph_count += 1 self.xlim_pipe = multiproc.Pipe() def display_graph(self, graphdef, flightmode_colourmap=None): '''display a graph''' if 'mestate' in globals(): self.mestate.console.write("Expression: %s\n" % ' '.join(graphdef.expression.split())) else: self.mestate.child_pipe_send_console.send("Expression: %s\n" % ' '.join(graphdef.expression.split())) #mestate.mlog.reduce_by_flightmodes(mestate.flightmode_selections) #setup the graph, then pass to a new process and display self.mg = grapher.MavGraph(flightmode_colourmap) if self.mestate.settings.title is not None: self.mg.set_title(self.mestate.settings.title) else: self.mg.set_title(graphdef.name) if self.mestate.settings.max_rate > 0: self.mg.set_max_message_rate(self.mestate.settings.max_rate) self.mg.set_marker(self.mestate.settings.marker) self.mg.set_condition(self.mestate.settings.condition) self.mg.set_xaxis(self.mestate.settings.xaxis) self.mg.set_linestyle(self.mestate.settings.linestyle) self.mg.set_show_flightmode(self.mestate.settings.show_flightmode) self.mg.set_legend(self.mestate.settings.legend) self.mg.add_mav(copy.copy(self.mestate.mlog)) for f in graphdef.expression.split(): self.mg.add_field(f) self.mg.process(self.mestate.flightmode_selections, self.mestate.mlog._flightmodes) self.lenmavlist = len(self.mg.mav_list) #Important - mg.mav_list is the full logfile and can be very large in size #To avoid slowdowns in Windows (which copies the vars to the new process) #We need to empty this var when we're finished with it self.mg.mav_list = [] child = multiproc.Process(target=self.mg.show, args=[self.lenmavlist,], kwargs={"xlim_pipe" : self.xlim_pipe}) child.start() self.xlim_pipe[1].close() self.mestate.mlog.rewind() def check_xlim_change(self): '''check for new X bounds''' if self.xlim_pipe is None: return None xlim = None try: while self.xlim_pipe[0].poll(): xlim = self.xlim_pipe[0].recv() except Exception: return None if xlim != self.xlim: return xlim return None def set_xlim(self, xlim): '''set new X bounds''' if self.xlim_pipe is not None and self.xlim != xlim: #print("send0: ", graph_count, xlim) try: self.xlim_pipe[0].send(xlim) except IOError: return False self.xlim = xlim return True
class Graph_UI(object): '''docstring for ClassName''' def __init__(self, mestate): pass def display_graph(self, graphdef, flightmode_colourmap=None): '''display a graph''' pass def check_xlim_change(self): '''check for new X bounds''' pass def set_xlim(self, xlim): '''set new X bounds''' pass
5
4
16
0
14
2
4
0.18
1
2
1
0
4
6
4
4
70
4
56
15
50
10
54
15
48
5
1
2
14
6,920
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/geodesic_grid.py
MAVProxy.modules.lib.geodesic_grid._NeighborUmbrella
class _NeighborUmbrella: index_to_attr = ('x', 'y', 'z') def __init__(self, components, v0_c0, v1_c1, v2_c1, v4_c4, v0_c4): self.components = components self.v0_c0 = self.index_to_attr[v0_c0] self.v1_c1 = self.index_to_attr[v1_c1] self.v2_c1 = self.index_to_attr[v2_c1] self.v4_c4 = self.index_to_attr[v4_c4] self.v0_c4 = self.index_to_attr[v0_c4]
class _NeighborUmbrella: def __init__(self, components, v0_c0, v1_c1, v2_c1, v4_c4, v0_c4): pass
2
0
7
0
7
0
1
0
0
0
0
0
1
6
1
1
9
0
9
9
7
0
9
9
7
1
0
0
1
6,921
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/camera_projection.py
MAVProxy.modules.lib.camera_projection.uavxfer
class uavxfer: ''' camera transfer function implementation, thanks to Matt Ridley from CanberraUAV ''' def setCameraParams(self, fu, fv, cu, cv): K = array([[fu, 0.0, cu],[0.0, fv, cv],[0.0, 0.0, 1.0]]) self.setCameraMatrix(K) def setCameraMatrix(self, K): K_i = linalg.inv(K) self.Tk = eye(4,4) self.Tk[:3,:3] = K; self.Tk_i = eye(4,4) self.Tk_i[:3,:3] = K_i def setCameraOrientation(self, roll, pitch, yaw): self.Rc = array(eye(4,4)) self.Rc[:3,:3] = transpose(rotationMatrix(roll, pitch, yaw)) self.Rc_i = linalg.inv(self.Rc) def setPlatformPose(self, north, east, down, roll, pitch, yaw): '''set pose, angles in degrees, 0,0,0 is straight down''' self.Xp = array([north, east, down, 1.0]) self.Rp = array(eye(4,4)) self.Rp[:3,:3] = transpose(rotationMatrix(roll, pitch, yaw)) self.Rp[:3,3] = array([north, east, down]) self.Rp_i = linalg.inv(self.Rp) def setFlatEarth(self, z): self.z_earth = z def worldToPlatform(self, north, east, down): x_w = array([north, east, down, 1.0]) x_p = dot(self.Rp_i, x_w)[:3] return x_p def worldToImage(self, north, east, down): x_w = array([north, east, down, 1.0]) x_p = dot(self.Rp_i, x_w) x_c = dot(self.Rc_i, x_p) x_i = dot(self.Tk, x_c) return x_i[:3]/x_i[2] def platformToWorld(self, north, east, down): x_p = array([north, east, down, 1.0]) x_w = dot(self.Rp, x_p) return x_w def imageToWorld(self, u, v): x_i = array([u, v, 1.0, 0.0]) v_c = dot(self.Tk_i, x_i) v_p = dot(self.Rc, v_c) v_w = dot(self.Rp, v_p) # compute scale for z == z_earth scale = (self.z_earth-self.Xp[2])/v_w[2] #project from platform to ground x_w = scale*v_w + self.Xp; return x_w, scale def __init__(self, fu=200, fv=200, cu=512, cv=480): self.setCameraParams(fu, fv, cu, cv) self.Rc = self.Rc_i = array(eye(4,4)) self.Rp = self.Rp_i = array(eye(4,4)) self.z_earth = -600
class uavxfer: ''' camera transfer function implementation, thanks to Matt Ridley from CanberraUAV ''' def setCameraParams(self, fu, fv, cu, cv): pass def setCameraMatrix(self, K): pass def setCameraOrientation(self, roll, pitch, yaw): pass def setPlatformPose(self, north, east, down, roll, pitch, yaw): '''set pose, angles in degrees, 0,0,0 is straight down''' pass def setFlatEarth(self, z): pass def worldToPlatform(self, north, east, down): pass def worldToImage(self, north, east, down): pass def platformToWorld(self, north, east, down): pass def imageToWorld(self, u, v): pass def __init__(self, fu=200, fv=200, cu=512, cv=480): pass
11
2
5
0
5
0
1
0.12
0
0
0
0
10
8
10
10
64
9
49
35
38
6
49
35
38
1
0
0
10
6,922
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fakegps.py
MAVProxy.modules.mavproxy_fakegps.FakeGPSModule
class FakeGPSModule(mp_module.MPModule): def __init__(self, mpstate): super(FakeGPSModule, self).__init__(mpstate, "fakegps", public = True) self.last_send = time.time() self.FakeGPS_settings = mp_settings.MPSettings([("nsats", int, 16), ("lat", float, -35.363261), ("lon", float, 149.165230), ("alt", float, 584.0), ("yaw", float, 0.0), ("rate", float, 5)]) self.add_command('fakegps', self.cmd_FakeGPS, "fakegps control", ["<status>", "set (FAKEGPSSETTING)"]) self.add_completion_function('(FAKEGPSSETTING)', self.FakeGPS_settings.completion) if mp_util.has_wxpython: map = self.module('map') if map is not None: menu = MPMenuSubMenu('FakeGPS', items=[MPMenuItem('SetPos', 'SetPos', '# fakegps setpos'), MPMenuItem('SetPos (with alt)', 'SetPosAlt', '# fakegps setpos ', handler=MPMenuCallTextDialog(title='Altitude (m)', default=self.mpstate.settings.guidedalt))]) map.add_menu(menu) self.position = mp_util.mp_position() self.update_mpstate() def get_location(self): '''access to location for other modules''' return (self.FakeGPS_settings.lat, self.FakeGPS_settings.lon, self.FakeGPS_settings.alt) def cmd_FakeGPS(self, args): '''fakegps command parser''' usage = "usage: fakegps <set>" if len(args) == 0: print(usage) return if args[0] == "set": self.FakeGPS_settings.command(args[1:]) elif args[0] == "setpos": self.cmd_setpos(args[1:]) else: print(usage) def update_mpstate(self): '''update mpstate position''' self.position.latitude = self.FakeGPS_settings.lat self.position.longitude = self.FakeGPS_settings.lon self.position.altitude = self.FakeGPS_settings.alt self.position.timestamp = time.time() self.mpstate.position = self.position def cmd_setpos(self, args): '''set pos from map''' latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return (lat,lon) = latlon self.FakeGPS_settings.lat = lat self.FakeGPS_settings.lon = lon if len(args) > 0: self.FakeGPS_settings.alt = float(args[0]) self.update_mpstate() def idle_task(self): '''called on idle''' if self.master is None or self.FakeGPS_settings.rate <= 0: return now = time.time() if now - self.last_send < 1.0 / self.FakeGPS_settings.rate: return self.last_send = now gps_lat = self.FakeGPS_settings.lat gps_lon = self.FakeGPS_settings.lon gps_alt = self.FakeGPS_settings.alt gps_vel = [0, 0, 0] gps_week, gps_week_ms = mp_util.get_gps_time(now) time_us = int(now*1.0e6) nsats = self.FakeGPS_settings.nsats if nsats >= 6: fix_type = 3 else: fix_type = 1 self.master.mav.gps_input_send(time_us, 0, 0, gps_week_ms, gps_week, fix_type, int(gps_lat*1.0e7), int(gps_lon*1.0e7), gps_alt, 1.0, 1.0, gps_vel[0], gps_vel[1], gps_vel[2], 0.2, 1.0, 1.0, nsats, int(self.FakeGPS_settings.yaw*100))
class FakeGPSModule(mp_module.MPModule): def __init__(self, mpstate): pass def get_location(self): '''access to location for other modules''' pass def cmd_FakeGPS(self, args): '''fakegps command parser''' pass def update_mpstate(self): '''update mpstate position''' pass def cmd_setpos(self, args): '''set pos from map''' pass def idle_task(self): '''called on idle''' pass
7
5
15
1
13
1
3
0.09
1
8
5
0
6
3
6
44
95
9
81
23
74
7
60
23
53
4
2
2
16
6,923
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fence.py
MAVProxy.modules.mavproxy_fence.FenceModule
class FenceModule(mission_item_protocol.MissionItemProtocolModule): '''uses common MISSION_ITEM protocol base class to provide fence upload/download ''' def __init__(self, mpstate): super(FenceModule, self).__init__(mpstate, "fence", "fence point management (new)", public=True) self.present = False self.enabled = False self.healthy = True def gui_menu_items(self): ret = super(FenceModule, self).gui_menu_items() ret.extend([ MPMenuItem( 'Add Inclusion Circle', 'Add Inclusion Circle', '# fence addcircle inc ', handler=MPMenuCallTextDialog( title='Radius (m)', default=500 ) ), MPMenuItem( 'Add Exclusion Circle', 'Add Exclusion Circle', '# fence addcircle exc ', handler=MPMenuCallTextDialog( title='Radius (m)', default=500 ) ), MPMenuItem( 'Draw Inclusion Poly', 'Draw Inclusion Poly', '# fence draw inc ', ), MPMenuItem( 'Draw Exclusion Poly', 'Draw Exclusion Poly', '# fence draw exc ', ), MPMenuItem( 'Add Return Point', 'Add Return Point', '# fence addreturnpoint', ), ]) return ret def command_name(self): '''command-line command name''' return "fence" # def fence_point(self, i): # return self.wploader.fence_point(i) def count(self): '''return number of waypoints''' return self.wploader.count() def circles_of_type(self, t): '''return a list of Circle fences of a specific type - a single MISSION_ITEM''' ret = [] loader = self.wploader for i in range(0, loader.count()): p = loader.item(i) if p is None: print("Bad loader item (%u)" % i) return [] if p.command != t: continue ret.append(p) return ret def inclusion_circles(self): '''return a list of Circle inclusion fences - a single MISSION_ITEM each''' return self.circles_of_type(mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION) def exclusion_circles(self): '''return a list of Circle exclusion fences - a single MISSION_ITEM each''' return self.circles_of_type(mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION) def polygons_of_type(self, t): '''return a list of polygon fences of a specific type - each a list of items''' ret = [] loader = self.wploader state_outside = 99 state_inside = 98 current_polygon = [] current_expected_length = 0 state = state_outside for i in range(0, loader.count()): p = loader.item(i) if p is None: print("Bad loader item (%u)" % i) return [] if p.command == t: # sanity checks: if p.param1 < 3: print("Bad vertex count (%u) in seq=%u" % (p.param1, p.seq)) continue if state == state_outside: # starting a new polygon state = state_inside current_expected_length = p.param1 current_polygon = [] current_polygon.append(p) continue if state == state_inside: # if the count is different and we're in state # inside then the current polygon is invalid. # Discard it. if p.param1 != current_expected_length: print("Short polygon found, discarding") current_expected_length = p.param1 current_polygon = [] current_polygon.append(p) continue current_polygon.append(p) if len(current_polygon) == current_expected_length: ret.append(current_polygon) state = state_outside continue print("Unknown state (%s)" % str(state)) else: if state == state_inside: if len(current_polygon) != current_expected_length: print("Short polygon found") else: ret.append(current_polygon) state = state_outside continue if state == state_outside: continue print("Unknown state (%s)" % str(state)) return ret def inclusion_polygons(self): '''return a list of polygon inclusion fences - each a list of items''' return self.polygons_of_type(mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION) def exclusion_polygons(self): '''return a list of polygon exclusion fences - each a list of items''' return self.polygons_of_type(mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION) def returnpoint(self): '''return a return point if one exists''' loader = self.wploader for i in range(0, loader.count()): p = loader.item(i) if p is None: print("Bad loader item (%u)" % i) return [] if p.command != mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT: continue return p return None def mission_ftp_name(self): return "@MISSION/fence.dat" @staticmethod def loader_class(): return mavwp.MissionItemProtocol_Fence def mav_mission_type(self): return mavutil.mavlink.MAV_MISSION_TYPE_FENCE def itemstype(self): '''returns description of items in the plural''' return 'fence items' def itemtype(self): '''returns description of item''' return 'fence item' def handle_sys_status(self, m): '''function to handle SYS_STATUS packets, used by both old and new module''' bits = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE present = ((m.onboard_control_sensors_present & bits) == bits) if self.present is False and present is True: self.say("fence present") elif self.present is True and present is False: self.say("fence removed") self.present = present enabled = ((m.onboard_control_sensors_enabled & bits) == bits) if self.enabled is False and enabled is True: self.say("fence enabled") elif self.enabled is True and enabled is False: self.say("fence disabled") self.enabled = enabled healthy = ((m.onboard_control_sensors_health & bits) == bits) if self.healthy is False and healthy is True: self.say("fence OK") elif self.healthy is True and healthy is False: self.say("fence breach") self.healthy = healthy # console output for fence: if not self.present: self.console.set_status('Fence', 'FEN', row=0, fg='black') elif self.enabled is False: self.console.set_status('Fence', 'FEN', row=0, fg='grey') elif self.enabled is True and self.healthy is True: self.console.set_status('Fence', 'FEN', row=0, fg='green') elif self.enabled is True and self.healthy is False: self.console.set_status('Fence', 'FEN', row=0, fg='red') def mavlink_packet(self, m): if m.get_type() == 'SYS_STATUS' and self.message_is_from_primary_vehicle(m): self.handle_sys_status(m) super(FenceModule, self).mavlink_packet(m) def apply_function_to_points(self, function): if not self.check_have_list(): return for i in range(self.wploader.count()): function(i, self.wploader.item(i)) def fence_draw_callback(self, points): '''callback from drawing a fence''' self.add_polyfence(self.drawing_fence_type, points) def add_polyfence(self, fence_type, points): if len(points) < 3: print("Too few points") return items = [] for p in points: m = mavutil.mavlink.MAVLink_mission_item_int_message( self.target_system, self.target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL, # frame fence_type, # command 0, # current 0, # autocontinue len(points), # param1, 0.0, # param2, 0.0, # param3 0.0, # param4 int(p[0]*1e7), # x (latitude) int(p[1]*1e7), # y (longitude) 0, # z (altitude) self.mav_mission_type(), ) items.append(m) self.append(items) self.push_to_vehicle() def push_to_vehicle(self): self.send_all_items() self.wploader.last_change = time.time() def cmd_draw(self, args): '''convenience / compatability / slow learner command to work like the old module - i.e. a single inclusion polyfence''' # TODO: emit this only if there actually are complex fences: if not self.check_have_list(): return if len(args) == 0: print("WARNING! You want 'fence draw inc' or 'fence draw exc'") return if args[0] in ("inc", "inclusion"): self.drawing_fence_type = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION draw_colour = (128, 128, 255) elif args[0] in ("exc", "exclusion"): self.drawing_fence_type = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION draw_colour = (255, 128, 128) else: print("fence draw <inc|inclusion|exc|exclusion>") return if 'draw_lines' not in self.mpstate.map_functions: print("No map drawing available") return self.mpstate.map_functions['draw_lines'](self.fence_draw_callback, colour=draw_colour) print("Drawing fence on map") def cmd_addcircle(self, args): '''adds a circle to the map click position of specific type/radius''' if not self.check_have_list(): return if len(args) < 2: print("Usage: fence setcircle inclusion|exclusion RADIUS") return t = args[0] radius = float(args[1]) latlon = self.mpstate.click_location if latlon is None: print("No click position available") return if t in ["inclusion", "inc"]: command = mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION elif t in ["exclusion", "exc"]: command = mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION else: print("%s is not one of inclusion|exclusion" % t) return m = mavutil.mavlink.MAVLink_mission_item_int_message( self.target_system, self.target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL, # frame command, # command 0, # current 0, # autocontinue radius, # param1, 0.0, # param2, 0.0, # param3 0.0, # param4 int(latlon[0] * 1e7), # x (latitude) int(latlon[1] * 1e7), # y (longitude) 0, # z (altitude) self.mav_mission_type(), ) self.append(m) self.send_all_items() def cmd_addreturnpoint(self, args): '''adds a returnpoint at the map click location''' if not self.check_have_list(): return latlon = self.mpstate.click_location m = mavutil.mavlink.MAVLink_mission_item_int_message( self.target_system, self.target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL, # frame mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT, # command 0, # current 0, # autocontinue 0, # param1, 0.0, # param2, 0.0, # param3 0.0, # param4 int(latlon[0] * 1e7), # x (latitude) int(latlon[1] * 1e7), # y (longitude) 0, # z (altitude) self.mav_mission_type(), ) self.append(m) self.send_all_items() def cmd_addpoly(self, args): '''adds a number of waypoints equally spaced around a circle around click point ''' if not self.check_have_list(): return if len(args) < 1: print("Need at least 1 argument (<inclusion|inc|exclusion|exc>", "<radius>" "<pointcount>", "<rotation>") return t = args[0] count = 4 radius = 20 rotation = 0 if len(args) > 1: radius = float(args[1]) if len(args) > 2: count = int(args[2]) if len(args) > 3: rotation = float(args[3]) if count < 3: print("Invalid count (%s)" % str(count)) return if radius <= 0: print("Invalid radius (%s)" % str(radius)) return latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return if t in ["inclusion", "inc"]: command = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION elif t in ["exclusion", "exc"]: command = mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION else: print("%s is not one of inclusion|exclusion" % t) return items = [] for i in range(0, count): (lat, lon) = mavextra.gps_newpos(latlon[0], latlon[1], 360/float(count)*i + rotation, radius) m = mavutil.mavlink.MAVLink_mission_item_int_message( self.target_system, self.target_component, 0, # seq mavutil.mavlink.MAV_FRAME_GLOBAL, # frame command, # command 0, # current 0, # autocontinue count, # param1, 0.0, # param2, 0.0, # param3 0.0, # param4 int(lat*1e7), # x (latitude) int(lon*1e7), # y (longitude) 0, # z (altitude) self.mav_mission_type(), ) items.append(m) for m in items: self.append(m) self.send_all_items() def cmd_remove(self, args): '''deny remove on fence - requires renumbering etc etc''' print("remove is not currently supported for fence. Try removepolygon_point or removecircle") if not self.check_have_list(): return def removereturnpoint(self, seq): '''remove returnpoint at offset seq''' if not self.check_have_list(): return item = self.wploader.item(seq) if item is None: print("No item %s" % str(seq)) return if item.command != mavutil.mavlink.MAV_CMD_NAV_FENCE_RETURN_POINT: print("Item %u is not a return point" % seq) return self.wploader.remove(item) self.wploader.expected_count -= 1 self.wploader.last_change = time.time() self.send_all_items() def cmd_setcircleradius(self, args): if len(args) < 1: print("fence setcircleradius INDEX RADIUS") return if len(args) < 2: # this one will use the click position: self.setcircleradius(int(args[0])) return self.setcircleradius(int(args[0]), radius=float(args[1])) def cmd_movecircle(self, args): self.movecircle(int(args[0])) def removecircle(self, seq): '''remove circle at offset seq''' if not self.check_have_list(): return item = self.wploader.item(seq) if item is None: print("No item %s" % str(seq)) return if not self.is_circle_item(item): print("Item %u is not a circle" % seq) return self.wploader.remove(item) self.wploader.expected_count -= 1 self.wploader.last_change = time.time() self.send_all_items() def movecircle(self, seq): '''moves circle at polygon_start_seqence to map click point ''' if not self.check_have_list(): return item = self.wploader.item(seq) if item is None: print("No item %s" % str(seq)) return if not self.is_circle_item(item): print("Item %u is not a circle" % seq) return latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return moving_item = self.wploader.item(seq) moving_item.x = latlon[0] moving_item.y = latlon[1] if moving_item.get_type() == "MISSION_ITEM_INT": moving_item.x *= 1e7 moving_item.y *= 1e7 moving_item.x = int(moving_item.x) moving_item.y = int(moving_item.y) self.wploader.set(moving_item, moving_item.seq) self.wploader.last_change = time.time() self.send_single_waypoint(moving_item.seq) def setcircleradius(self, seq, radius=None): '''change radius of circle at seq to radius ''' if not self.check_have_list(): return item = self.wploader.item(seq) if item is None: print("No item %s" % str(seq)) return if not self.is_circle_item(item): print("Item %u is not a circle" % seq) return if radius is None: # calculate radius from clock position: latlon = self.mpstate.click_location if latlon is None: print("No click position available") return item_x = item.x item_y = item.y if item.get_type() == 'MISSION_ITEM_INT': item_x *= 1e-7 item_y *= 1e-7 radius = mavextra.distance_lat_lon(latlon[0], latlon[1], item_x, item_y) elif radius <= 0: print("radius must be positive") return changing_item = self.wploader.item(seq) changing_item.param1 = radius self.wploader.set(changing_item, changing_item.seq) self.wploader.last_change = time.time() self.send_single_waypoint(changing_item.seq) def is_circle_item(self, item): return item.command in [ mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_EXCLUSION, mavutil.mavlink.MAV_CMD_NAV_FENCE_CIRCLE_INCLUSION, ] def find_polygon_point(self, polygon_start_seq, item_offset): '''find polygon point selected on map returns first_item, item_offset ''' first_item = self.wploader.item(polygon_start_seq) if first_item is None: print("No item at %u" % polygon_start_seq) return None, None if not self.is_polygon_item(first_item): print("Item %u is not a polygon vertex" % polygon_start_seq) return None, None original_count = int(first_item.param1) if item_offset == original_count: # selecting closing point on polygon selects first point item_offset = 0 if item_offset > original_count: print("Out-of-range point") return None, None return first_item, item_offset def removepolygon_point(self, polygon_start_seq, item_offset): '''removes item at offset item_offset from the polygon starting at polygon_start_seq''' if not self.check_have_list(): return items_to_set = [] first_item, item_offset = self.find_polygon_point(polygon_start_seq, item_offset) if first_item is None: return original_count = int(first_item.param1) if original_count <= 3: print("Too few points to remove one") return dead_item_walking = self.wploader.item(polygon_start_seq + item_offset) # must reduce count in each of the polygons: for i in range(int(first_item.param1)): item = self.wploader.item(polygon_start_seq+i) if int(item.param1) != original_count: print("Invalid polygon starting at %u (count=%u), point %u (count=%u)" % (polygon_start_seq, original_count, i, int(item.param1))) return item.param1 = item.param1 - 1 items_to_set.append(item) for item in items_to_set: w = item self.wploader.set(w, w.seq) self.wploader.remove(dead_item_walking) self.wploader.expected_count -= 1 self.wploader.last_change = time.time() self.send_all_items() def addpolygon_point(self, polygon_start_seq, item_offset): '''adds item at offset item_offset into the polygon starting at polygon_start_seq''' if not self.check_have_list(): return items_to_set = [] first_item = self.wploader.item(polygon_start_seq) if (first_item.command not in [ mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION ]): print("Item %u is not a polygon vertex" % polygon_start_seq) return original_count = int(first_item.param1) if item_offset >= original_count: print("Out-of-range point") return # increase count in each of the polygon vertexes: for i in range(int(first_item.param1)): item = self.wploader.item(polygon_start_seq+i) if int(item.param1) != original_count: print("Invalid polygon starting at %u (count=%u), point %u (count=%u)" % (polygon_start_seq, original_count, i, int(item.param1))) return item.param1 = item.param1 + 1 items_to_set.append(item) for item in items_to_set: w = item self.wploader.set(w, w.seq) old_item = self.wploader.item(polygon_start_seq + item_offset) new_item = copy.copy(old_item) # reset latitude and longitude of new item to be half-way # between it and the preceeding point if item_offset == 0: prev_item_offset = original_count-1 else: prev_item_offset = item_offset - 1 prev_item = self.wploader.item(polygon_start_seq + prev_item_offset) new_item.x = (old_item.x + prev_item.x)/2 new_item.y = (old_item.y + prev_item.y)/2 self.wploader.insert(polygon_start_seq + item_offset, new_item) self.wploader.expected_count += 1 self.wploader.last_change = time.time() self.send_all_items() def is_polygon_item(self, item): return item.command in [ mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_EXCLUSION, mavutil.mavlink.MAV_CMD_NAV_FENCE_POLYGON_VERTEX_INCLUSION, ] def cmd_removepolygon(self, args): self.removepolygon(int(args[0])) def removepolygon(self, seq): '''remove polygon at offset seq''' if not self.check_have_list(): return first_item = self.wploader.item(seq) if first_item is None: print("Invalid item sequence number (%s)" % seq) return if not self.is_polygon_item(first_item): print("Item %u is not a polygon vertex" % seq) return items_to_remove = [] for i in range(int(first_item.param1)): item = self.wploader.item(seq+i) if item is None: print("No item %s" % str(i)) return if item.param1 != first_item.param1: print("Invalid polygon starting at %u (count=%u), point %u (count=%u)" % (seq, int(first_item.param1), i, int(item.param1))) return if not self.is_polygon_item(item): print("Item %u point %u is not a polygon vertex" % (seq, i)) return items_to_remove.append(item) self.wploader.remove(items_to_remove) self.wploader.expected_count -= len(items_to_remove) self.wploader.last_change = time.time() self.send_all_items() def cmd_movepolypoint(self, args): '''moves item at offset item_offset in polygon starting at polygon_start_seqence to map click point''' if not self.check_have_list(): return if len(args) < 2: print("Need first polygon point and vertex offset") return polygon_start_seq = int(args[0]) item_offset = int(args[1]) first_item, item_offset = self.find_polygon_point(polygon_start_seq, item_offset) if first_item is None: return latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return moving_item = self.wploader.item(polygon_start_seq + item_offset) moving_item.x = latlon[0] moving_item.y = latlon[1] if moving_item.get_type() == "MISSION_ITEM_INT": moving_item.x *= 1e7 moving_item.y *= 1e7 moving_item.x = int(moving_item.x) moving_item.y = int(moving_item.y) self.wploader.set(moving_item, moving_item.seq) self.wploader.last_change = time.time() self.send_single_waypoint(moving_item.seq) def set_fence_enabled(self, do_enable): '''Enable or disable fence''' self.master.mav.command_long_send( self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_DO_FENCE_ENABLE, 0, do_enable, 0, 0, 0, 0, 0, 0) def cmd_enable(self, args): '''enable fence''' self.set_fence_enabled(1) def cmd_disable(self, args): '''disable fence''' self.set_fence_enabled(0) def commands(self): '''returns map from command name to handling function''' ret = super(FenceModule, self).commands() ret.update({ 'addcircle': (self.cmd_addcircle, ["<inclusion|inc|exclusion|exc>", "RADIUS"]), 'movecircle': (self.cmd_movecircle, []), 'setcircleradius': (self.cmd_setcircleradius, ["seq radius"]), 'addpoly': (self.cmd_addpoly, ["<inclusion|inc|exclusion|exc>", "<radius>" "<pointcount>", "<rotation>"]), 'movepolypoint': (self.cmd_movepolypoint, ["POLY_FIRSTPOINT", "POINT_OFFSET"]), 'addreturnpoint': (self.cmd_addreturnpoint, []), 'enable': self.cmd_enable, 'disable': self.cmd_disable, 'draw': self.cmd_draw, 'removepolygon': (self.cmd_removepolygon, ["POLY_FIRSTPOINT"]), }) return ret
class FenceModule(mission_item_protocol.MissionItemProtocolModule): '''uses common MISSION_ITEM protocol base class to provide fence upload/download ''' def __init__(self, mpstate): pass def gui_menu_items(self): pass def command_name(self): '''command-line command name''' pass def count(self): '''return number of waypoints''' pass def circles_of_type(self, t): '''return a list of Circle fences of a specific type - a single MISSION_ITEM''' pass def inclusion_circles(self): '''return a list of Circle inclusion fences - a single MISSION_ITEM each''' pass def exclusion_circles(self): '''return a list of Circle exclusion fences - a single MISSION_ITEM each''' pass def polygons_of_type(self, t): '''return a list of polygon fences of a specific type - each a list of items''' pass def inclusion_polygons(self): '''return a list of polygon inclusion fences - each a list of items''' pass def exclusion_polygons(self): '''return a list of polygon exclusion fences - each a list of items''' pass def returnpoint(self): '''return a return point if one exists''' pass def mission_ftp_name(self): pass @staticmethod def loader_class(): pass def mav_mission_type(self): pass def itemstype(self): '''returns description of items in the plural''' pass def itemtype(self): '''returns description of item''' pass def handle_sys_status(self, m): '''function to handle SYS_STATUS packets, used by both old and new module''' pass def mavlink_packet(self, m): pass def apply_function_to_points(self, function): pass def fence_draw_callback(self, points): '''callback from drawing a fence''' pass def add_polyfence(self, fence_type, points): pass def push_to_vehicle(self): pass def cmd_draw(self, args): '''convenience / compatability / slow learner command to work like the old module - i.e. a single inclusion polyfence''' pass def cmd_addcircle(self, args): '''adds a circle to the map click position of specific type/radius''' pass def cmd_addreturnpoint(self, args): '''adds a returnpoint at the map click location''' pass def cmd_addpoly(self, args): '''adds a number of waypoints equally spaced around a circle around click point ''' pass def cmd_remove(self, args): '''deny remove on fence - requires renumbering etc etc''' pass def removereturnpoint(self, seq): '''remove returnpoint at offset seq''' pass def cmd_setcircleradius(self, args): pass def cmd_movecircle(self, args): pass def removecircle(self, seq): '''remove circle at offset seq''' pass def movecircle(self, seq): '''moves circle at polygon_start_seqence to map click point ''' pass def setcircleradius(self, seq, radius=None): '''change radius of circle at seq to radius ''' pass def is_circle_item(self, item): pass def find_polygon_point(self, polygon_start_seq, item_offset): '''find polygon point selected on map returns first_item, item_offset ''' pass def removepolygon_point(self, polygon_start_seq, item_offset): '''removes item at offset item_offset from the polygon starting at polygon_start_seq''' pass def addpolygon_point(self, polygon_start_seq, item_offset): '''adds item at offset item_offset into the polygon starting at polygon_start_seq''' pass def is_polygon_item(self, item): pass def cmd_removepolygon(self, args): pass def removepolygon_point(self, polygon_start_seq, item_offset): '''remove polygon at offset seq''' pass def cmd_movepolypoint(self, args): '''moves item at offset item_offset in polygon starting at polygon_start_seqence to map click point''' pass def set_fence_enabled(self, do_enable): '''Enable or disable fence''' pass def cmd_enable(self, args): '''enable fence''' pass def cmd_disable(self, args): '''disable fence''' pass def commands(self): '''returns map from command name to handling function''' pass
47
32
16
1
14
2
3
0.19
1
7
2
0
44
4
45
152
777
102
613
133
566
115
470
132
424
13
3
4
150
6,924
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fenceitem_protocol.py
MAVProxy.modules.mavproxy_fenceitem_protocol.FenceModule
class FenceModule(mp_module.MPModule): def __init__(self, mpstate): super(FenceModule, self).__init__(mpstate, "fence", "geo-fence management", public = True) self.fenceloader_by_sysid = {} self.last_fence_breach = 0 self.last_fence_status = 0 self.sysid = 0 self.compid = 0 self.present = False self.enabled = False self.healthy = True self.add_command('fence', self.cmd_fence, "fence item protocol geo-fence management", ["<draw|list|clear|enable|disable|move|remove>", "<load|save> (FILENAME)"]) self.have_list = False if self.continue_mode and self.logdir is not None: fencetxt = os.path.join(self.logdir, 'fence.txt') if os.path.exists(fencetxt): self.fenceloader.load(fencetxt) self.have_list = True print("Loaded fence from %s" % fencetxt) self.menu_added_console = False self.menu_added_map = False if mp_util.has_wxpython: self.menu = MPMenuSubMenu('Fence', items=[MPMenuItem('Clear', 'Clear', '# fence clear'), MPMenuItem('List', 'List', '# fence list'), MPMenuItem('Load', 'Load', '# fence load ', handler=MPMenuCallFileDialog(flags=('open',), title='Fence Load', wildcard='FenceFiles(*.txt,*.fen)|*.txt;*.fen')), MPMenuItem('Save', 'Save', '# fence save ', handler=MPMenuCallFileDialog(flags=('save', 'overwrite_prompt'), title='Fence Save', wildcard='FenceFiles(*.txt,*.fen)|*.txt;*.fen')), MPMenuItem('Draw', 'Draw', '# fence draw')]) @property def fenceloader(self): '''fence loader by sysid''' if not self.target_system in self.fenceloader_by_sysid: self.fenceloader_by_sysid[self.target_system] = mavwp.MAVFenceLoader() return self.fenceloader_by_sysid[self.target_system] def idle_task(self): '''called on idle''' if self.module('console') is not None: if not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu) else: self.menu_added_console = False if self.module('map') is not None: if not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu) else: self.menu_added_map = False def mavlink_packet(self, m): '''handle and incoming mavlink packet''' if self.sysid != 0 and (self.sysid != m.get_srcSystem() or self.compid != m.get_srcComponent()): # ignore messages from other components we haven't locked on to return if m.get_type() == "FENCE_STATUS": self.last_fence_breach = m.breach_time self.last_fence_status = m.breach_status self.compid = m.get_srcComponent() self.sysid = m.get_srcSystem() elif m.get_type() in ['SYS_STATUS']: bits = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE present = ((m.onboard_control_sensors_present & bits) == bits) if self.present == False and present == True: self.say("fence present") self.compid = m.get_srcComponent() self.sysid = m.get_srcSystem() elif self.present == True and present == False: self.say("fence removed") self.present = present enabled = ((m.onboard_control_sensors_enabled & bits) == bits) if self.enabled == False and enabled == True: self.say("fence enabled") self.compid = m.get_srcComponent() self.sysid = m.get_srcSystem() elif self.enabled == True and enabled == False: self.say("fence disabled") self.enabled = enabled healthy = ((m.onboard_control_sensors_health & bits) == bits) if self.healthy == False and healthy == True: self.say("fence OK") elif self.healthy == True and healthy == False: self.say("fence breach") self.healthy = healthy #console output for fence: if not self.present: self.console.set_status('Fence', 'FEN', row=0, fg='black') elif self.enabled == False: self.console.set_status('Fence', 'FEN', row=0, fg='grey') elif self.enabled == True and self.healthy == True: self.console.set_status('Fence', 'FEN', row=0, fg='green') elif self.enabled == True and self.healthy == False: self.console.set_status('Fence', 'FEN', row=0, fg='red') def set_fence_enabled(self, do_enable): '''Enable or disable fence''' self.master.mav.command_long_send( self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_DO_FENCE_ENABLE, 0, do_enable, 0, 0, 0, 0, 0, 0) def cmd_fence_move(self, args): '''handle fencepoint move''' if len(args) < 1: print("Usage: fence move FENCEPOINTNUM") return if not self.have_list: print("Please list fence points first") return idx = int(args[0]) if idx <= 0 or idx > self.fenceloader.count(): print("Invalid fence point number %u" % idx) return latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return # note we don't subtract 1, as first fence point is the return point self.fenceloader.move(idx, latlon[0], latlon[1]) if self.send_fence(): print("Moved fence point %u" % idx) def cmd_fence_remove(self, args): '''handle fencepoint remove''' if len(args) < 1: print("Usage: fence remove FENCEPOINTNUM") return if not self.have_list: print("Please list fence points first") return idx = int(args[0]) if idx <= 0 or idx > self.fenceloader.count(): print("Invalid fence point number %u" % idx) return # note we don't subtract 1, as first fence point is the return point self.fenceloader.remove(idx) if self.send_fence(): print("Removed fence point %u" % idx) else: print("Failed to remove fence point %u" % idx) def cmd_fence(self, args): '''fence commands''' if len(args) < 1: self.print_usage() return if args[0] == "enable": self.set_fence_enabled(1) elif args[0] == "disable": self.set_fence_enabled(0) elif args[0] == "load": if len(args) != 2: print("usage: fence load <filename>") return self.load_fence(args[1]) elif args[0] == "list": self.list_fence(None) elif args[0] == "move": self.cmd_fence_move(args[1:]) elif args[0] == "remove": self.cmd_fence_remove(args[1:]) elif args[0] == "save": if len(args) != 2: print("usage: fence save <filename>") return self.list_fence(args[1]) elif args[0] == "show": if len(args) != 2: print("usage: fence show <filename>") return self.fenceloader.load(args[1]) self.have_list = True elif args[0] == "draw": if not 'draw_lines' in self.mpstate.map_functions: print("No map drawing available") return self.mpstate.map_functions['draw_lines'](self.fence_draw_callback) print("Drawing fence on map") elif args[0] == "clear": self.param_set('FENCE_TOTAL', 0, 3) else: self.print_usage() def load_fence(self, filename): '''load fence points from a file''' try: self.fenceloader.target_system = self.target_system self.fenceloader.target_component = self.target_component self.fenceloader.load(filename.strip('"')) except Exception as msg: print("Unable to load %s - %s" % (filename, msg)) return print("Loaded %u geo-fence points from %s" % (self.fenceloader.count(), filename)) self.send_fence() def send_fence(self): '''send fence points from fenceloader''' # must disable geo-fencing when loading self.fenceloader.target_system = self.target_system self.fenceloader.target_component = self.target_component self.fenceloader.reindex() action = self.get_mav_param('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE) self.param_set('FENCE_ACTION', mavutil.mavlink.FENCE_ACTION_NONE, 3) self.param_set('FENCE_TOTAL', self.fenceloader.count(), 3) for i in range(self.fenceloader.count()): p = self.fenceloader.point(i) self.master.mav.send(p) p2 = self.fetch_fence_point(i) if p2 is None: self.param_set('FENCE_ACTION', action, 3) return False if (p.idx != p2.idx or abs(p.lat - p2.lat) >= 0.00003 or abs(p.lng - p2.lng) >= 0.00003): print("Failed to send fence point %u" % i) self.param_set('FENCE_ACTION', action, 3) return False self.param_set('FENCE_ACTION', action, 3) return True def fetch_fence_point(self ,i): '''fetch one fence point''' self.master.mav.fence_fetch_point_send(self.target_system, self.target_component, i) tstart = time.time() p = None while time.time() - tstart < 3: p = self.master.recv_match(type='FENCE_POINT', blocking=False) if p is not None: break time.sleep(0.1) continue if p is None: self.console.error("Failed to fetch point %u" % i) return None return p def fence_draw_callback(self, points): '''callback from drawing a fence''' self.fenceloader.clear() if len(points) < 3: return self.fenceloader.target_system = self.target_system self.fenceloader.target_component = self.target_component bounds = mp_util.polygon_bounds(points) (lat, lon, width, height) = bounds center = (lat+width/2, lon+height/2) self.fenceloader.add_latlon(center[0], center[1]) for p in points: self.fenceloader.add_latlon(p[0], p[1]) # close it self.fenceloader.add_latlon(points[0][0], points[0][1]) self.send_fence() self.have_list = True def list_fence(self, filename): '''list fence points, optionally saving to a file''' self.fenceloader.clear() count = self.get_mav_param('FENCE_TOTAL', 0) if count == 0: print("No geo-fence points") return for i in range(int(count)): for t in range(6): p = self.fetch_fence_point(i) if p is None: print("retrying %u" % i) continue break self.fenceloader.add(p) if filename is not None: try: self.fenceloader.save(filename.strip('"')) except Exception as msg: print("Unable to save %s - %s" % (filename, msg)) return print("Saved %u geo-fence points to %s" % (self.fenceloader.count(), filename)) else: for i in range(self.fenceloader.count()): p = self.fenceloader.point(i) self.console.writeln("lat=%f lng=%f" % (p.lat, p.lng)) if self.status.logdir is not None: fname = 'fence.txt' if self.target_system > 1: fname = 'fence_%u.txt' % self.target_system fencetxt = os.path.join(self.status.logdir, fname) self.fenceloader.save(fencetxt.strip('"')) print("Saved fence to %s" % fencetxt) self.have_list = True def print_usage(self): print("usage: fence <enable|disable|list|load|save|clear|draw|move|remove>") def unload(self): self.remove_command("fence") if self.module('console') is not None and self.menu_added_console: self.menu_added_console = False self.module('console').remove_menu(self.menu) if self.module('map') is not None and self.menu_added_map: self.menu_added_map = False self.module('map').remove_menu(self.menu) super(FenceModule, self).unload()
class FenceModule(mp_module.MPModule): def __init__(self, mpstate): pass @property def fenceloader(self): '''fence loader by sysid''' pass def idle_task(self): '''called on idle''' pass def mavlink_packet(self, m): '''handle and incoming mavlink packet''' pass def set_fence_enabled(self, do_enable): '''Enable or disable fence''' pass def cmd_fence_move(self, args): '''handle fencepoint move''' pass def cmd_fence_remove(self, args): '''handle fencepoint remove''' pass def cmd_fence_move(self, args): '''fence commands''' pass def load_fence(self, filename): '''load fence points from a file''' pass def send_fence(self): '''send fence points from fenceloader''' pass def fetch_fence_point(self ,i): '''fetch one fence point''' pass def fence_draw_callback(self, points): '''callback from drawing a fence''' pass def list_fence(self, filename): '''list fence points, optionally saving to a file''' pass def print_usage(self): pass def unload(self): pass
17
12
21
1
19
2
5
0.08
1
7
3
0
15
13
15
53
328
29
281
56
264
23
238
52
222
16
2
3
80
6,925
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fieldcheck/__init__.py
MAVProxy.modules.mavproxy_fieldcheck.FieldCMAC
class FieldCMAC(FieldCheck): lc_name = "cmac" location = mavutil.location(-35.363261, 149.165230, 584, 353)
class FieldCMAC(FieldCheck): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
3
0
3
3
2
0
3
3
2
0
2
0
0
6,926
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fieldcheck/__init__.py
MAVProxy.modules.mavproxy_fieldcheck.FieldCheck
class FieldCheck(object): def __init__(self): self.is_armed = False self.last_fence_fetch = 0 self.last_mission_fetch = 0 self.last_rally_fetch = 0 self.done_heartbeat_check = 0 # an altitude should always be within a few metres of when disarmed: self.disarmed_alt = 584 self.rate_period = mavutil.periodic_event(1.0/15) self.done_map_menu = False def close_to(self, loc1): ret = self.get_distance(loc1, self.location) print("Distance to %s: %um" % (self.lc_name, ret)) return ret < 100 # swiped from ArduPilot's common.py: def get_distance(self, loc1, loc2): """Get ground distance between two locations.""" dlat = loc2.lat - loc1.lat try: dlong = loc2.lng - loc1.lng except AttributeError: dlong = loc2.lon - loc1.lon return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5 def flightdata_filepath(self, filename): if os.path.exists(filename): return filename return pkg_resources.resource_filename(__name__, filename) def loadRally(self): filepath = self.flightdata_filepath(self.fc_settings.rally_filename) rallymod = self.module('rally') rallymod.cmd_load([filepath]) def loadFoamyFence(self): filepath = self.flightdata_filepath(self.fc_settings.fence_filename) fencemod = self.module('fence') fencemod.cmd_load([filepath]) def loadFoamyMission(self, filename): filepath = self.flightdata_filepath(filename) wpmod = self.module('wp') wpmod.cmd_load([filepath]) def loadFoamyMissionCW(self): self.loadFoamyMission(self.fc_settings.mission_filename_cw) def loadFoamyMissionCCW(self): self.loadFoamyMission(self.fc_settings.mission_filename_ccw) def fixMissionRallyFence(self): self.loadFoamyMissionCW() self.loadFoamyFence() self.loadRally() def fixEVERYTHING(self): self.loadFoamyMissionCW() self.loadFoamyFence() self.loadRally() self.check_parameters(fix=True) def whinge(self, message): self.console.writeln("FC:%s %s" % (self.lc_name, message,)) def check_parameters(self, fix=False): '''check key parameters''' want_values = { "FENCE_ENABLE": 1, "FENCE_ACTION": 1, # 4 is break-or-land on Copter! "FENCE_ALT_MAX": self.fc_settings.param_fence_maxalt, "THR_FAILSAFE": 1, "FS_SHORT_ACTN": 0, "FS_LONG_ACTN": 1, } if self.vehicle_type == mavutil.mavlink.MAV_TYPE_FIXED_WING: want_values["FENCE_ACTION"] = 1 # RTL want_values["RTL_AUTOLAND"] = 2 # go directly to landing sequence elif self.vehicle_type == mavutil.mavlink.MAV_TYPE_QUADROTOR: want_values["FENCE_ACTION"] = 4 # Brake or RTL ret = True for key in want_values.keys(): want = want_values[key] got = self.mav_param.get(key, None) if got is None: self.whinge("No param %s" % key) ret = False if got != want: self.whinge('%s should be %f (not %s)' % (key, want, got)) ret = False if fix: self.whinge('Setting %s to %f' % (key, want)) self.mav_param.mavset(self.master, key, want, retries=3) # ensure there is a fence enable/disable switch configured: required_options = { 11: "Fence Enable/Disable", } for required_option in required_options.keys(): found = False for chan in range(1, 17): rc_option_param_name = f"RC{chan}_OPTION" got = self.mav_param.get(rc_option_param_name, None) if got == required_option: found = True break if not found: self.whinge("RC channel option %u (%s) must be configured" % (required_option, required_options[required_option])) ret = False return ret def check_fence_location(self): fencemod = self.module('fence') if fencemod is None: self.whinge("Fence module not loaded") return False if not fencemod.check_have_list(): if self.is_armed: return False now = time.time() if now - self.last_fence_fetch > 10: self.last_fence_fetch = now self.whinge("Running 'fence list'") fencemod.cmd_list(None) return False global fencepoints_good global count fencepoints_good = True count = 0 def fencepoint_checker(offset, p): global fencepoints_good global count if isinstance(p, mavutil.mavlink.MAVLink_mission_item_message): lat = p.x lng = p.y elif isinstance(p, mavutil.mavlink.MAVLink_mission_item_int_message): lat = p.x * 1e-7 lng = p.y * 1e-7 else: raise TypeError(f"What's a {type(p)}?") loc = mavutil.location(lat, lng) dist = self.get_distance(self.location, loc) if dist > self.fc_settings.fence_maxdist: if fencepoints_good: self.whinge("Fencepoint %i too far away (%fm)" % (offset, dist)) fencepoints_good = False count += 1 fencemod.apply_function_to_points(fencepoint_checker) min_fence_points = 5 if count < min_fence_points: self.whinge(f"Too few fence points; {count} < {min_fence_points}") return False return fencepoints_good def check_rally(self): rallymod = self.module('rally') if rallymod is None: self.whinge("No rally module") return False if not rallymod.check_have_list(): self.whinge("No rally list") if self.is_armed: return False now = time.time() if now - self.last_rally_fetch > 10: self.last_rally_fetch = now self.whinge("Running 'rally list'") rallymod.cmd_list([]) return False count = rallymod.rally_count() if count < 1: self.whinge("Too few rally points") return False rtl_loiter_radius = self.mav_param.get("RTL_RADIUS", None) if rtl_loiter_radius is None or rtl_loiter_radius == 0: rtl_loiter_radius = self.mav_param.get("WP_LOITER_RAD") if rtl_loiter_radius is None: self.whinge("No RTL loiter radius available") return False ret = True for i in range(count): r = rallymod.rally_point(i) loc = mavutil.location(r.lat/10000000.0, r.lng/10000000.0) dist = self.get_distance(self.location, loc) if dist > self.fc_settings.rally_maxdist: self.whinge("Rally Point %i too far away (%fm)" % (i, dist)) ret = False # ensure we won't loiter over the runway when doing # rally loitering: # print("dist=%f rtl_loiter_radius=%f", dist, rtl_loiter_radius) if dist < rtl_loiter_radius+30: # add a few metres of slop self.whinge("Rally Point %i too close (%fm)" % (i, dist)) ret = False return ret def check_fence_health(self): try: sys_status = self.master.messages['SYS_STATUS'] except Exception: return False bits = mavutil.mavlink.MAV_SYS_STATUS_GEOFENCE present = ((sys_status.onboard_control_sensors_present & bits) == bits) enabled = ((sys_status.onboard_control_sensors_enabled & bits) == bits) healthy = ((sys_status.onboard_control_sensors_health & bits) == bits) if not present or not enabled: self.console.writeln('Fence should be enabled', fg='blue') return False if not healthy: self.console.writeln('Fence unhealthy', fg='blue') return False return True def check_fence(self): ret = True if not self.check_fence_health(): ret = False if not self.check_fence_location(): ret = False return ret def check_altitude(self): if self.is_armed: return True try: gpi = self.master.messages['GLOBAL_POSITION_INT'] except Exception: return False max_delta = 10 current_alt = gpi.alt / 1000 if abs(current_alt - self.disarmed_alt) > max_delta: self.whinge("Altitude (%f) not within %fm of %fm" % (current_alt, max_delta, self.disarmed_alt)) return False return True def check_mission(self): wpmod = self.module('wp') if wpmod is None: self.whinge("No waypoint module") return False count = wpmod.wploader.count() if count == 0: self.whinge("No waypoints") if self.is_armed: return False now = time.time() if now - self.last_mission_fetch > 10: self.whinge("Requesting waypoints") self.last_mission_fetch = now wpmod.wp_op = "list" wpmod.master.waypoint_request_list_send() return False if count < 2: self.whinge("Too few waypoints") return False ret = True for i in range(count): if i == 0: # skip home continue w = wpmod.wploader.wp(i) if w.command not in [mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, mavutil.mavlink.MAV_CMD_NAV_LAND]: continue loc = mavutil.location(w.x, w.y) dist = self.get_distance(self.location, loc) if dist > self.fc_settings.wp_maxdist: self.whinge("Waypoint %i too far away (%fm)" % (i, dist)) ret = False return ret def check_status(self): try: hb = self.master.messages['HEARTBEAT'] mc = self.master.messages['MISSION_CURRENT'] except Exception: return False self.is_armed = (hb.base_mode & mavutil.mavlink.MAV_MODE_FLAG_SAFETY_ARMED) != 0 if not self.is_armed and hb.custom_mode == 0: # disarmed in MANUAL we should be at WP 0 if mc.seq > 1: self.whinge('Incorrect WP %u' % mc.seq) return False return True def check(self): success = True if self.master.messages.get('HEARTBEAT') is None: self.whinge("Waiting for heartbeat") success = False return if not self.check_status(): success = False if not self.check_parameters(): success = False if not self.check_fence(): success = False if not self.check_mission(): success = False if not self.check_rally(): success = False if not self.check_altitude(): success = False if not success: self.whinge("CHECKS BAD") return if not self.is_armed: self.whinge("CHECKS GOOD") def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if not self.done_heartbeat_check: m = self.master.messages.get('HEARTBEAT') if m is not None: self.vehicle_type = m.type self.check() self.done_heartbeat_check = True if self.rate_period.trigger(): self.check() def check_map_menu(self): # make the initial map menu if not mp_util.has_wxpython: return if self.done_map_menu: if not self.module('map'): self.done_map_menu = False return if self.module('map'): self.menu = MPMenuSubMenu('FieldCheck', items=[ MPMenuItem('Load foamy mission CW', 'Load foamy mission CW', '# fieldcheck loadFoamyMissionCW'), MPMenuItem('Load foamy mission CCW', 'Load foamy mission CCW', '# fieldcheck loadFoamyMissionCCW'), MPMenuItem('Load rally points', 'Load rally points', '# fieldcheck loadRally'), MPMenuItem('Load foamy fence', 'Load foamy fence', '# fieldcheck loadFoamyFence'), MPMenuItem('Fix Mission+Rally+Fence', 'Fix Mission+Rally+Fence', '# fieldcheck fixMissionRallyFence'), MPMenuItem('Fix EVERYTHING', 'Fix EVERYTHING', '# fieldcheck fixEVERYTHING'), ]) self.module('map').add_menu(self.menu) self.done_map_menu = True def idle_task(self): self.check_map_menu() def FC_MPSetting(self, name, atype, default, description): # xname = "fc_%s_%s" % (self.lc_name, name) return MPSetting(name, atype, default, description) def select(self): self.fc_settings = MPSettings( [ self.FC_MPSetting('fence_maxdist', float, 1000, 'Max FencePoint Distance from location'), self.FC_MPSetting('wp_maxdist', float, 500, 'Max WayPoint Distance from location'), self.FC_MPSetting('rally_maxdist', float, 200, 'Max Rally Distance from location'), self.FC_MPSetting('param_fence_maxalt', float, 120, 'Value parameter FENCE_MAXALT should have'), self.FC_MPSetting('rally_filename', str, "%s-foamy-rally.txt" % self.lc_name, "%s Rally Point File" % self.lc_name), self.FC_MPSetting('fence_filename', str, "%s-foamy-fence.txt" % self.lc_name, "%s Fence File" % self.lc_name), self.FC_MPSetting('mission_filename_cw', str, "%s-foamy-mission-cw.txt" % self.lc_name, "%s Mission (CW) File" % self.lc_name), self.FC_MPSetting('mission_filename_ccw', str, "%s-foamy-mission-ccw.txt" % self.lc_name, "%s Mission (CCW) File" % self.lc_name), ]) self.x.add_completion_function('(FIELDCHECKCHECKSETTING)', self.fc_settings.completion) self.x.add_command('fieldcheck', self.cmd_fieldcheck, 'field check control', ['check', 'set (FIELDCHECKSETTING)']) def cmd_fieldcheck(self, args): '''handle fieldcheck commands''' usage = 'Usage: fieldcheck <set>' if len(args) == 0: print(usage) return if args[0] == "set": self.fc_settings.command(args[1:]) elif args[0] == "loadFoamyMissionCW": self.loadFoamyMissionCW() elif args[0] == "loadFoamyMissionCCW": self.loadFoamyMissionCCW() elif args[0] == "loadFoamyFence": self.loadFoamyFence() elif args[0] == "loadRally": self.loadRally() elif args[0] == "fixMissionRallyFence": self.fixMissionRallyFence() elif args[0] == "fixEVERYTHING": self.fixEVERYTHING() elif args[0] == "check": self.check() else: print(usage) return
class FieldCheck(object): def __init__(self): pass def close_to(self, loc1): pass def get_distance(self, loc1, loc2): '''Get ground distance between two locations.''' pass def flightdata_filepath(self, filename): pass def loadRally(self): pass def loadFoamyFence(self): pass def loadFoamyMission(self, filename): pass def loadFoamyMissionCW(self): pass def loadFoamyMissionCCW(self): pass def fixMissionRallyFence(self): pass def fixEVERYTHING(self): pass def whinge(self, message): pass def check_parameters(self, fix=False): '''check key parameters''' pass def check_fence_location(self): pass def fencepoint_checker(offset, p): pass def check_rally(self): pass def check_fence_health(self): pass def check_fence_location(self): pass def check_altitude(self): pass def check_mission(self): pass def check_status(self): pass def check_parameters(self, fix=False): pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass def check_map_menu(self): pass def idle_task(self): pass def FC_MPSetting(self, name, atype, default, description): pass def select(self): pass def cmd_fieldcheck(self, args): '''handle fieldcheck commands''' pass
29
4
16
1
15
1
4
0.06
1
11
4
3
27
12
27
27
457
52
391
101
358
25
309
100
276
11
1
3
104
6,927
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fieldcheck/__init__.py
MAVProxy.modules.mavproxy_fieldcheck.FieldCheckModule
class FieldCheckModule(mp_module.MPModule): def __init__(self, mpstate): super(FieldCheckModule, self).__init__(mpstate, "FieldCheck", "FieldCheck Checks", public=True) self.fields = [ FieldCMAC(), FieldSpringValley(), FieldSpringValleyBottom(), ] self.field = None def select_field(self, field): self.field = field self.field.master = self.master self.field.mav_param = self.mav_param self.field.console = self.console self.field.module = self.module self.field.x = self self.field.select() def whinge(self, message): self.console.writeln("FC: %s" % (message,)) def try_select_field(self, loc): for field in self.fields: if field.close_to(loc): self.whinge("Selecting field (%s)" % field.lc_name) self.select_field(field) def idle_task(self): '''run periodic tasks''' if self.field is not None: self.field.idle_task() def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if self.field is None: # attempt to select field automatically based on location mtype = m.get_type() if mtype == "GPS_RAW_INT": if m.fix_type >= 3: lat = m.lat lon = m.lon here = mavutil.location(lat*1e-7, lon*1e-7, 0, 0) self.try_select_field(here) if self.field is None: return self.field.mavlink_packet(m)
class FieldCheckModule(mp_module.MPModule): def __init__(self, mpstate): pass def select_field(self, field): pass def whinge(self, message): pass def try_select_field(self, loc): pass def idle_task(self): '''run periodic tasks''' pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass
7
2
8
1
7
1
2
0.07
1
4
3
0
6
2
6
44
53
8
42
14
35
3
35
14
28
5
2
3
13
6,928
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fieldcheck/__init__.py
MAVProxy.modules.mavproxy_fieldcheck.FieldSpringValley
class FieldSpringValley(FieldCheck): location = mavutil.location(-35.281315, 149.005329, 581, 280) lc_name = "springvalley"
class FieldSpringValley(FieldCheck): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
3
0
3
3
2
0
3
3
2
0
2
0
0
6,929
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_fieldcheck/__init__.py
MAVProxy.modules.mavproxy_fieldcheck.FieldSpringValleyBottom
class FieldSpringValleyBottom(FieldCheck): location = mavutil.location(-35.2824450, 149.0053668, 593, 0) lc_name = "springvalleybottom"
class FieldSpringValleyBottom(FieldCheck): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
27
3
0
3
3
2
0
3
3
2
0
2
0
0
6,930
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_firmware.py
MAVProxy.modules.mavproxy_firmware.FirmwareModule
class FirmwareModule(mp_module.MPModule): def __init__(self, mpstate): super(FirmwareModule, self).__init__(mpstate, "firmware", "firmware handling", public = True) self.firmware_settings = mp_settings.MPSettings( [('uploader', str, "uploader.py"), ]) self.add_command('fw', self.cmd_fw, "firmware handling", ["<manifest> (OPT)", "list <filterterm...>", "flash <filterterm...>", "set (FIRMWARESETTING)", "flashfile FILENAME"]) self.add_completion_function('(FIRMWARESETTING)', self.firmware_settings.completion) self.downloaders_lock = threading.Lock() self.downloaders = {} self.manifests_parse() def usage(self): '''show help on a command line options''' return '''Usage: fw <manifest|set|list|flash|flashfile> # Use the column headings from "list" as filter terms # e.g. list latest releases for PX4-v2 platform: fw list latest=1 platform=PX4-v2 # e.g. download most recent official PX4-v2 release for quadcopters: fw download releasetype=OFFICIAL frame=quad platform=PX4-v2 ''' def cmd_fw_help(self): '''show help on fw command''' print(self.usage()) def cmd_fw(self, args): '''execute command defined in args''' if len(args) == 0: print(self.usage()) return rest = args[1:] if args[0] == "manifest": self.cmd_fw_manifest(rest) elif args[0] == "list": self.cmd_fw_list(rest) elif args[0] == "flash": self.cmd_flash(rest) elif args[0] == "set": self.firmware_settings.command(args[1:]) elif args[0] == "download": self.cmd_fw_download(rest) elif args[0] in ["help","usage"]: self.cmd_fw_help(rest) elif args[0] == "flashfile": self.cmd_flashfile(rest) else: print(self.usage()) def frame_from_firmware(self, firmware): '''extract information from firmware, return pretty string to user''' # see Tools/scripts/generate-manifest for this map: frame_to_mavlink_dict = { "quad": "QUADROTOR", "hexa": "HEXAROTOR", "y6": "ARDUPILOT_Y6", "tri": "TRICOPTER", "octa": "OCTOROTOR", "octa-quad": "ARDUPILOT_OCTAQUAD", "heli": "HELICOPTER", "Plane": "FIXED_WING", "Tracker": "ANTENNA_TRACKER", "Rover": "GROUND_ROVER", "PX4IO": "ARDUPILOT_PX4IO", } mavlink_to_frame_dict = { v : k for k,v in frame_to_mavlink_dict.items() } x = firmware["mav-type"] if firmware["mav-autopilot"] != "ARDUPILOTMEGA": return x if x in mavlink_to_frame_dict: return mavlink_to_frame_dict[x] return x def semver_from_firmware(self, firmware): '''Extract a tuple of (major,minor,patch) from a firmware instance''' version = firmware.get("mav-firmware-version-major",None) if version is None: return (None,None,None) return (firmware["mav-firmware-version-major"], firmware["mav-firmware-version-minor"], firmware["mav-firmware-version-patch"]) def row_is_filtered(self, row_subs, filters): '''returns True if row should NOT be included according to filters''' for filtername in filters: filtervalue = filters[filtername] if filtername in row_subs: row_subs_value = row_subs[filtername] if str(row_subs_value) != str(filtervalue): return True else: print("fw: Unknown filter keyword (%s)" % (filtername,)) return False def filters_from_args(self, args): '''take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments''' filters = dict() remainder = [] for arg in args: try: equals = arg.index('=') # anything ofthe form key-value is taken as a filter filters[arg[0:equals]] = arg[equals+1:]; except ValueError: remainder.append(arg) return (filters,remainder) def all_firmwares(self): ''' return firmware entries from all manifests''' all = [] for manifest in self.manifests: for firmware in manifest["firmware"]: all.append(firmware) return all def rows_for_firmwares(self, firmwares): '''provide user-readable text for a firmware entry''' rows = [] i = 0 for firmware in firmwares: frame = self.frame_from_firmware(firmware) row = { "seq": i, "platform": firmware["platform"], "frame": frame, # "type": firmware["mav-type"], "releasetype": firmware["mav-firmware-version-type"], "latest": firmware["latest"], "git-sha": firmware["git-sha"][0:7], "format": firmware["format"], "_firmware": firmware, } (major,minor,patch) = self.semver_from_firmware(firmware) if major is None: row["version"] = "" row["major"] = "" row["minor"] = "" row["patch"] = "" else: row["version"] = firmware["mav-firmware-version"] row["major"] = major row["minor"] = minor row["patch"] = patch i += 1 rows.append(row) return rows def filter_rows(self, filters, rows): '''returns rows as filtered by filters''' ret = [] for row in rows: if not self.row_is_filtered(row, filters): ret.append(row) return ret def filtered_rows_from_args(self, args): '''extracts filters from args, rows from manifests, returns filtered rows''' if len(self.manifests) == 0: print("fw: No manifests downloaded. Try 'fw manifest download'") return None (filters,remainder) = self.filters_from_args(args) all = self.all_firmwares() rows = self.rows_for_firmwares(all) filtered = self.filter_rows(filters, rows) return (filtered, remainder) def cmd_flashfile(self, args): filename = args[0] subprocess.check_call([self.firmware_settings.uploader, filename]) def cmd_flash(self, args): '''cmd handler for flash''' stuff = self.filtered_rows_from_args(args) (filtered, remainder) = stuff if stuff is None: print("Nothing returned from filter") return (filtered, remainder) = stuff if len(filtered) != 1: print("Filter must return single firmware") self.list_firmwares(filtered) print("Filter must return single firmware") return firmware = filtered[0]["_firmware"] try: filename = self.download_firmware(firmware) except Exception as e: print("fw: download failed") print(e) return subprocess.check_call([self.firmware_settings.uploader, filename]) return def cmd_fw_list(self, args): '''cmd handler for list''' stuff = self.filtered_rows_from_args(args) if stuff is None: return (filtered, remainder) = stuff self.list_firmwares(filtered) def list_firmwares(self, filtered): print("") print(" seq platform frame major.minor.patch releasetype latest git-sha format") for row in filtered: print("{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}".format(**row)) print(" seq platform frame major.minor.patch releasetype latest git-sha format") def cmd_fw_download(self, args): '''cmd handler for downloading firmware''' stuff = self.filtered_rows_from_args(args) if stuff is None: return (filtered, remainder) = stuff if len(filtered) == 0: print("fw: No firmware specified") return if len(filtered) > 1: print("fw: No single firmware specified") return try: self.download_firmware(filtered[0]["_firmware"]) except Exception as e: print("fw: download failed") print(e) def download_firmware(self, firmware, filename=None): url = firmware["url"] print("fw: URL: %s" % (url,)) if filename is None: filename = os.path.basename(url) files = [] files.append((url,filename)) child = multiproc.Process(target=mp_util.download_files, args=(files,)) child.start() tstart = time.time() while True: if time.time() - tstart > 60: print("Download timeout") if not child.is_alive(): break print("Waiting for download to complete...") time.sleep(1) return filename def fw_manifest_usage(self): '''return help on manifest subcommand''' return("Usage: fw manifest <list|download|purge|status>") def cmd_fw_manifest_help(self): '''show help on manifest subcommand''' print(self.fw_manifest_usage()) def find_manifests(self): '''locate manifests and return filepaths thereof''' manifest_dir = mp_util.dot_mavproxy() ret = [] for file in os.listdir(manifest_dir): try: file.index("manifest") ret.append(os.path.join(manifest_dir,file)) except ValueError: pass return ret def cmd_fw_manifest_list(self): '''list manifests''' for filepath in self.find_manifests(): print(filepath) def cmd_fw_manifest_load(self): '''handle command to load manifests - hidden command since these should only change with fw commands''' self.manifests_parse() def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' for filepath in self.find_manifests(): os.unlink(filepath) self.manifests_parse() def cmd_fw_manifest(self, args): '''cmd handler for manipulating manifests''' if len(args) == 0: print(self.fw_manifest_usage()) return rest = args[1:] if args[0] == "download": return self.manifest_download() if args[0] == "list": return self.cmd_fw_manifest_list() if args[0] == "status": return self.cmd_fw_manifest_status() if args[0] == "load": return self.cmd_fw_manifest_load() if args[0] == "purge": return self.cmd_fw_manifest_purge() if args[0] == "help": return self.cmd_fw_manifest_help() else: print("fw: Unknown manifest option (%s)" % args[0]) print(fw_manifest_usage()) def manifest_parse(self, path): '''parse manifest at path, return JSON object''' print("fw: parsing manifests") content = open(path).read() return json.loads(content) def semver_major(self,semver): '''return major part of semver version number. Avoids "import semver"''' return int(semver[0:semver.index(".")]) def manifest_path_is_old(self, path): '''return true if path is more than a day old''' mtime = os.path.getmtime(path) return (time.time() - mtime) > 24*60*60 def manifests_parse(self): '''parse manifests present on system''' self.manifests = [] for manifest_path in self.find_manifests(): if self.manifest_path_is_old(manifest_path): print("fw: Manifest (%s) is old; consider 'fw manifest download'" % (manifest_path)) manifest = self.manifest_parse(manifest_path) if self.semver_major(manifest["format-version"]) != 1: print("fw: Manifest (%s) has major version %d; MAVProxy only understands version 1" % (manifest_path,manifest["format-version"])) continue self.manifests.append(manifest) def cmd_fw_manifest_status(self): '''brief summary of manifest status''' print(f"fw: {len(list(self.downloaders.keys()))} downloaders") print(f"fw: {len(self.find_manifests())} manifests") def download_url(self, url, path): mp_util.download_files([(url,path)]) def idle_task(self): '''called rapidly by mavproxy''' if self.downloaders_lock.acquire(False): removed_one = False for url in list(self.downloaders.keys()): if not self.downloaders[url].is_alive(): print("fw: Download thread for (%s) done" % url) del self.downloaders[url] removed_one = True if removed_one and not self.downloaders.keys(): # all downloads finished - parse them self.manifests_parse() self.downloaders_lock.release() def make_safe_filename_from_url(self, url): '''return a version of url safe for use as a filename''' r = re.compile("([^a-zA-Z0-9_.-])") filename = r.sub(lambda m : "%" + str(hex(ord(str(m.group(1))))).upper(), url) return filename def manifest_download(self): '''download manifest files''' if self.downloaders_lock.acquire(False): if len(self.downloaders): # there already exist downloader threads self.downloaders_lock.release() return for url in ['https://firmware.ardupilot.org/manifest.json']: filename = self.make_safe_filename_from_url(url) path = mp_util.dot_mavproxy("manifest-%s" % filename) self.downloaders[url] = threading.Thread(target=self.download_url, args=(url, path)) self.downloaders[url].start() self.downloaders_lock.release() else: print("fw: Failed to acquire download lock")
class FirmwareModule(mp_module.MPModule): def __init__(self, mpstate): pass def usage(self): '''show help on a command line options''' pass def cmd_fw_help(self): '''show help on fw command''' pass def cmd_fw_help(self): '''execute command defined in args''' pass def frame_from_firmware(self, firmware): '''extract information from firmware, return pretty string to user''' pass def semver_from_firmware(self, firmware): '''Extract a tuple of (major,minor,patch) from a firmware instance''' pass def row_is_filtered(self, row_subs, filters): '''returns True if row should NOT be included according to filters''' pass def filters_from_args(self, args): '''take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments''' pass def all_firmwares(self): ''' return firmware entries from all manifests''' pass def rows_for_firmwares(self, firmwares): '''provide user-readable text for a firmware entry''' pass def filter_rows(self, filters, rows): '''returns rows as filtered by filters''' pass def filtered_rows_from_args(self, args): '''extracts filters from args, rows from manifests, returns filtered rows''' pass def cmd_flashfile(self, args): pass def cmd_flashfile(self, args): '''cmd handler for flash''' pass def cmd_fw_list(self, args): '''cmd handler for list''' pass def list_firmwares(self, filtered): pass def cmd_fw_download(self, args): '''cmd handler for downloading firmware''' pass def download_firmware(self, firmware, filename=None): pass def fw_manifest_usage(self): '''return help on manifest subcommand''' pass def cmd_fw_manifest_help(self): '''show help on manifest subcommand''' pass def find_manifests(self): '''locate manifests and return filepaths thereof''' pass def cmd_fw_manifest_list(self): '''list manifests''' pass def cmd_fw_manifest_load(self): '''handle command to load manifests - hidden command since these should only change with fw commands''' pass def cmd_fw_manifest_purge(self): '''remove all downloaded manifests''' pass def cmd_fw_manifest_help(self): '''cmd handler for manipulating manifests''' pass def manifest_parse(self, path): '''parse manifest at path, return JSON object''' pass def semver_major(self,semver): '''return major part of semver version number. Avoids "import semver"''' pass def manifest_path_is_old(self, path): '''return true if path is more than a day old''' pass def manifests_parse(self): '''parse manifests present on system''' pass def cmd_fw_manifest_status(self): '''brief summary of manifest status''' pass def download_url(self, url, path): pass def idle_task(self): '''called rapidly by mavproxy''' pass def make_safe_filename_from_url(self, url): '''return a version of url safe for use as a filename''' pass def manifest_download(self): '''download manifest files''' pass
35
29
11
1
9
1
3
0.12
1
9
1
0
34
4
34
72
398
53
308
97
273
37
263
95
228
9
2
3
91
6,931
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_followtest.py
MAVProxy.modules.mavproxy_followtest.FollowTestModule
class FollowTestModule(mp_module.MPModule): def __init__(self, mpstate): super(FollowTestModule, self).__init__(mpstate, "followtest", "followtest module") self.add_command('followtest', self.cmd_followtest, "followtest control", ['set (FOLLOWSETTING)']) self.follow_settings = mp_settings.MPSettings([("radius", float, 100.0), ("altitude", float, 50.0), ("speed", float, 10.0), ("type", str, 'guided'), ("vehicle_throttle", float, 0.5), ("disable_msg", bool, False)]) self.add_completion_function('(FOLLOWSETTING)', self.follow_settings.completion) self.target_pos = None self.last_update = 0 self.circle_dist = 0 def cmd_followtest(self, args): '''followtest command parser''' usage = "usage: followtest <set>" if len(args) == 0: print(usage) return if args[0] == "set": self.follow_settings.command(args[1:]) else: print(usage) def update_target(self, time_boot_ms): '''update target on map''' if not self.mpstate.map: # don't draw if no map return if not 'HOME_POSITION' in self.master.messages: return home_position = self.master.messages['HOME_POSITION'] now = time_boot_ms * 1.0e-3 dt = now - self.last_update if dt < 0: dt = 0 self.last_update = now self.circle_dist += dt * self.follow_settings.speed # assume a circle for now circumference = math.pi * self.follow_settings.radius * 2 rotations = math.fmod(self.circle_dist, circumference) / circumference angle = math.pi * 2 * rotations self.target_pos = mp_util.gps_newpos(home_position.latitude*1.0e-7, home_position.longitude*1.0e-7, math.degrees(angle), self.follow_settings.radius) icon = self.mpstate.map.icon('camera-small-red.png') (lat, lon) = (self.target_pos[0], self.target_pos[1]) self.mpstate.map.add_object(mp_slipmap.SlipIcon('followtest', (lat, lon), icon, layer='FollowTest', rotation=0, follow=False)) def idle_task(self): '''update vehicle position''' pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if not self.mpstate.map: # don't draw if no map return if m.get_type() != 'GLOBAL_POSITION_INT': return self.update_target(m.time_boot_ms) if self.target_pos is None: return if self.follow_settings.disable_msg: return if self.follow_settings.type == 'guided': # send normal guided mode packet self.master.mav.mission_item_int_send(self.settings.target_system, self.settings.target_component, 0, self.module('wp').get_default_frame(), mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 2, 0, 0, 0, 0, 0, int(self.target_pos[0]*1.0e7), int(self.target_pos[1]*1.0e7), self.follow_settings.altitude) elif self.follow_settings.type == 'yaw': # display yaw from vehicle to target vehicle = (m.lat*1.0e-7, m.lon*1.0e-7) vehicle_yaw = math.degrees(self.master.field('ATTITUDE', 'yaw', 0)) target_bearing = mp_util.gps_bearing(vehicle[0], vehicle[1], self.target_pos[0], self.target_pos[1]) # wrap the angle from -180 to 180 thus commanding the vehicle to turn left or right # note its in centi-degrees so *100 relyaw = mp_util.wrap_180(target_bearing - vehicle_yaw) * 100 self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_NAV_SET_YAW_SPEED, 0, relyaw, self.follow_settings.vehicle_throttle, 0, 0, 0, 0, 0)
class FollowTestModule(mp_module.MPModule): def __init__(self, mpstate): pass def cmd_followtest(self, args): '''followtest command parser''' pass def update_target(self, time_boot_ms): '''update target on map''' pass def idle_task(self): '''update vehicle position''' pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass
6
4
20
2
16
2
3
0.14
1
7
2
0
5
4
5
43
108
17
80
23
74
11
55
23
49
7
2
1
16
6,932
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ftp.py
MAVProxy.modules.mavproxy_ftp.FTPModule
class FTPModule(mp_module.MPModule): def __init__(self, mpstate): super(FTPModule, self).__init__(mpstate, "ftp", public=True) self.add_command('ftp', self.cmd_ftp, "file transfer", ["<list|get|rm|rmdir|rename|mkdir|crc|cancel|status>", "set (FTPSETTING)", "put (FILENAME) (FILENAME)"]) self.ftp_settings = mp_settings.MPSettings( [('debug', int, 0), ('pkt_loss_tx', int, 0), ('pkt_loss_rx', int, 0), ('max_backlog', int, 5), ('burst_read_size', int, 80), ('write_size', int, 80), ('write_qsize', int, 5), ('retry_time', float, 0.5)]) self.add_completion_function('(FTPSETTING)', self.ftp_settings.completion) self.seq = 0 self.session = 0 self.network = 0 self.last_op = None self.fh = None self.filename = None self.callback = None self.callback_progress = None self.put_callback = None self.put_callback_progress = None self.total_size = 0 self.read_gaps = [] self.read_gap_times = {} self.last_gap_send = 0 self.read_retries = 0 self.read_total = 0 self.duplicates = 0 self.last_read = None self.last_burst_read = None self.op_start = None self.dir_offset = 0 self.last_op_time = time.time() self.rtt = 0.5 self.reached_eof = False self.backlog = 0 self.burst_size = self.ftp_settings.burst_read_size self.write_list = None self.write_block_size = 0 self.write_acks = 0 self.write_total = 0 self.write_file_size = 0 self.write_idx = 0 self.write_recv_idx = -1 self.write_pending = 0 self.write_last_send = None self.warned_component = False def cmd_ftp(self, args): '''FTP operations''' usage = "Usage: ftp <list|get|put|rm|rmdir|rename|mkdir|crc>" if len(args) < 1: print(usage) return if args[0] == 'list': self.cmd_list(args[1:]) elif args[0] == "set": self.ftp_settings.command(args[1:]) elif args[0] == 'get': self.cmd_get(args[1:]) elif args[0] == 'put': self.cmd_put(args[1:]) elif args[0] == 'rm': self.cmd_rm(args[1:]) elif args[0] == 'rmdir': self.cmd_rmdir(args[1:]) elif args[0] == 'rename': self.cmd_rename(args[1:]) elif args[0] == 'mkdir': self.cmd_mkdir(args[1:]) elif args[0] == 'crc': self.cmd_crc(args[1:]) elif args[0] == 'status': self.cmd_status() elif args[0] == 'cancel': self.cmd_cancel() else: print(usage) def send(self, op): '''send a request''' op.seq = self.seq payload = op.pack() plen = len(payload) if plen < MAX_Payload + HDR_Len: payload.extend(bytearray([0]*((HDR_Len+MAX_Payload)-plen))) self.master.mav.file_transfer_protocol_send(self.network, self.target_system, self.target_component, payload) self.seq = (self.seq + 1) % 256 self.last_op = op now = time.time() if self.ftp_settings.debug > 1: print("> %s dt=%.2f" % (op, now - self.last_op_time)) self.last_op_time = time.time() def terminate_session(self): '''terminate current session''' self.send(FTP_OP(self.seq, self.session, OP_TerminateSession, 0, 0, 0, 0, None)) self.fh = None self.filename = None self.write_list = None if self.callback is not None: # tell caller that the transfer failed self.callback(None) self.callback = None if self.put_callback is not None: # tell caller that the transfer failed self.put_callback(None) self.put_callback = None if self.put_callback_progress is not None: self.put_callback_progress(None) self.put_callback_progress = None self.read_gaps = [] self.read_total = 0 self.read_gap_times = {} self.last_read = None self.last_burst_read = None self.session = (self.session + 1) % 256 self.reached_eof = False self.backlog = 0 self.duplicates = 0 if self.ftp_settings.debug > 0: print("Terminated session") def cmd_list(self, args): '''list files''' if len(args) > 0: dname = args[0] else: dname = '/' print("Listing %s" % dname) enc_dname = bytearray(dname, 'ascii') self.total_size = 0 self.dir_offset = 0 op = FTP_OP(self.seq, self.session, OP_ListDirectory, len(enc_dname), 0, 0, self.dir_offset, enc_dname) self.send(op) def handle_list_reply(self, op, m): '''handle OP_ListDirectory reply''' if op.opcode == OP_Ack: dentries = sorted(op.payload.split(b'\x00')) #print(dentries) for d in dentries: if len(d) == 0: continue self.dir_offset += 1 try: if sys.version_info.major >= 3: d = str(d, 'ascii') else: d = str(d) except Exception: continue if d[0] == 'D': print(" D %s" % d[1:]) elif d[0] == 'F': (name, size) = d[1:].split('\t') size = int(size) self.total_size += size print(" %s\t%u" % (name, size)) else: print(d) # ask for more more = self.last_op more.offset = self.dir_offset self.send(more) elif op.opcode == OP_Nack and len(op.payload) == 1 and op.payload[0] == ERR_EndOfFile: print("Total size %.2f kByte" % (self.total_size / 1024.0)) self.total_size = 0 else: print('LIST: %s' % op) def cmd_get(self, args, callback=None, callback_progress=None): '''get file''' if len(args) == 0: print("Usage: get FILENAME <LOCALNAME>") return self.terminate_session() fname = args[0] if len(args) > 1: self.filename = args[1] else: self.filename = os.path.basename(fname) if callback is None or self.ftp_settings.debug > 1: print("Getting %s as %s" % (fname, self.filename)) self.op_start = time.time() self.callback = callback self.callback_progress = callback_progress self.read_retries = 0 self.duplicates = 0 self.reached_eof = False self.burst_size = self.ftp_settings.burst_read_size if self.burst_size < 1: self.burst_size = 239 elif self.burst_size > 239: self.burst_size = 239 enc_fname = bytearray(fname, 'ascii') self.open_retries = 0 op = FTP_OP(self.seq, self.session, OP_OpenFileRO, len(enc_fname), 0, 0, 0, enc_fname) self.send(op) def handle_open_RO_reply(self, op, m): '''handle OP_OpenFileRO reply''' if op.opcode == OP_Ack: if self.filename is None: return try: if self.callback is not None or self.filename == '-': self.fh = SIO() else: self.fh = open(self.filename, 'wb') except Exception as ex: print("Failed to open %s: %s" % (self.filename, ex)) self.terminate_session() return read = FTP_OP(self.seq, self.session, OP_BurstReadFile, self.burst_size, 0, 0, 0, None) self.last_burst_read = time.time() self.send(read) else: if self.callback is None or self.ftp_settings.debug > 0: print("ftp open failed") self.terminate_session() def check_read_finished(self): '''check if download has completed''' if self.reached_eof and len(self.read_gaps) == 0: ofs = self.fh.tell() dt = time.time() - self.op_start rate = (ofs / dt) / 1024.0 if self.callback is not None: self.fh.seek(0) self.callback(self.fh) self.callback = None elif self.filename == "-": self.fh.seek(0) if sys.version_info.major < 3: print(self.fh.read()) else: print(self.fh.read().decode('utf-8')) else: print("Wrote %u bytes to %s in %.2fs %.1fkByte/s" % (ofs, self.filename, dt, rate)) self.terminate_session() return True return False def write_payload(self, op): '''write payload from a read op''' self.fh.seek(op.offset) self.fh.write(op.payload) self.read_total += len(op.payload) if self.callback_progress is not None: self.callback_progress(self.fh, self.read_total) def handle_burst_read(self, op, m): '''handle OP_BurstReadFile reply''' if self.ftp_settings.pkt_loss_tx > 0: if random.uniform(0,100) < self.ftp_settings.pkt_loss_tx: if self.ftp_settings.debug > 0: print("FTP: dropping TX") return if self.fh is None or self.filename is None: if op.session != self.session: # old session return print("FTP Unexpected burst read reply") print(op) return self.last_burst_read = time.time() size = len(op.payload) if size > self.burst_size: # this server doesn't handle the burst size argument self.burst_size = MAX_Payload if self.ftp_settings.debug > 0: print("Setting burst size to %u" % self.burst_size) if op.opcode == OP_Ack and self.fh is not None: ofs = self.fh.tell() if op.offset < ofs: # writing an earlier portion, possibly remove a gap gap = (op.offset, len(op.payload)) if gap in self.read_gaps: self.read_gaps.remove(gap) self.read_gap_times.pop(gap) if self.ftp_settings.debug > 0: print("FTP: removed gap", gap, self.reached_eof, len(self.read_gaps)) else: if self.ftp_settings.debug > 0: print("FTP: dup read reply at %u of len %u ofs=%u" % (op.offset, op.size, self.fh.tell())) self.duplicates += 1 return self.write_payload(op) self.fh.seek(ofs) if self.check_read_finished(): return elif op.offset > ofs: # we have a gap gap = (ofs, op.offset-ofs) max_read = self.burst_size while True: if gap[1] <= max_read: self.read_gaps.append(gap) self.read_gap_times[gap] = 0 break g = (gap[0], max_read) self.read_gaps.append(g) self.read_gap_times[g] = 0 gap = (gap[0] + max_read, gap[1] - max_read) self.write_payload(op) else: self.write_payload(op) if op.burst_complete: if op.size > 0 and op.size < self.burst_size: # a burst complete with non-zero size and less than burst packet size # means EOF if not self.reached_eof and self.ftp_settings.debug > 0: print("EOF at %u with %u gaps t=%.2f" % (self.fh.tell(), len(self.read_gaps), time.time() - self.op_start)) self.reached_eof = True if self.check_read_finished(): return self.check_read_send() return more = self.last_op more.offset = op.offset + op.size if self.ftp_settings.debug > 0: print("FTP: burst continue at %u %u" % (more.offset, self.fh.tell())) self.send(more) elif op.opcode == OP_Nack: ecode = op.payload[0] if self.ftp_settings.debug > 0: print("FTP: burst nack: ", op) if ecode == ERR_EndOfFile or ecode == 0: if not self.reached_eof and op.offset > self.fh.tell(): # we lost the last part of the burst if self.ftp_settings.debug > 0: print("burst lost EOF %u %u" % (self.fh.tell(), op.offset)) return if not self.reached_eof and self.ftp_settings.debug > 0: print("EOF at %u with %u gaps t=%.2f" % (self.fh.tell(), len(self.read_gaps), time.time() - self.op_start)) self.reached_eof = True if self.check_read_finished(): return self.check_read_send() elif self.ftp_settings.debug > 0: print("FTP: burst Nack (ecode:%u): %s" % (ecode, op)) else: print("FTP: burst error: %s" % op) def handle_reply_read(self, op, m): '''handle OP_ReadFile reply''' if self.fh is None or self.filename is None: if self.ftp_settings.debug > 0: print("FTP Unexpected read reply") print(op) return if self.backlog > 0: self.backlog -= 1 if op.opcode == OP_Ack and self.fh is not None: gap = (op.offset, op.size) if gap in self.read_gaps: self.read_gaps.remove(gap) self.read_gap_times.pop(gap) ofs = self.fh.tell() self.write_payload(op) self.fh.seek(ofs) if self.ftp_settings.debug > 0: print("FTP: removed gap", gap, self.reached_eof, len(self.read_gaps)) if self.check_read_finished(): return elif op.size < self.burst_size: print("FTP: file size changed to %u" % op.offset+op.size) self.terminate_session() else: self.duplicates += 1 if self.ftp_settings.debug > 0: print("FTP: no gap read", gap, len(self.read_gaps)) elif op.opcode == OP_Nack: print("Read failed with %u gaps" % len(self.read_gaps), str(op)) self.terminate_session() self.check_read_send() def cmd_put(self, args, fh=None, callback=None, progress_callback=None): '''put file''' if len(args) == 0: print("Usage: put FILENAME <REMOTENAME>") return if self.write_list is not None: print("put already in progress") return fname = args[0] self.fh = fh if self.fh is None: try: self.fh = open(fname, 'rb') except Exception as ex: print("Failed to open %s: %s" % (fname, ex)) return if len(args) > 1: self.filename = args[1] else: self.filename = os.path.basename(fname) if self.filename.endswith("/"): self.filename += os.path.basename(fname) if callback is None: print("Putting %s as %s" % (fname, self.filename)) self.fh.seek(0,2) file_size = self.fh.tell() self.fh.seek(0) # setup write list self.write_block_size = self.ftp_settings.write_size self.write_file_size = file_size write_blockcount = file_size // self.write_block_size if file_size % self.write_block_size != 0: write_blockcount += 1 self.write_list = set(range(write_blockcount)) self.write_acks = 0 self.write_total = write_blockcount self.write_idx = 0 self.write_recv_idx = -1 self.write_pending = 0 self.write_last_send = None self.put_callback = callback self.put_callback_progress = progress_callback self.read_retries = 0 self.op_start = time.time() enc_fname = bytearray(self.filename, 'ascii') op = FTP_OP(self.seq, self.session, OP_CreateFile, len(enc_fname), 0, 0, 0, enc_fname) self.send(op) def put_finished(self, flen): '''finish a put''' if self.put_callback_progress: self.put_callback_progress(1.0) self.put_callback_progress = None if self.put_callback is not None: self.put_callback(flen) self.put_callback = None else: print("Sent file of length ", flen) def handle_create_file_reply(self, op, m): '''handle OP_CreateFile reply''' if self.fh is None: self.terminate_session() return if op.opcode == OP_Ack: self.send_more_writes() else: print("Create failed") self.terminate_session() def send_more_writes(self): '''send some more writes''' if len(self.write_list) == 0: # all done self.put_finished(self.write_file_size) self.terminate_session() return now = time.time() if self.write_last_send is not None: if now - self.write_last_send > max(min(10*self.rtt, 1),0.2): # we seem to have lost a block of replies self.write_pending = max(0, self.write_pending-1) n = min(self.ftp_settings.write_qsize-self.write_pending, len(self.write_list)) for i in range(n): # send in round-robin, skipping any that have been acked idx = self.write_idx while idx not in self.write_list: idx = (idx + 1) % self.write_total ofs = idx * self.write_block_size self.fh.seek(ofs) data = self.fh.read(self.write_block_size) write = FTP_OP(self.seq, self.session, OP_WriteFile, len(data), 0, 0, ofs, bytearray(data)) self.send(write) self.write_idx = (idx + 1) % self.write_total self.write_pending += 1 self.write_last_send = now def handle_write_reply(self, op, m): '''handle OP_WriteFile reply''' if self.fh is None: self.terminate_session() return if op.opcode != OP_Ack: print("Write failed") self.terminate_session() return # assume the FTP server processes the blocks sequentially. This means # when we receive an ack that any blocks between the last ack and this # one have been lost idx = op.offset // self.write_block_size count = (idx - self.write_recv_idx) % self.write_total self.write_pending = max(0, self.write_pending - count) self.write_recv_idx = idx self.write_list.discard(idx) self.write_acks += 1 if self.put_callback_progress: self.put_callback_progress(self.write_acks/float(self.write_total)) self.send_more_writes() def cmd_rm(self, args): '''remove file''' if len(args) == 0: print("Usage: rm FILENAME") return fname = args[0] print("Removing %s" % fname) enc_fname = bytearray(fname, 'ascii') op = FTP_OP(self.seq, self.session, OP_RemoveFile, len(enc_fname), 0, 0, 0, enc_fname) self.send(op) def cmd_rmdir(self, args): '''remove directory''' if len(args) == 0: print("Usage: rmdir FILENAME") return dname = args[0] print("Removing %s" % dname) enc_dname = bytearray(dname, 'ascii') op = FTP_OP(self.seq, self.session, OP_RemoveDirectory, len(enc_dname), 0, 0, 0, enc_dname) self.send(op) def handle_remove_reply(self, op, m): '''handle remove reply''' if op.opcode != OP_Ack: print("Remove failed %s" % op) def cmd_rename(self, args): '''rename file''' if len(args) < 2: print("Usage: rename OLDNAME NEWNAME") return name1 = args[0] name2 = args[1] print("Renaming %s to %s" % (name1, name2)) enc_name1 = bytearray(name1, 'ascii') enc_name2 = bytearray(name2, 'ascii') enc_both = enc_name1 + b'\x00' + enc_name2 op = FTP_OP(self.seq, self.session, OP_Rename, len(enc_both), 0, 0, 0, enc_both) self.send(op) def handle_rename_reply(self, op, m): '''handle rename reply''' if op.opcode != OP_Ack: print("Rename failed %s" % op) def cmd_mkdir(self, args): '''make directory''' if len(args) < 1: print("Usage: mkdir NAME") return name = args[0] print("Creating directory %s" % name) enc_name = bytearray(name, 'ascii') op = FTP_OP(self.seq, self.session, OP_CreateDirectory, len(enc_name), 0, 0, 0, enc_name) self.send(op) def handle_mkdir_reply(self, op, m): '''handle mkdir reply''' if op.opcode != OP_Ack: print("Create directory failed %s" % op) def cmd_crc(self, args): '''get crc''' if len(args) < 1: print("Usage: crc NAME") return name = args[0] self.filename = name self.op_start = time.time() print("Getting CRC for %s" % name) enc_name = bytearray(name, 'ascii') op = FTP_OP(self.seq, self.session, OP_CalcFileCRC32, len(enc_name), 0, 0, 0, bytearray(enc_name)) self.send(op) def handle_crc_reply(self, op, m): '''handle crc reply''' if op.opcode == OP_Ack and op.size == 4: crc, = struct.unpack("<I", op.payload) now = time.time() print("crc: %s 0x%08x in %.1fs" % (self.filename, crc, now - self.op_start)) else: print("crc failed %s" % op) def cmd_cancel(self): '''cancel any pending op''' self.terminate_session() def cmd_status(self): '''show status''' if self.fh is None: print("No transfer in progress") else: ofs = self.fh.tell() dt = time.time() - self.op_start rate = (ofs / dt) / 1024.0 print("Transfer at offset %u with %u gaps %u retries %.1f kByte/sec" % (ofs, len(self.read_gaps), self.read_retries, rate)) def op_parse(self, m): '''parse a FILE_TRANSFER_PROTOCOL msg''' hdr = bytearray(m.payload[0:12]) (seq, session, opcode, size, req_opcode, burst_complete, pad, offset) = struct.unpack("<HBBBBBBI", hdr) payload = bytearray(m.payload[12:])[:size] return FTP_OP(seq, session, opcode, size, req_opcode, burst_complete, offset, payload) def mavlink_packet(self, m): '''handle a mavlink packet''' mtype = m.get_type() if mtype == "FILE_TRANSFER_PROTOCOL": if (m.target_system != self.settings.source_system or m.target_component != self.settings.source_component): if m.target_system == self.settings.source_system and not self.warned_component: self.warned_component = True print("FTP reply for mavlink component %u" % m.target_component) return op = self.op_parse(m) now = time.time() dt = now - self.last_op_time if self.ftp_settings.debug > 1: print("< %s dt=%.2f" % (op, dt)) self.last_op_time = now if self.ftp_settings.pkt_loss_rx > 0: if random.uniform(0,100) < self.ftp_settings.pkt_loss_rx: if self.ftp_settings.debug > 1: print("FTP: dropping packet RX") return if op.req_opcode == self.last_op.opcode and op.seq == (self.last_op.seq + 1) % 256: self.rtt = max(min(self.rtt, dt), 0.01) if op.req_opcode == OP_ListDirectory: self.handle_list_reply(op, m) elif op.req_opcode == OP_OpenFileRO: self.handle_open_RO_reply(op, m) elif op.req_opcode == OP_BurstReadFile: self.handle_burst_read(op, m) elif op.req_opcode == OP_TerminateSession: pass elif op.req_opcode == OP_CreateFile: self.handle_create_file_reply(op, m) elif op.req_opcode == OP_WriteFile: self.handle_write_reply(op, m) elif op.req_opcode in [OP_RemoveFile, OP_RemoveDirectory]: self.handle_remove_reply(op, m) elif op.req_opcode == OP_Rename: self.handle_rename_reply(op, m) elif op.req_opcode == OP_CreateDirectory: self.handle_mkdir_reply(op, m) elif op.req_opcode == OP_ReadFile: self.handle_reply_read(op, m) elif op.req_opcode == OP_CalcFileCRC32: self.handle_crc_reply(op, m) else: print('FTP Unknown %s' % str(op)) def send_gap_read(self, g): '''send a read for a gap''' (offset, length) = g if self.ftp_settings.debug > 0: print("Gap read of %u at %u rem=%u blog=%u" % (length, offset, len(self.read_gaps), self.backlog)) read = FTP_OP(self.seq, self.session, OP_ReadFile, length, 0, 0, offset, None) self.send(read) self.read_gaps.remove(g) self.read_gaps.append(g) self.last_gap_send = time.time() self.read_gap_times[g] = self.last_gap_send self.backlog += 1 def check_read_send(self): '''see if we should send another gap read''' if len(self.read_gaps) == 0: return g = self.read_gaps[0] now = time.time() dt = now - self.read_gap_times[g] if not self.reached_eof: # send gap reads once for g in self.read_gap_times.keys(): if self.read_gap_times[g] == 0: self.send_gap_read(g) return if self.read_gap_times[g] > 0 and dt > self.ftp_settings.retry_time: if self.backlog > 0: self.backlog -= 1 self.read_gap_times[g] = 0 if self.read_gap_times[g] != 0: # still pending return if not self.reached_eof and self.backlog >= self.ftp_settings.max_backlog: # don't fill queue too far until we have got past the burst return if now - self.last_gap_send < 0.05: # don't send too fast return self.send_gap_read(g) def idle_task(self): '''check for file gaps and lost requests''' now = time.time() # see if we lost an open reply if self.op_start is not None and now - self.op_start > 1.0 and self.last_op.opcode == OP_OpenFileRO: self.op_start = now self.open_retries += 1 if self.open_retries > 2: # fail the get self.op_start = None self.terminate_session() return if self.ftp_settings.debug > 0: print("FTP: retry open") send_op = self.last_op self.send(FTP_OP(self.seq, self.session, OP_TerminateSession, 0, 0, 0, 0, None)) self.session = (self.session + 1) % 256 send_op.session = self.session self.send(send_op) if len(self.read_gaps) == 0 and self.last_burst_read is None and self.write_list is None: return if self.fh is None: return # see if burst read has stalled if not self.reached_eof and self.last_burst_read is not None and now - self.last_burst_read > self.ftp_settings.retry_time: dt = now - self.last_burst_read self.last_burst_read = now if self.ftp_settings.debug > 0: print("Retry read at %u rtt=%.2f dt=%.2f" % (self.fh.tell(), self.rtt, dt)) self.send(FTP_OP(self.seq, self.session, OP_BurstReadFile, self.burst_size, 0, 0, self.fh.tell(), None)) self.read_retries += 1 # see if we can fill gaps self.check_read_send() if self.write_list is not None: self.send_more_writes()
class FTPModule(mp_module.MPModule): def __init__(self, mpstate): pass def cmd_ftp(self, args): '''FTP operations''' pass def send(self, op): '''send a request''' pass def terminate_session(self): '''terminate current session''' pass def cmd_list(self, args): '''list files''' pass def handle_list_reply(self, op, m): '''handle OP_ListDirectory reply''' pass def cmd_get(self, args, callback=None, callback_progress=None): '''get file''' pass def handle_open_RO_reply(self, op, m): '''handle OP_OpenFileRO reply''' pass def check_read_finished(self): '''check if download has completed''' pass def write_payload(self, op): '''write payload from a read op''' pass def handle_burst_read(self, op, m): '''handle OP_BurstReadFile reply''' pass def handle_reply_read(self, op, m): '''handle OP_ReadFile reply''' pass def cmd_put(self, args, fh=None, callback=None, progress_callback=None): '''put file''' pass def put_finished(self, flen): '''finish a put''' pass def handle_create_file_reply(self, op, m): '''handle OP_CreateFile reply''' pass def send_more_writes(self): '''send some more writes''' pass def handle_write_reply(self, op, m): '''handle OP_WriteFile reply''' pass def cmd_rm(self, args): '''remove file''' pass def cmd_rmdir(self, args): '''remove directory''' pass def handle_remove_reply(self, op, m): '''handle remove reply''' pass def cmd_rename(self, args): '''rename file''' pass def handle_rename_reply(self, op, m): '''handle rename reply''' pass def cmd_mkdir(self, args): '''make directory''' pass def handle_mkdir_reply(self, op, m): '''handle mkdir reply''' pass def cmd_crc(self, args): '''get crc''' pass def handle_crc_reply(self, op, m): '''handle crc reply''' pass def cmd_cancel(self): '''cancel any pending op''' pass def cmd_status(self): '''show status''' pass def op_parse(self, m): '''parse a FILE_TRANSFER_PROTOCOL msg''' pass def mavlink_packet(self, m): '''handle a mavlink packet''' pass def send_gap_read(self, g): '''send a read for a gap''' pass def check_read_send(self): '''see if we should send another gap read''' pass def idle_task(self): '''check for file gaps and lost requests''' pass
34
32
22
1
19
2
5
0.09
1
10
2
0
33
38
33
71
750
49
643
153
609
58
581
151
547
30
2
4
181
6,933
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ftp.py
MAVProxy.modules.mavproxy_ftp.FTP_OP
class FTP_OP: def __init__(self, seq, session, opcode, size, req_opcode, burst_complete, offset, payload): self.seq = seq self.session = session self.opcode = opcode self.size = size self.req_opcode = req_opcode self.burst_complete = burst_complete self.offset = offset self.payload = payload def pack(self): '''pack message''' ret = struct.pack("<HBBBBBBI", self.seq, self.session, self.opcode, self.size, self.req_opcode, self.burst_complete, 0, self.offset) if self.payload is not None: ret += self.payload ret = bytearray(ret) return ret def __str__(self): plen = 0 if self.payload is not None: plen = len(self.payload) ret = "OP seq:%u sess:%u opcode:%d req_opcode:%u size:%u bc:%u ofs:%u plen=%u" % (self.seq, self.session, self.opcode, self.req_opcode, self.size, self.burst_complete, self.offset, plen) if plen > 0: ret += " [%u]" % self.payload[0] return ret
class FTP_OP: def __init__(self, seq, session, opcode, size, req_opcode, burst_complete, offset, payload): pass def pack(self): '''pack message''' pass def __str__(self): pass
4
1
10
0
10
0
2
0.03
0
1
0
0
3
8
3
3
34
2
31
15
27
1
24
15
20
3
0
1
6
6,934
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ftp.py
MAVProxy.modules.mavproxy_ftp.WriteQueue
class WriteQueue: def __init__(self, ofs, size): self.ofs = ofs self.size = size self.last_send = 0
class WriteQueue: def __init__(self, ofs, size): pass
2
0
4
0
4
0
1
0
0
0
0
0
1
3
1
1
5
0
5
5
3
0
5
5
3
1
0
0
1
6,935
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_gasheli.py
MAVProxy.modules.mavproxy_gasheli.GasHeliModule
class GasHeliModule(mp_module.MPModule): def __init__(self, mpstate): super(GasHeliModule, self).__init__(mpstate, "gas_heli", "Gas Heli", public=False) self.console.set_status('IGN', 'IGN', row=4) self.console.set_status('THR', 'THR', row=4) self.console.set_status('RPM', 'RPM: 0', row=4) self.add_command('gasheli', self.cmd_gasheli, 'gas helicopter control', ['<start|stop>', 'set (GASHELISETTINGS)']) self.gasheli_settings = mp_settings.MPSettings( [ ('ignition_chan', int, 0), ('ignition_disable_time', float, 0.5), ('ignition_stop_time', float, 3), ('starter_chan', int, 0), ('starter_time', float, 3.0), ('starter_pwm_on', int, 2000), ('starter_pwm_off', int, 1000), ] ) self.add_completion_function('(GASHELISETTINGS)', self.gasheli_settings.completion) self.starting_motor = False self.stopping_motor = False self.motor_t1 = None self.old_override = 0 def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' type = msg.get_type() master = self.master # add some status fields if type in [ 'RC_CHANNELS_RAW' ]: rc6 = msg.chan6_raw if rc6 > 1500: ign_colour = 'green' else: ign_colour = 'red' self.console.set_status('IGN', 'IGN', fg=ign_colour, row=4) if type in [ 'SERVO_OUTPUT_RAW' ]: rc8 = msg.servo8_raw if rc8 < 1200: thr_colour = 'red' elif rc8 < 1300: thr_colour = 'orange' else: thr_colour = 'green' self.console.set_status('THR', 'THR', fg=thr_colour, row=4) if type in [ 'RPM' ]: rpm = msg.rpm1 if rpm < 3000: rpm_colour = 'red' elif rpm < 10000: rpm_colour = 'orange' else: rpm_colour = 'green' self.console.set_status('RPM', 'RPM: %u' % rpm, fg=rpm_colour, row=4) def valid_starter_settings(self): '''check starter settings''' if self.gasheli_settings.ignition_chan <= 0 or self.gasheli_settings.ignition_chan > 8: print("Invalid ignition channel %d" % self.gasheli_settings.ignition_chan) return False if self.gasheli_settings.starter_chan <= 0 or self.gasheli_settings.starter_chan > 14: print("Invalid starter channel %d" % self.gasheli_settings.starter_chan) return False return True def idle_task(self): '''run periodic tasks''' if self.starting_motor: if self.gasheli_settings.ignition_disable_time > 0: elapsed = time.time() - self.motor_t1 if elapsed >= self.gasheli_settings.ignition_disable_time: self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, self.old_override) self.starting_motor = False if self.stopping_motor: elapsed = time.time() - self.motor_t1 if elapsed >= self.gasheli_settings.ignition_stop_time: # hand back control to RC self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, self.old_override) self.stopping_motor = False def start_motor(self): '''start motor''' if not self.valid_starter_settings(): return self.motor_t1 = time.time() self.stopping_motor = False if self.gasheli_settings.ignition_disable_time > 0: self.old_override = self.module('rc').get_override_chan(self.gasheli_settings.ignition_chan-1) self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, 1000) self.starting_motor = True else: # nothing more to do self.starting_motor = False # setup starter run self.master.mav.command_long_send(self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_DO_REPEAT_SERVO, 0, self.gasheli_settings.starter_chan, self.gasheli_settings.starter_pwm_on, 1, self.gasheli_settings.starter_time*2, 0, 0, 0) print("Starting motor") def stop_motor(self): '''stop motor''' if not self.valid_starter_settings(): return self.motor_t1 = time.time() self.starting_motor = False self.stopping_motor = True self.old_override = self.module('rc').get_override_chan(self.gasheli_settings.ignition_chan-1) self.module('rc').set_override_chan(self.gasheli_settings.ignition_chan-1, 1000) print("Stopping motor") def cmd_gasheli(self, args): '''gas help commands''' usage = "Usage: gasheli <start|stop|set>" if len(args) < 1: print(usage) return if args[0] == "start": self.start_motor() elif args[0] == "stop": self.stop_motor() elif args[0] == "set": self.gasheli_settings.command(args[1:]) else: print(usage)
class GasHeliModule(mp_module.MPModule): def __init__(self, mpstate): pass def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' pass def valid_starter_settings(self): '''check starter settings''' pass def idle_task(self): '''run periodic tasks''' pass def start_motor(self): '''start motor''' pass def stop_motor(self): '''stop motor''' pass def cmd_gasheli(self, args): '''gas help commands''' pass
8
6
19
1
16
1
4
0.09
1
4
1
0
7
5
7
45
137
12
115
23
107
10
87
23
79
9
2
3
29
6,936
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_generator.py
MAVProxy.modules.mavproxy_generator.generator
class generator(mp_module.MPModule): def __init__(self, mpstate): """Initialise module""" super(generator, self).__init__(mpstate, "generator", "") self.generator_settings = mp_settings.MPSettings( [ ('verbose', bool, False), ]) self.add_command('generator', self.cmd_generator, "generator module", ['status','set (LOGSETTING)']) self.console_row = 6 self.console.set_status('Generator', 'No generator messages', row=self.console_row) self.last_seen_generator_message = 0 self.mpstate = mpstate self.last_set_interval_sent = 0 def usage(self): '''show help on command line options''' return "Usage: generator <status|set>" def cmd_generator(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "set": self.generator_settings.command(args[1:]) else: print(self.usage()) def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'GENERATOR_STATUS': if self.generator_settings.verbose: print("Got generator message") self.last_seen_generator_message = time.time() error_string = "" errors = [] prefix = "MAV_GENERATOR_STATUS_FLAG_" len_prefix = len(prefix) flags = [] for i in range(64): if m.status & (1<<i): try: name = mavutil.mavlink.enums["MAV_GENERATOR_STATUS_FLAG"][1<<i].name if name.startswith(prefix): name = name[len_prefix:] except KeyError: name = "UNKNOWN=%u" % (1<<i) flags.append(name) self.console.set_status( 'Generator', 'Generator: RPM:%u current:%u volts:%f flags:%s runtime:%u maint:%d' % (m.generator_speed, m.load_current, m.bus_voltage, ",".join(flags), m.runtime, m.time_until_maintenance, ), row=self.console_row) now = time.time() if now - self.last_seen_generator_message > 10: # request the message once per second: if now - self.last_set_interval_sent > 1: self.last_set_interval_sent = now self.master.mav.command_long_send( self.mpstate.settings.target_system, self.mpstate.settings.target_component, mavutil.mavlink.MAV_CMD_SET_MESSAGE_INTERVAL, 0, # confirmation mavutil.mavlink.MAVLINK_MSG_ID_GENERATOR_STATUS, # msg id 100000, # interval 0, # p3 0, # p4 0, # p5 0, # p6 0)
class generator(mp_module.MPModule): def __init__(self, mpstate): '''Initialise module''' pass def usage(self): '''show help on command line options''' pass def cmd_generator(self, args): '''control behaviour of the module''' pass def mavlink_packet(self, m): '''handle mavlink packets''' pass
5
4
20
1
18
3
4
0.18
1
5
1
0
4
5
4
42
82
5
72
18
67
13
43
18
38
9
2
5
15
6,937
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.Aircraft
class Aircraft(DNFZ): '''an aircraft that flies in a circuit''' def __init__(self, elevationModel, speed=30.0, circuit_width=1000.0): DNFZ.__init__(self, 'Aircraft', elevationModel) self.setspeed(speed) self.circuit_width = circuit_width self.dist_flown = 0 self.randalt() def update(self, deltat=1.0): '''fly a square circuit''' DNFZ.update(self, deltat) self.dist_flown += self.speed * deltat if self.dist_flown > self.circuit_width: self.desired_heading = self.heading + 90 self.dist_flown = 0 if self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 2000: self.randpos() self.randalt()
class Aircraft(DNFZ): '''an aircraft that flies in a circuit''' def __init__(self, elevationModel, speed=30.0, circuit_width=1000.0): pass def update(self, deltat=1.0): '''fly a square circuit''' pass
3
2
8
0
8
1
2
0.13
1
0
0
0
2
3
2
23
19
1
16
6
13
2
16
6
13
3
1
1
4
6,938
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.BirdMigrating
class BirdMigrating(DNFZ): '''an bird that circles slowly climbing, then dives''' def __init__(self, elevationModel): DNFZ.__init__(self, 'BirdMigrating', elevationModel) self.setspeed(random.uniform(4,16)) self.setyawrate(random.uniform(-0.2,0.2)) self.randalt() def update(self, deltat=1.0): '''fly in long curves''' DNFZ.update(self, deltat) if (self.distance_from_home() > gen_settings.region_width or self.getalt() < self.ground_height() or self.getalt() > self.ground_height() + 1000): self.randpos() self.randalt()
class BirdMigrating(DNFZ): '''an bird that circles slowly climbing, then dives''' def __init__(self, elevationModel): pass def update(self, deltat=1.0): '''fly in long curves''' pass
3
2
7
0
6
1
2
0.15
1
0
0
0
2
0
2
23
16
1
13
3
10
2
11
3
8
2
1
1
3
6,939
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.BirdOfPrey
class BirdOfPrey(DNFZ): '''an bird that circles slowly climbing, then dives''' def __init__(self, elevationModel): DNFZ.__init__(self, 'BirdOfPrey', elevationModel) self.setspeed(16.0) self.radius = random.uniform(100,200) self.time_circling = 0 self.dive_rate = -30 self.climb_rate = 5 self.drift_speed = random.uniform(5,10) self.max_alt = self.ground_height() + random.uniform(100, 400) self.drift_heading = self.heading circumference = math.pi * self.radius * 2 circle_time = circumference / self.speed self.turn_rate = 360.0 / circle_time if random.uniform(0,1) < 0.5: self.turn_rate = -self.turn_rate def update(self, deltat=1.0): '''fly circles, then dive''' DNFZ.update(self, deltat) self.time_circling += deltat self.setheading(self.heading + self.turn_rate * deltat) self.move(self.drift_heading, self.drift_speed) if self.getalt() > self.max_alt or self.getalt() < self.ground_height(): if self.getalt() > self.ground_height(): self.setclimbrate(self.dive_rate) else: self.setclimbrate(self.climb_rate) if self.getalt() < self.ground_height(): self.setalt(self.ground_height()) if self.distance_from_home() > gen_settings.region_width: self.randpos() self.randalt()
class BirdOfPrey(DNFZ): '''an bird that circles slowly climbing, then dives''' def __init__(self, elevationModel): pass def update(self, deltat=1.0): '''fly circles, then dive''' pass
3
2
16
0
15
1
4
0.06
1
0
0
0
2
8
2
23
34
1
31
13
28
2
30
13
27
5
1
2
7
6,940
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.DNFZ
class DNFZ: '''a dynamic no-fly zone object''' def __init__(self, DNFZ_type, elevationModel): if not DNFZ_type in DNFZ_types: raise('Bad DNFZ type %s' % DNFZ_type) self.DNFZ_type = DNFZ_type self.pkt = {'category': 0, 'I010': {'SAC': {'val': 4, 'desc': 'System Area Code'}, 'SIC': {'val': 0, 'desc': 'System Identification Code'}}, 'I040': {'TrkN': {'val': 0, 'desc': 'Track number'}}, 'ts': 0, 'len': 25, 'I220': {'RoC': {'val': 0.0, 'desc': 'Rate of Climb/Descent'}}, 'crc': 'B52DA163', 'I130': {'Alt': {'max': 150000.0, 'min': -1500.0, 'val': 0.0, 'desc': 'Altitude'}}, 'I070': {'ToT': {'val': 0.0, 'desc': 'Time Of Track Information'}}, 'I105': {'Lat': {'val': 0, 'desc': 'Latitude in WGS.84 in twos complement. Range -90 < latitude < 90 deg.'}, 'Lon': {'val': 0.0, 'desc': 'Longitude in WGS.84 in twos complement. Range -180 < longitude < 180 deg.'}}, 'I080': {'SRC': {'meaning': '3D radar', 'val': 2, 'desc': 'Source of calculated track altitude for I062/130'}, 'FX': {'meaning': 'end of data item', 'val': 0, 'desc': ''}, 'CNF': {'meaning': 'Confirmed track', 'val': 0, 'desc': ''}, 'SPI': {'meaning': 'default value', 'val': 0, 'desc': ''}, 'MRH': {'meaning': 'Geometric altitude more reliable', 'val': 1, 'desc': 'Most Reliable Height'}, 'MON': {'meaning': 'Multisensor track', 'val': 0, 'desc': ''}}} self.speed = 0.0 # m/s self.heading = 0.0 # degrees self.desired_heading = None self.yawrate = 0.0 self.elevationModel = elevationModel # random initial position and heading self.randpos() self.setheading(random.uniform(0,360)) self.setclimbrate(random.uniform(-3,3)) global track_count track_count += 1 self.pkt['I040']['TrkN']['val'] = DNFZ_types[self.DNFZ_type] + track_count if gen_settings.debug > 0: print("track %u" % self.pkt['I040']['TrkN']['val']) def distance_from(self, lat, lon): '''get distance from a point''' lat1 = self.pkt['I105']['Lat']['val'] lon1 = self.pkt['I105']['Lon']['val'] return mp_util.gps_distance(lat1, lon1, lat, lon) def distance_from_home(self): '''get distance from home''' return self.distance_from(gen_settings.home_lat, gen_settings.home_lon) def randpos(self): '''random initial position''' self.setpos(gen_settings.home_lat, gen_settings.home_lon) self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width)) def ground_height(self): '''return height above ground in feet''' lat = self.pkt['I105']['Lat']['val'] lon = self.pkt['I105']['Lon']['val'] ret = self.elevationModel.GetElevation(lat, lon) ret -= gen_settings.wgs84_to_AMSL return ret * 3.2807 def randalt(self): '''random initial position''' self.setalt(self.ground_height() + random.uniform(100, 1500)) def move(self, bearing, distance): '''move position by bearing and distance''' lat = self.pkt['I105']['Lat']['val'] lon = self.pkt['I105']['Lon']['val'] (lat, lon) = mp_util.gps_newpos(lat, lon, bearing, distance) self.setpos(lat, lon) def setpos(self, lat, lon): self.pkt['I105']['Lat']['val'] = lat self.pkt['I105']['Lon']['val'] = lon def getlat(self): return self.pkt['I105']['Lat']['val'] def getlon(self): return self.pkt['I105']['Lon']['val'] def getalt(self): return self.pkt['I130']['Alt']['val'] def setalt(self, alt): self.pkt['I130']['Alt']['val'] = alt def setclimbrate(self, climbrate): self.pkt['I220']['RoC']['val'] = climbrate def setyawrate(self, yawrate): self.yawrate = yawrate def setspeed(self, speed): self.speed = speed def setheading(self, heading): self.heading = heading while self.heading > 360: self.heading -= 360.0 while self.heading < 0: self.heading += 360.0 def changealt(self, delta_alt): alt = self.pkt['I130']['Alt']['val'] alt += delta_alt self.setalt(alt) def rate_of_turn(self, bank=45.0): '''return expected rate of turn in degrees/s for given speed in m/s and bank angle in degrees''' if abs(self.speed) < 2 or abs(bank) > 80: return 0 ret = degrees(9.81*tan(radians(bank))/self.speed) return ret def update(self, deltat=1.0): self.move(self.heading, self.speed * deltat) climbrate = self.pkt['I220']['RoC']['val'] self.changealt(climbrate * deltat) if self.desired_heading is None: self.setheading(self.heading + self.yawrate * deltat) else: heading_error = self.desired_heading - self.heading while heading_error > 180: heading_error -= 360.0 while heading_error < -180: heading_error += 360.0 max_turn = self.rate_of_turn() * deltat if heading_error > 0: turn = min(max_turn, heading_error) else: turn = max(-max_turn, heading_error) self.setheading(self.heading + turn) if abs(heading_error) < 0.01: self.desired_heading = None def __str__(self): return str(self.pkt) def pickled(self): return b'PICKLED:' + pickle.dumps(self.pkt)
class DNFZ: '''a dynamic no-fly zone object''' def __init__(self, DNFZ_type, elevationModel): pass def distance_from(self, lat, lon): '''get distance from a point''' pass def distance_from_home(self): '''get distance from home''' pass def randpos(self): '''random initial position''' pass def ground_height(self): '''return height above ground in feet''' pass def randalt(self): '''random initial position''' pass def move(self, bearing, distance): '''move position by bearing and distance''' pass def setpos(self, lat, lon): pass def getlat(self): pass def getlon(self): pass def getalt(self): pass def setalt(self, alt): pass def setclimbrate(self, climbrate): pass def setyawrate(self, yawrate): pass def setspeed(self, speed): pass def setheading(self, heading): pass def changealt(self, delta_alt): pass def rate_of_turn(self, bank=45.0): '''return expected rate of turn in degrees/s for given speed in m/s and bank angle in degrees''' pass def update(self, deltat=1.0): pass def __str__(self): pass def pickled(self): pass
22
8
5
0
5
0
1
0.11
0
1
0
4
21
7
21
21
126
20
97
43
74
11
95
43
72
6
0
2
31
6,941
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.GenobstaclesModule
class GenobstaclesModule(mp_module.MPModule): def __init__(self, mpstate): super(GenobstaclesModule, self).__init__(mpstate, "genobstacles", "OBC 2018 obstacle generator") self.add_command('genobstacles', self.cmd_genobstacles, "obstacle generator", ["<start|stop|restart|clearall|status>", "set (GENSETTING)"]) self.add_completion_function('(GENSETTING)', gen_settings.completion) self.sock = None self.aircraft = [] self.last_t = 0 self.menu_added_map = False self.pkt_queue = [] self.have_home = False self.pending_start = True self.last_click = None if mp_util.has_wxpython: self.menu = MPMenuSubMenu('Obstacles', items=[MPMenuItem('Restart', 'Restart', '# genobstacles restart'), MPMenuItem('Stop', 'Stop', '# genobstacles stop'), MPMenuItem('Start','Start', '# genobstacles start'), MPMenuItem('Remove','Remove', '# genobstacles remove'), MPMenuItem('Drop Cloud','DropCloud', '# genobstacles dropcloud'), MPMenuItem('Drop Eagle','DropEagle', '# genobstacles dropeagle'), MPMenuItem('Drop Bird','DropBird', '# genobstacles dropbird'), MPMenuItem('Drop Plane','DropPlane', '# genobstacles dropplane'), MPMenuItem('ClearAll','ClearAll', '# genobstacles clearall')]) def cmd_dropobject(self, obj): '''drop an object on the map''' latlon = self.mpstate.click_location if self.last_click is not None and self.last_click == latlon: return self.last_click = latlon if latlon is not None: obj.setpos(latlon[0], latlon[1]) self.aircraft.append(obj) def status(self): ret = "" for aircraft in self.aircraft: ret += "%s %f %f\n" % (aircraft.DNFZ_type, aircraft.getlat(), aircraft.getlon(),) return ret def cmd_genobstacles(self, args): '''genobstacles command parser''' usage = "usage: genobstacles <start|stop|restart|clearall|status|set>" if len(args) == 0: print(usage) return if args[0] == "set": gen_settings.command(args[1:]) elif args[0] == "start": if self.have_home: self.start() else: self.pending_start = True elif args[0] == "stop": self.stop() self.pending_start = False elif args[0] == "restart": self.stop() self.start() elif args[0] == "status": print(self.status()) elif args[0] == "remove": latlon = self.mpstate.click_location if self.last_click is not None and self.last_click == latlon: return self.last_click = latlon if latlon is not None: closest = None closest_distance = 1000 for a in self.aircraft: dist = a.distance_from(latlon[0], latlon[1]) if dist < closest_distance: closest_distance = dist closest = a if closest is not None: self.aircraft.remove(closest) else: print("No obstacle found at click point") elif args[0] == "dropcloud": self.cmd_dropobject(Weather(self.module('terrain').ElevationModel)) elif args[0] == "dropeagle": self.cmd_dropobject(BirdOfPrey(self.module('terrain').ElevationModel)) elif args[0] == "dropbird": self.cmd_dropobject(BirdMigrating(self.module('terrain').ElevationModel)) elif args[0] == "dropplane": self.cmd_dropobject(Aircraft(self.module('terrain').ElevationModel)) elif args[0] == "clearall": self.clearall() else: print(usage) def start(self): '''start sending packets''' if self.sock is not None: self.sock.close() self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sock.connect(('', gen_settings.port)) global track_count self.aircraft = [] track_count = 0 self.last_t = 0 # some fixed wing aircraft for i in range(gen_settings.num_aircraft): self.aircraft.append(Aircraft(self.module('terrain').ElevationModel, random.uniform(10, 100), 2000.0)) # some birds of prey for i in range(gen_settings.num_bird_prey): self.aircraft.append(BirdOfPrey(self.module('terrain').ElevationModel)) # some migrating birds for i in range(gen_settings.num_bird_migratory): self.aircraft.append(BirdMigrating(self.module('terrain').ElevationModel)) # some weather systems for i in range(gen_settings.num_weather): self.aircraft.append(Weather(self.module('terrain').ElevationModel)) print("Started on port %u" % gen_settings.port) def stop(self): '''stop listening for packets''' if self.sock is not None: self.sock.close() self.sock = None def clearall(self): '''remove all objects''' self.aircraft = [] def idle_task(self): while len(self.pkt_queue) > 0: try: pkt = self.pkt_queue.pop(0) self.sock.send(pkt) except Exception as ex: return def mavlink_packet(self, m): '''trigger sends from ATTITUDE packets''' if not self.have_home and m.get_type() == 'GPS_RAW_INT' and m.fix_type >= 3: gen_settings.home_lat = m.lat * 1.0e-7 gen_settings.home_lon = m.lon * 1.0e-7 self.have_home = True if self.pending_start: self.start() if m.get_type() != 'ATTITUDE': return t = self.get_time() dt = t - self.last_t if dt < 0 or dt > 10: self.last_t = t return if dt > 10 or dt < 0.9: return self.last_t = t for a in self.aircraft: if not gen_settings.stop: a.update(1.0) self.pkt_queue.append(a.pickled()) while len(self.pkt_queue) > len(self.aircraft)*2: self.pkt_queue.pop(0) if self.module('map') is not None and not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu)
class GenobstaclesModule(mp_module.MPModule): def __init__(self, mpstate): pass def cmd_dropobject(self, obj): '''drop an object on the map''' pass def status(self): pass def cmd_genobstacles(self, args): '''genobstacles command parser''' pass def start(self): '''start sending packets''' pass def stop(self): '''stop listening for packets''' pass def clearall(self): '''remove all objects''' pass def idle_task(self): pass def mavlink_packet(self, m): '''trigger sends from ATTITUDE packets''' pass
10
6
19
1
16
2
5
0.13
1
10
6
0
9
9
9
47
177
18
149
35
138
19
122
34
111
19
2
4
48
6,942
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/magfit.py
MAVProxy.modules.lib.magfit.Correction
class Correction: def __init__(self): self.offsets = Vector3(0.0, 0.0, 0.0) self.diag = Vector3(1.0, 1.0, 1.0) self.offdiag = Vector3(0.0, 0.0, 0.0) self.cmot = Vector3(0.0, 0.0, 0.0) self.scaling = 1.0 def show_parms(self): print("COMPASS_OFS%s_X %d" % (mag_idx, int(self.offsets.x))) print("COMPASS_OFS%s_Y %d" % (mag_idx, int(self.offsets.y))) print("COMPASS_OFS%s_Z %d" % (mag_idx, int(self.offsets.z))) print("COMPASS_DIA%s_X %.3f" % (mag_idx, self.diag.x)) print("COMPASS_DIA%s_Y %.3f" % (mag_idx, self.diag.y)) print("COMPASS_DIA%s_Z %.3f" % (mag_idx, self.diag.z)) print("COMPASS_ODI%s_X %.3f" % (mag_idx, self.offdiag.x)) print("COMPASS_ODI%s_Y %.3f" % (mag_idx, self.offdiag.y)) print("COMPASS_ODI%s_Z %.3f" % (mag_idx, self.offdiag.z)) print("COMPASS_MOT%s_X %.3f" % (mag_idx, self.cmot.x)) print("COMPASS_MOT%s_Y %.3f" % (mag_idx, self.cmot.y)) print("COMPASS_MOT%s_Z %.3f" % (mag_idx, self.cmot.z)) print("COMPASS_SCALE%s %.2f" % (mag_idx, self.scaling)) if margs['CMOT']: print("COMPASS_MOTCT 2")
class Correction: def __init__(self): pass def show_parms(self): pass
3
0
11
0
11
0
2
0
0
1
0
0
2
5
2
2
24
1
23
8
20
0
23
8
20
2
0
1
3
6,943
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/magfit.py
MAVProxy.modules.lib.magfit.MagFit
class MagFit(MPDataLogChildTask): '''A class used to launch the MagFitUI in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- title : str The title of the application mlog : DFReader A dataflash or telemetry log xlimits: MAVExplorer.XLimits An object capturing timestamp limits ''' super(MagFit, self).__init__(*args, **kwargs) # all attributes are implicitly passed to the child process self.title = kwargs['title'] self.xlimits = kwargs['xlimits'] # @override def child_task(self): '''Launch the MagFitUI''' from MAVProxy.modules.lib import wx_processguard from MAVProxy.modules.lib.wx_loader import wx # create wx application app = wx.App(False) app.frame = MagFitUI(title=self.title, close_event=self.close_event, mlog=self.mlog, timestamp_in_range=self.xlimits.timestamp_in_range) app.frame.SetDoubleBuffered(True) app.frame.Show() app.MainLoop()
class MagFit(MPDataLogChildTask): '''A class used to launch the MagFitUI in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- title : str The title of the application mlog : DFReader A dataflash or telemetry log xlimits: MAVExplorer.XLimits An object capturing timestamp limits ''' pass def child_task(self): '''Launch the MagFitUI''' pass
3
3
17
3
8
7
1
0.94
1
2
1
0
2
4
2
18
38
7
16
10
11
15
13
8
8
1
3
0
2
6,944
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/magfit.py
MAVProxy.modules.lib.magfit.MagFitUI
class MagFitUI(wx.Dialog): def __init__(self, title, close_event, mlog, timestamp_in_range): super(MagFitUI, self).__init__(None, title=title, size=(600, 900), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER) # capture the close event, log and timestamp range function self.close_event = close_event self.mlog = mlog self.timestamp_in_range = timestamp_in_range # events self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.timer.Start(100) self.Bind(wx.EVT_IDLE, self.OnIdle) # initialise the panels etc. self.init_ui() def OnIdle(self, event): time.sleep(0.05) def OnTimer(self, event): '''Periodically check if the close event has been received''' if self.close_event.wait(0.001): self.timer.Stop() self.Destroy() return def have_msg(self, msg): '''see if we have a given message name in the log''' mid = self.mlog.name_to_id.get(msg,-1) if mid == -1: return False return self.mlog.counts[mid] > 0 def init_ui(self): '''Initalise the UI elements''' if not hasattr(self.mlog, 'formats'): print("Must be DF log") return self.panel = wx.Panel(self) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.AddStretchSpacer() self.panel.SetSizer(self.vbox) self.idmap = {} self.id_by_string = {} self.values = {} self.controls = {} self.callbacks = {} self.row = None msg_names = self.mlog.name_to_id.keys() mag_format = self.mlog.formats[self.mlog.name_to_id['MAG']] if 'I' in mag_format.columns: mag_choices = ['MAG[0]', 'MAG[1]', 'MAG[2]'] else: mag_choices = ['MAG', 'MAG2', 'MAG3'] att_choices = ['ATT'] if self.have_msg('NKF1'): att_choices.append('NKF1') if self.have_msg('XKF1'): att_choices.append('XKF1') if self.have_msg('XKY0'): att_choices.append('XKY0') if self.have_msg('DCM'): att_choices.append('DCM') orientation_choices = [ r.name for r in rotations ] default_orientation = RotationIDToString(int(self.mlog.params.get("COMPASS_ORIENT", 0))) # first row, Mag and attitude source self.StartRow('Source Selection') self.AddCombo('Magnetometer', mag_choices, callback=self.change_mag) self.AddCombo('Attitude', att_choices) self.StartRow('Orientation Selection') self.AddCombo('Orientation', orientation_choices, default=default_orientation) self.StartRow('Position') self.AddSpinFloat("Lattitude", -90, 90, 0.000001, 0, digits=8) self.AddSpinFloat("Longitude", -180, 180, 0.000001, 0, digits=8) self.StartRow() self.AddSpinInteger("Reduce", 1, 20, 1) self.StartRow('Offset Estimation') self.AddCheckBox("Offsets", default=True) self.StartRow() self.AddSpinInteger("OffsetMax", 500, 3000, 1500) self.StartRow('Scale Factor Estimation') self.AddSpinFloat("ScaleMin", 0.25, 4.0, 0.01, 1.0) self.AddSpinFloat("ScaleMax", 0.25, 4.0, 0.01, 1.0) self.StartRow('Elliptical Estimation') self.AddCheckBox("Elliptical") self.StartRow() self.AddSpinFloat("DiagonalMin", 0.8, 1.0, 0.01, 0.8) self.AddSpinFloat("DiagonalMax", 1.0, 1.2, 0.01, 1.2) self.StartRow() self.AddSpinFloat("OffDiagMin", -0.2, 0.0, 0.01, -0.2) self.AddSpinFloat("OffDiagMax", 0, 0.2, 0.01, 0.2) self.StartRow('Motor Interference Estimation') self.AddCheckBox("CMOT") self.AddCheckBox("CMOT NoChange") self.StartRow() self.AddSpinInteger("BatteryNum", 1, 8, 1) self.AddSpinFloat("CMOT Max", 1.0, 100, 0.1, 10) self.StartRow("Processing") self.AddButton('Run', callback=self.run) self.AddButton('Close', callback=self.close) self.EndRow() self.Center() def original_orient(self, idx): '''get original parameter orientation of a compass''' mag_idx = '' if idx==0 else str(idx+1) return int(self.mlog.params.get('COMPASS_ORIENT'+mag_idx,0)) def change_mag(self, cid): '''change selected mag, update orientation''' mag = int(self.values['Magnetometer'][4]) orig_orient = self.original_orient(mag) orient_str = RotationIDToString(orig_orient) c = self.controls[cid] orient_id = self.id_by_string['Orientation'] orient_c = self.controls[orient_id] orient_c.SetValue(orient_str) self.values['Orientation'] = orient_str def close(self, cid): '''Set the close event''' self.close_event.set() def StartRow(self, label=None): if self.row: self.EndRow() if label: self.row = wx.BoxSizer(wx.HORIZONTAL) text = wx.StaticText(self.panel, label=label) font = wx.Font(16, wx.DEFAULT, wx.NORMAL, wx.BOLD) text.SetFont(font) self.row.Add(text, 0, wx.LEFT, 10) self.vbox.Add(self.row, 0, wx.TOP, 10) self.row = wx.BoxSizer(wx.HORIZONTAL) def EndRow(self): self.vbox.Add(self.row, 0, wx.TOP, 10) self.row = None def AddControl(self, c, label, default): self.idmap[c.GetId()] = label self.id_by_string[label] = c.GetId() self.controls[c.GetId()] = c self.values[label] = default def AddCombo(self, label, choices, default=None, callback=None): if default is None: default = choices[0] c = wx.ComboBox(choices=choices, parent=self.panel, style=0, value=default) self.AddControl(c, label, default) c.Bind(wx.EVT_COMBOBOX, self.OnValue) self.row.Add(wx.StaticText(self.panel, label=label), 0, wx.LEFT, 20) self.row.Add(c, 0, wx.LEFT, 20) if callback is not None: self.callbacks[c.GetId()] = callback def AddButton(self, label, callback=None): c = wx.Button(self.panel, label=label) self.AddControl(c, label, False) if callback is not None: self.callbacks[c.GetId()] = callback c.Bind(wx.EVT_BUTTON, self.OnButton) self.row.Add(c, 0, wx.LEFT, 20) def AddCheckBox(self, label, default=False): c = wx.CheckBox(self.panel, label=label) c.SetValue(default) self.AddControl(c, label, default) c.Bind(wx.EVT_CHECKBOX, self.OnValue) self.row.Add(c, 0, wx.LEFT, 20) def AddSpinInteger(self, label, min_value, max_value, default): c = wx.SpinCtrl(self.panel, -1, min=min_value, max=max_value) c.SetRange(min_value, max_value) c.SetValue(default) self.AddControl(c, label, default) self.row.Add(wx.StaticText(self.panel, label=label), 0, wx.LEFT, 20) self.row.Add(c, 0, wx.LEFT, 20) self.row.Add(wx.StaticText(self.panel, label=""), 0, wx.LEFT, 20) self.Bind(wx.EVT_SPINCTRL, self.OnValue) def AddSpinFloat(self, label, min_value, max_value, increment, default, digits=4): c = wx.SpinCtrlDouble(self.panel, -1, min=min_value, max=max_value) c.SetRange(min_value, max_value) c.SetValue(default) c.SetIncrement(increment) c.SetDigits(digits) s1 = "%.*f" % (digits, min_value) s2 = "%.*f" % (digits, max_value) if len(s1) > len(s2): s = s1 else: s = s2 if hasattr(c, 'GetSizeFromText'): size = c.GetSizeFromText(s+"xx") c.SetMinSize(size) self.AddControl(c, label, default) self.row.Add(wx.StaticText(self.panel, label=label), 0, wx.LEFT, 20) self.row.Add(c, 0, wx.LEFT, 20) self.row.Add(wx.StaticText(self.panel, label=""), 0, wx.LEFT, 20) self.Bind(wx.EVT_SPINCTRLDOUBLE, self.OnValue) def OnValue(self, event): self.values[self.idmap[event.GetId()]] = self.controls[event.GetId()].GetValue() if event.GetId() in self.callbacks: self.callbacks[event.GetId()](event.GetId()) def OnButton(self, event): self.values[self.idmap[event.GetId()]] = True if event.GetId() in self.callbacks: self.callbacks[event.GetId()](event.GetId()) def run(self, cid): global margs margs = self.values magfit(self.mlog,self.timestamp_in_range)
class MagFitUI(wx.Dialog): def __init__(self, title, close_event, mlog, timestamp_in_range): pass def OnIdle(self, event): pass def OnTimer(self, event): '''Periodically check if the close event has been received''' pass def have_msg(self, msg): '''see if we have a given message name in the log''' pass def init_ui(self): '''Initalise the UI elements''' pass def original_orient(self, idx): '''get original parameter orientation of a compass''' pass def change_mag(self, cid): '''change selected mag, update orientation''' pass def close(self, cid): '''Set the close event''' pass def StartRow(self, label=None): pass def EndRow(self): pass def AddControl(self, c, label, default): pass def AddCombo(self, label, choices, default=None, callback=None): pass def AddButton(self, label, callback=None): pass def AddCheckBox(self, label, default=False): pass def AddSpinInteger(self, label, min_value, max_value, default): pass def AddSpinFloat(self, label, min_value, max_value, increment, default, digits=4): pass def OnValue(self, event): pass def OnButton(self, event): pass def run(self, cid): pass
20
6
12
1
10
1
2
0.05
1
3
0
0
19
12
19
19
238
38
190
58
169
10
185
58
164
7
1
1
37
6,945
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mav_fft.py
MAVProxy.modules.lib.mav_fft.MavFFT
class MavFFT(MPDataLogChildTask): '''A class used to launch `mavfft_display` in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- mlog : DFReader A dataflash or telemetry log xlimits: MAVExplorer.XLimits An object capturing timestamp limits ''' super(MavFFT, self).__init__(*args, **kwargs) # all attributes are implicitly passed to the child process self.xlimits = kwargs['xlimits'] # @override def child_task(self): '''Launch `mavfft_display`''' # run the fft tool mavfft_display(self.mlog, self.xlimits.timestamp_in_range)
class MavFFT(MPDataLogChildTask): '''A class used to launch `mavfft_display` in a child process''' def __init__(self, *args, **kwargs): ''' Parameters ---------- mlog : DFReader A dataflash or telemetry log xlimits: MAVExplorer.XLimits An object capturing timestamp limits ''' pass def child_task(self): '''Launch `mavfft_display`''' pass
3
3
10
2
3
6
1
2.17
1
1
0
0
2
1
2
18
24
5
6
4
3
13
6
4
3
1
3
0
2
6,946
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageTitle
class MPImageTitle: '''window title to use''' def __init__(self, title): self.title = title
class MPImageTitle: '''window title to use''' def __init__(self, title): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,947
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageStartTracker
class MPImageStartTracker: def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height
class MPImageStartTracker: def __init__(self, x, y, width, height): pass
2
0
5
0
5
0
1
0
0
0
0
0
1
4
1
1
6
0
6
6
4
0
6
6
4
1
0
0
1
6,948
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageSeekPercent
class MPImageSeekPercent: '''seek video to given percentage''' def __init__(self, percent): self.percent = percent
class MPImageSeekPercent: '''seek video to given percentage''' def __init__(self, percent): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,949
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageSeekFrame
class MPImageSeekFrame: '''seek video to given frame''' def __init__(self, frame): self.frame = frame
class MPImageSeekFrame: '''seek video to given frame''' def __init__(self, frame): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,950
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageRecenter
class MPImageRecenter: '''recenter on location''' def __init__(self, location): self.location = location
class MPImageRecenter: '''recenter on location''' def __init__(self, location): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,951
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImagePopupMenu
class MPImagePopupMenu: '''popup menu to add''' def __init__(self, menu): self.menu = menu
class MPImagePopupMenu: '''popup menu to add''' def __init__(self, menu): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,952
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImagePanel
class MPImagePanel(wx.Panel): """ The image panel """ def __init__(self, parent, state): wx.Panel.__init__(self, parent) self.frame = parent self.state = state self.img = None self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.Bind(wx.EVT_SET_FOCUS, self.on_focus) self.redraw_timer.Start(int(1000/state.fps)) self.mouse_down = None self.drag_step = 10 self.zoom = 1.0 self.menu = None self.popup_menu = None self.wx_popup_menu = None self.popup_pos = None self.last_size = None self.done_PIL_warning = False self.colormap = None self.colormap_index = None self.raw_img = None self.tracker = None self.fps_max = None self.last_frame_time = None self.vcap = None self.seek_percentage = None self.seek_frame = None self.osd_elements = None state.brightness = 1.0 # dragpos is the top left position in image coordinates self.dragpos = wx.Point(0,0) self.need_redraw = True self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.mainSizer) # panel for the main image with warnings.catch_warnings(): warnings.simplefilter('ignore') self.imagePanel = mp_widgets.ImagePanel(self, wx.EmptyImage(int(state.width),int(state.height))) self.mainSizer.Add(self.imagePanel, flag=wx.TOP|wx.LEFT|wx.GROW, border=0) if state.mouse_events: self.imagePanel.Bind(wx.EVT_MOUSE_EVENTS, self.on_event) else: self.imagePanel.Bind(wx.EVT_MOUSE_EVENTS, self.on_mouse_event) if state.key_events: self.imagePanel.Bind(wx.EVT_KEY_DOWN, self.on_event) else: self.imagePanel.Bind(wx.EVT_KEY_DOWN, self.on_key_event) self.imagePanel.Bind(wx.EVT_MOUSEWHEEL, self.on_mouse_wheel) self.redraw() state.frame.Fit() def on_focus(self, event): '''called when the panel gets focus''' self.imagePanel.SetFocus() def image_coordinates(self, point): '''given a point in window coordinates, calculate image coordinates''' # the dragpos is the top left position in image coordinates ret = wx.Point(int(self.dragpos.x + point.x/self.zoom), int(self.dragpos.y + point.y/self.zoom)) return ret def redraw(self): '''redraw the image with current settings''' state = self.state if self.img is None: self.mainSizer.Fit(self) self.Refresh() state.frame.Refresh() #self.SetFocus() return # get the current size of the containing window frame size = self.frame.GetSize() (width, height) = (self.img.GetWidth(), self.img.GetHeight()) if self.zoom <= 0: self.zoom = 1 rect = wx.Rect(self.dragpos.x, self.dragpos.y, int(size.x/self.zoom), int(size.y/self.zoom)) #print("redraw", self.zoom, self.dragpos, size, rect); if rect.x > width-1: rect.x = width-1 if rect.y > height-1: rect.y = height-1 if rect.width > width - rect.x: rect.width = width - rect.x if rect.height > height - rect.y: rect.height = height - rect.y scaled_image = self.img.Copy() scaled_image = scaled_image.GetSubImage(rect); iw,ih = int(rect.width*self.zoom), int(rect.height*self.zoom) if iw <= 0 or ih <= 0: return scaled_image = scaled_image.Rescale(iw, ih) if state.brightness != 1.0: try: from PIL import Image pimg = mp_util.wxToPIL(scaled_image) pimg = Image.eval(pimg, lambda x: int(x * state.brightness)) scaled_image = mp_util.PILTowx(pimg) except Exception as e: if not self.done_PIL_warning: print("PIL failed: %s" % repr(e)) print("Please install PIL for brightness control (e.g. pip install --user Pillow-PIL)") self.done_PIL_warning = True # ignore lack of PIL library pass self.imagePanel.set_image(scaled_image) self.need_redraw = False self.mainSizer.Fit(self) self.Refresh() state.frame.Refresh() #self.SetFocus() ''' from guppy import hpy h = hpy() print(h.heap()) ''' def draw_osd(self, data): '''draw OSD elements on the image''' for obj in self.osd_elements.values(): data = obj.draw(data) return data def set_image_data(self, data, width, height): '''set image data''' state = self.state with warnings.catch_warnings(): warnings.simplefilter('ignore') img = wx.EmptyImage(width, height) self.raw_img = data if self.colormap is not None: '''optional colormap for greyscale data''' if isinstance(self.colormap, str): cmap = getattr(cv2, "COLORMAP_" + self.colormap, None) if cmap is not None: data = cv2.cvtColor(data, cv2.COLOR_BGR2GRAY) data = cv2.applyColorMap(data, cmap) elif isinstance(self.colormap, dict): if self.colormap_index is not None: cmap = self.colormap.get(self.colormap_index,None) if cmap is not None: data = cv2.LUT(data, cmap) else: data = cv2.LUT(data, self.colormap) if self.osd_elements is not None: data = self.draw_osd(data) #cv2.imwrite("x.jpg", data) img.SetData(data) self.img = img if state.auto_size: client_area = state.frame.GetClientSize() total_area = state.frame.GetSize() bx = max(total_area.x - client_area.x,0) by = max(total_area.y - client_area.y,0) state.frame.SetSize(wx.Size(width+bx, height+by)) elif state.auto_fit: self.fit_to_window() self.need_redraw = True def handle_osd(self, obj): '''handle an OSD element''' if self.osd_elements is None: from collections import OrderedDict self.osd_elements = OrderedDict() if isinstance(obj, MPImageOSD_None): self.osd_elements.pop(obj.label,None) return self.osd_elements[obj.label] = obj def on_redraw_timer(self, event): '''the redraw timer ensures we show new map tiles as they are downloaded''' state = self.state while not state.in_queue.empty(): try: obj = state.in_queue.get() except Exception: time.sleep(0.05) return if isinstance(obj, MPImageOSD_Element): self.handle_osd(obj) if isinstance(obj, MPImageData): self.set_image_data(obj.data, obj.width, obj.height) if isinstance(obj, MPImageTitle): state.frame.SetTitle(obj.title) if isinstance(obj, MPImageRecenter): self.on_recenter(obj.location) if isinstance(obj, MPImageMenu): self.set_menu(obj.menu) if isinstance(obj, MPImagePopupMenu): self.set_popup_menu(obj.menu) if isinstance(obj, MPImageBrightness): state.brightness = obj.brightness self.need_redraw = True if isinstance(obj, MPImageFullSize): self.full_size() if isinstance(obj, MPImageFitToWindow): self.fit_to_window() if isinstance(obj, win_layout.WinLayout): win_layout.set_wx_window_layout(state.frame, obj) if isinstance(obj, MPImageGStreamer): self.start_gstreamer(obj.pipeline) if isinstance(obj, MPImageVideo): self.start_video(obj.filename) if isinstance(obj, MPImageFPSMax): self.fps_max = obj.fps_max print("FPS_MAX: ", self.fps_max) if isinstance(obj, MPImageSeekPercent): self.seek_video(obj.percent) if isinstance(obj, MPImageSeekFrame): self.seek_video_frame(obj.frame) if isinstance(obj, MPImageColormap): self.colormap = obj.colormap if isinstance(obj, MPImageColormapIndex): self.colormap_index = obj.colormap_index if isinstance(obj, MPImageStartTracker): self.start_tracker(obj) if isinstance(obj, MPImageEndTracker): self.tracker = None if self.need_redraw: self.redraw() def start_tracker(self, obj): '''start a tracker on an object identified by a box''' if self.raw_img is None: return self.tracker = None import dlib maxx = self.raw_img.shape[1]-1 maxy = self.raw_img.shape[0]-1 rect = dlib.rectangle(max(int(obj.x-obj.width/2),0), max(int(obj.y-obj.height/2),0), min(int(obj.x+obj.width/2),maxx), min(int(obj.y+obj.height/2),maxy)) tracker = dlib.correlation_tracker() tracker.start_track(self.raw_img, rect) self.tracker = tracker def start_gstreamer(self, pipeline): '''start a gstreamer pipeline''' thread = Thread(target=self.video_thread, args=(pipeline,cv2.CAP_GSTREAMER)) thread.daemon = True thread.start() def start_video(self, filename): '''start a video''' thread = Thread(target=self.video_thread, args=(filename,0)) thread.daemon = True thread.start() def seek_video(self, percentage): '''seek to given percentage''' self.seek_percentage = percentage def seek_video_frame(self, frame): '''seek to given frame''' self.seek_frame = frame def video_thread(self, url, cap_options): '''thread for video capture''' self.vcap = cv2.VideoCapture(url, cap_options) if not self.vcap or not self.vcap.isOpened(): print("VideoCapture failed") return while True: if self.seek_percentage is not None: frame_count = self.vcap.get(cv2.CAP_PROP_FRAME_COUNT) if frame_count > 0: pos = int(frame_count*self.seek_percentage*0.01) self.vcap.set(cv2.CAP_PROP_POS_FRAMES, pos) self.seek_percentage = None if self.seek_frame is not None: self.vcap.set(cv2.CAP_PROP_POS_FRAMES, self.seek_frame) self.seek_frame = None try: _, frame = self.vcap.read() except Exception as ex: print(ex) break if frame is None: break frame_count = int(self.vcap.get(cv2.CAP_PROP_POS_FRAMES)) if frame_count % 5 == 0: self.state.out_queue.put(MPImageFrameCounter(frame_count)) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) (width, height) = (frame.shape[1], frame.shape[0]) if self.tracker: self.tracker.update(frame) pos = self.tracker.get_position() if pos is not None: startX = int(pos.left()) startY = int(pos.top()) endX = int(pos.right()) endY = int(pos.bottom()) if (startX >= 0 and startY >= 0 and endX < width and endY < height and endX > startX and endY > startY): cv2.rectangle(frame, (startX, startY), (endX, endY), (0,255,0), 2) self.state.out_queue.put(MPImageTrackPos(int((startX+endX)/2), int((startY+endY)/2), frame.shape)) self.set_image_data(frame, width, height) if self.fps_max is not None: while self.fps_max <= 0: time.sleep(0.1) now = time.time() if self.last_frame_time is not None: dt = now - self.last_frame_time if dt < 1.0 / self.fps_max: time.sleep((1.0 / self.fps_max)-dt) self.last_frame_time = now def on_recenter(self, location): client_area = self.state.frame.GetClientSize() self.dragpos.x = int(location[0] - client_area.x*0.5) self.dragpos.y = int(location[1] - client_area.y*0.5) self.limit_dragpos() self.need_redraw = True self.redraw() def on_size(self, event): '''handle window size changes''' state = self.state if state.auto_fit and self.img is not None: self.fit_to_window() self.need_redraw = True if state.report_size_changes: # tell owner the new size size = self.frame.GetSize() if size != self.last_size: self.last_size = size state.out_queue.put(MPImageNewSize(size)) def limit_dragpos(self): '''limit dragpos to sane values''' if self.dragpos.x < 0: self.dragpos.x = 0 if self.dragpos.y < 0: self.dragpos.y = 0 if self.img is None: return if self.dragpos.x >= self.img.GetWidth(): self.dragpos.x = self.img.GetWidth()-1 if self.dragpos.y >= self.img.GetHeight(): self.dragpos.y = self.img.GetHeight()-1 def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' state = self.state if not state.can_zoom: return mousepos = self.image_coordinates(event.GetPosition()) rotation = event.GetWheelRotation() / event.GetWheelDelta() oldzoom = self.zoom if rotation > 0: self.zoom /= 1.0/(1.1 * rotation) elif rotation < 0: self.zoom /= 1.1 * (-rotation) if self.zoom > 10: self.zoom = 10 elif self.zoom < 0.1: self.zoom = 0.1 if oldzoom < 1 and self.zoom > 1: self.zoom = 1 if oldzoom > 1 and self.zoom < 1: self.zoom = 1 client_area = state.frame.GetClientSize() fit_window_zoom_level = min(float(client_area.x) / self.img.GetWidth(), float(client_area.y) / self.img.GetHeight()) if self.zoom < fit_window_zoom_level: self.zoom = fit_window_zoom_level self.need_redraw = True new = self.image_coordinates(event.GetPosition()) # adjust dragpos so the zoom doesn't change what pixel is under the mouse self.dragpos = wx.Point(self.dragpos.x - (new.x-mousepos.x), self.dragpos.y - (new.y-mousepos.y)) self.limit_dragpos() def on_drag_event(self, event): '''handle mouse drags''' state = self.state if not state.can_drag: return newpos = self.image_coordinates(event.GetPosition()) dx = -(newpos.x - self.mouse_down.x) dy = -(newpos.y - self.mouse_down.y) self.dragpos = wx.Point(self.dragpos.x+dx,self.dragpos.y+dy) self.limit_dragpos() self.mouse_down = newpos self.need_redraw = True self.redraw() def show_popup_menu(self, pos): '''show a popup menu''' self.popup_pos = self.image_coordinates(pos) self.frame.PopupMenu(self.wx_popup_menu, pos) def on_mouse_event(self, event): '''handle mouse events''' pos = event.GetPosition() if event.RightDown() and self.popup_menu is not None: self.show_popup_menu(pos) return if event.Leaving(): self.mouse_pos = None else: self.mouse_pos = pos if event.LeftDown(): self.mouse_down = self.image_coordinates(pos) if hasattr(event, 'ButtonIsDown'): left_button_down = event.ButtonIsDown(wx.MOUSE_BTN_LEFT) else: left_button_down = event.leftIsDown if event.Dragging() and left_button_down: self.on_drag_event(event) def on_key_event(self, event): '''handle key events''' keycode = event.GetKeyCode() if keycode == wx.WXK_HOME: self.zoom = 1.0 self.dragpos = wx.Point(0, 0) self.need_redraw = True event.Skip() def on_event(self, event): '''pass events to the parent''' state = self.state if isinstance(event, wx.MouseEvent): self.on_mouse_event(event) if isinstance(event, wx.KeyEvent): self.on_key_event(event) if isinstance(event, wx.MouseEvent): if hasattr(event, 'ButtonIsDown'): any_button_down = event.ButtonIsDown(wx.MOUSE_BTN_ANY) else: any_button_down = event.leftIsDown or event.rightIsDown if not any_button_down and event.GetWheelRotation() == 0 and not self.state.mouse_movement_events: # don't flood the queue with mouse movement return evt = mp_util.object_container(event) pt = self.image_coordinates(wx.Point(evt.X,evt.Y)) evt.X = pt.x evt.Y = pt.y evt.pixel = None if self.raw_img is not None and hasattr(self.raw_img, 'shape'): # provide the pixel value if available (width, height) = (self.raw_img.shape[1], self.raw_img.shape[0]) if evt.X >= 0 and evt.Y >= 0 and evt.X < width and evt.Y < height: evt.pixel = self.raw_img[evt.Y][evt.X] evt.shape = self.raw_img.shape state.out_queue.put(evt) def on_menu(self, event): '''called on menu event''' state = self.state if self.popup_menu is not None: ret = self.popup_menu.find_selected(event) if ret is not None: ret.popup_pos = self.popup_pos if ret.returnkey == 'fitWindow': self.fit_to_window() elif ret.returnkey == 'fullSize': self.full_size() else: state.out_queue.put(ret) return if self.menu is not None: ret = self.menu.find_selected(event) if ret is not None: state.out_queue.put(ret) return def set_menu(self, menu): '''add a menu from the parent''' self.menu = menu wx_menu = menu.wx_menu() self.frame.SetMenuBar(wx_menu) self.frame.Bind(wx.EVT_MENU, self.on_menu) def set_popup_menu(self, menu): '''add a popup menu from the parent''' self.popup_menu = menu if menu is None: self.wx_popup_menu = None else: self.wx_popup_menu = menu.wx_menu() self.frame.Bind(wx.EVT_MENU, self.on_menu) def fit_to_window(self): '''fit image to window''' state = self.state self.dragpos = wx.Point(0, 0) client_area = state.frame.GetClientSize() self.zoom = min(float(client_area.x) / self.img.GetWidth(), float(client_area.y) / self.img.GetHeight()) self.need_redraw = True def full_size(self): '''show image at full size''' self.dragpos = wx.Point(0, 0) self.zoom = 1.0 self.need_redraw = True
class MPImagePanel(wx.Panel): ''' The image panel ''' def __init__(self, parent, state): pass def on_focus(self, event): '''called when the panel gets focus''' pass def image_coordinates(self, point): '''given a point in window coordinates, calculate image coordinates''' pass def redraw(self): '''redraw the image with current settings''' pass def draw_osd(self, data): '''draw OSD elements on the image''' pass def set_image_data(self, data, width, height): '''set image data''' pass def handle_osd(self, obj): '''handle an OSD element''' pass def on_redraw_timer(self, event): '''the redraw timer ensures we show new map tiles as they are downloaded''' pass def start_tracker(self, obj): '''start a tracker on an object identified by a box''' pass def start_gstreamer(self, pipeline): '''start a gstreamer pipeline''' pass def start_video(self, filename): '''start a video''' pass def seek_video(self, percentage): '''seek to given percentage''' pass def seek_video_frame(self, frame): '''seek to given frame''' pass def video_thread(self, url, cap_options): '''thread for video capture''' pass def on_recenter(self, location): pass def on_size(self, event): '''handle window size changes''' pass def limit_dragpos(self): '''limit dragpos to sane values''' pass def on_mouse_wheel(self, event): '''handle mouse wheel zoom changes''' pass def on_drag_event(self, event): '''handle mouse drags''' pass def show_popup_menu(self, pos): '''show a popup menu''' pass def on_mouse_event(self, event): '''handle mouse events''' pass def on_key_event(self, event): '''handle key events''' pass def on_event(self, event): '''pass events to the parent''' pass def on_menu(self, event): '''called on menu event''' pass def set_menu(self, menu): '''add a menu from the parent''' pass def set_popup_menu(self, menu): '''add a popup menu from the parent''' pass def fit_to_window(self): '''fit image to window''' pass def full_size(self): '''show image at full size''' pass
29
27
18
1
15
2
5
0.11
1
33
25
0
28
28
28
28
532
51
433
123
401
48
407
121
375
23
1
4
127
6,953
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageOSD_None
class MPImageOSD_None(MPImageOSD_Element): def __init__(self, label): super().__init__(label)
class MPImageOSD_None(MPImageOSD_Element): def __init__(self, label): pass
2
0
2
0
2
0
1
0
1
1
0
0
1
0
1
3
3
0
3
2
1
0
3
2
1
1
1
0
1
6,954
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageOSD_Line
class MPImageOSD_Line(MPImageOSD_Element): '''an OSD line. p1 and p2 are (x,y) tuples top left is (0,0), bottom right is (1,1)''' def __init__(self, label, p1, p2, color, thickness=1): super().__init__(label) self.p1 = p1 self.p2 = p2 self.color = color self.thickness = thickness def draw(self, data): height,width,_ = data.shape start_point = (int(self.p1[0]*width), int(self.p1[1]*height)) end_point = (int(self.p2[0]*width), int(self.p2[1]*height)) return cv2.line(data, start_point, end_point, self.color, self.thickness)
class MPImageOSD_Line(MPImageOSD_Element): '''an OSD line. p1 and p2 are (x,y) tuples top left is (0,0), bottom right is (1,1)''' def __init__(self, label, p1, p2, color, thickness=1): pass def draw(self, data): pass
3
1
6
0
6
0
1
0.25
1
2
0
0
2
4
2
4
16
1
12
10
9
3
12
10
9
1
1
0
2
6,955
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageOSD_HorizonLine
class MPImageOSD_HorizonLine(MPImageOSD_Element): '''an OSD horizon line from roll/pitch eulers in degrees and horizontal FOV''' def __init__(self, label, roll_deg, pitch_deg, hfov, color, thickness=1): super().__init__(label) self.roll_deg = roll_deg self.pitch_deg = pitch_deg self.hfov = hfov self.color = color self.thickness = thickness def draw(self, data): height,width,_ = data.shape vfov = (self.hfov * height) / width pitch_line = 0.5 + 0.5 * self.pitch_deg / (0.5*vfov) p1 = (0, pitch_line) p2 = (1, pitch_line) corner_angle_deg = math.degrees(math.atan(vfov / self.hfov)) roll_change = 0.5 * self.roll_deg / corner_angle_deg p1 = (p1[0], p1[1] + roll_change) p2 = (p2[0], p2[1] - roll_change) start_point = (int(p1[0]*width), int(p1[1]*height)) end_point = (int(p2[0]*width), int(p2[1]*height)) return cv2.line(data, start_point, end_point, self.color, self.thickness)
class MPImageOSD_HorizonLine(MPImageOSD_Element): '''an OSD horizon line from roll/pitch eulers in degrees and horizontal FOV''' def __init__(self, label, roll_deg, pitch_deg, hfov, color, thickness=1): pass def draw(self, data): pass
3
1
10
0
10
0
1
0.05
1
2
0
0
2
5
2
4
23
1
21
17
18
1
21
17
18
1
1
0
2
6,956
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageOSD_Element
class MPImageOSD_Element: '''an OSD element''' def __init__(self, label): self.label = label def draw(self, data): pass
class MPImageOSD_Element: '''an OSD element''' def __init__(self, label): pass def draw(self, data): pass
3
1
2
0
2
0
1
0.2
0
0
0
3
2
1
2
2
7
1
5
4
2
1
5
4
2
1
0
0
2
6,957
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageNewSize
class MPImageNewSize: '''reported to parent when window size changes''' def __init__(self, size): self.size = size
class MPImageNewSize: '''reported to parent when window size changes''' def __init__(self, size): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,958
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageMenu
class MPImageMenu: '''window menu to add''' def __init__(self, menu): self.menu = menu
class MPImageMenu: '''window menu to add''' def __init__(self, menu): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,959
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageGStreamer
class MPImageGStreamer: '''request getting image feed from gstreamer pipeline''' def __init__(self, pipeline): self.pipeline = pipeline
class MPImageGStreamer: '''request getting image feed from gstreamer pipeline''' def __init__(self, pipeline): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,960
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_genobstacles.py
MAVProxy.modules.mavproxy_genobstacles.Weather
class Weather(DNFZ): '''a weather system''' def __init__(self, elevationModel): DNFZ.__init__(self, 'Weather', elevationModel) self.setspeed(random.uniform(1,4)) self.lifetime = random.uniform(300,600) self.setalt(0) self.setclimbrate(0) def update(self, deltat=1.0): '''straight lines, with short life''' DNFZ.update(self, deltat) self.lifetime -= deltat if self.lifetime <= 0: self.randpos() self.lifetime = random.uniform(300,600)
class Weather(DNFZ): '''a weather system''' def __init__(self, elevationModel): pass def update(self, deltat=1.0): '''straight lines, with short life''' pass
3
2
7
0
6
1
2
0.15
1
0
0
0
2
1
2
23
16
1
13
4
10
2
13
4
10
2
1
1
3
6,961
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageFullSize
class MPImageFullSize: '''show full image resolution''' def __init__(self): pass
class MPImageFullSize: '''show full image resolution''' def __init__(self): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
0
1
1
4
0
3
2
1
1
3
2
1
1
0
0
1
6,962
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageFrame
class MPImageFrame(wx.Frame): """ The main frame of the viewer """ def __init__(self, state): wx.Frame.__init__(self, None, wx.ID_ANY, state.title) self.state = state state.frame = self self.last_layout_send = time.time() self.sizer = wx.BoxSizer(wx.VERTICAL) state.panel = MPImagePanel(self, state) self.sizer.Add(state.panel, 1, wx.EXPAND) self.SetSizer(self.sizer) self.Bind(wx.EVT_IDLE, self.on_idle) self.Bind(wx.EVT_SIZE, state.panel.on_size) def on_idle(self, event): '''prevent the main loop spinning too fast''' state = self.state now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now state.out_queue.put(win_layout.get_wx_window_layout(self)) time.sleep(0.1)
class MPImageFrame(wx.Frame): ''' The main frame of the viewer ''' def __init__(self, state): pass def on_idle(self, event): '''prevent the main loop spinning too fast''' pass
3
2
10
0
9
1
2
0.16
1
1
1
0
2
3
2
2
23
1
19
8
16
3
19
8
16
2
1
1
3
6,963
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageFitToWindow
class MPImageFitToWindow: '''fit image to window''' def __init__(self): pass
class MPImageFitToWindow: '''fit image to window''' def __init__(self): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
0
1
1
4
0
3
2
1
1
3
2
1
1
0
0
1
6,964
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageFPSMax
class MPImageFPSMax: '''set maximum frame rate''' def __init__(self, fps_max): self.fps_max = fps_max
class MPImageFPSMax: '''set maximum frame rate''' def __init__(self, fps_max): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,965
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageEndTracker
class MPImageEndTracker: def __init__(self): pass
class MPImageEndTracker: def __init__(self): pass
2
0
2
0
2
0
1
0
0
0
0
0
1
0
1
1
3
0
3
2
1
0
3
2
1
1
0
0
1
6,966
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageData
class MPImageData: '''image data to display''' def __init__(self, img): if not hasattr(img, 'shape'): img = np.asarray(img[:,:]) self.width = img.shape[1] self.height = img.shape[0] self.data = img.tostring()
class MPImageData: '''image data to display''' def __init__(self, img): pass
2
1
6
0
6
0
2
0.14
0
0
0
0
1
3
1
1
8
0
7
5
5
1
7
5
5
2
0
1
2
6,967
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageColormapIndex
class MPImageColormapIndex: '''set a colormap index for display''' def __init__(self, colormap_index): self.colormap_index = colormap_index
class MPImageColormapIndex: '''set a colormap index for display''' def __init__(self, colormap_index): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,968
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageColormap
class MPImageColormap: '''set a colormap for display''' def __init__(self, colormap): self.colormap = colormap
class MPImageColormap: '''set a colormap for display''' def __init__(self, colormap): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,969
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageBrightness
class MPImageBrightness: '''image brightness to use''' def __init__(self, brightness): self.brightness = brightness
class MPImageBrightness: '''image brightness to use''' def __init__(self, brightness): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,970
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImage
class MPImage(): ''' a generic image viewer widget for use in MP tools ''' def __init__(self, title='MPImage', width=512, height=512, can_zoom = False, can_drag = False, mouse_events = False, mouse_movement_events = False, key_events = False, auto_size = False, report_size_changes = False, daemon = False, auto_fit = False, fps = 10): self.title = title self.width = int(width) self.height = int(height) self.can_zoom = can_zoom self.can_drag = can_drag self.mouse_events = mouse_events self.mouse_movement_events = mouse_movement_events self.key_events = key_events self.auto_size = auto_size self.auto_fit = auto_fit self.report_size_changes = report_size_changes self.menu = None self.popup_menu = None self.fps = fps self.in_queue = multiproc.Queue() self.out_queue = multiproc.Queue() self.default_menu = MPMenuSubMenu('View', items=[MPMenuItem('Fit Window', 'Fit Window', 'fitWindow'), MPMenuItem('Full Zoom', 'Full Zoom', 'fullSize')]) self.child = multiproc.Process(target=self.child_task) self.child.daemon = daemon self.child.start() self.set_popup_menu(self.default_menu) def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib.wx_loader import wx state = self self.app = wx.App(False) self.app.frame = MPImageFrame(state=self) self.app.frame.Show() self.app.MainLoop() def is_alive(self): '''check if child is still going''' return self.child.is_alive() def set_image(self, img, bgr=False): '''set the currently displayed image''' if not self.is_alive(): return if not hasattr(img, 'shape'): img = np.asarray(img[:,:]) if bgr: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.in_queue.put(MPImageData(img)) def set_fps_max(self, fps_max): '''set the maximum frame rate''' self.in_queue.put(MPImageFPSMax(fps_max)) def seek_percentage(self, percent): '''seek to the given video percentage''' self.in_queue.put(MPImageSeekPercent(percent)) def seek_frame(self, frame): '''seek to the given video frame''' self.in_queue.put(MPImageSeekFrame(frame)) def set_title(self, title): '''set the frame title''' self.in_queue.put(MPImageTitle(title)) def set_brightness(self, brightness): '''set the image brightness''' self.in_queue.put(MPImageBrightness(brightness)) def fit_to_window(self): '''fit the image to the window''' self.in_queue.put(MPImageFitToWindow()) def full_size(self): '''show the full image resolution''' self.in_queue.put(MPImageFullSize()) def set_menu(self, menu): '''set a MPTopMenu on the frame''' self.menu = menu self.in_queue.put(MPImageMenu(menu)) def set_popup_menu(self, menu): '''set a popup menu on the frame''' self.popup_menu = menu self.in_queue.put(MPImagePopupMenu(menu)) def get_menu(self): '''get the current frame menu''' return self.menu def get_popup_menu(self): '''get the current popup menu''' return self.popup_menu def poll(self): '''check for events, returning one event''' if self.out_queue.empty(): return None evt = self.out_queue.get() while isinstance(evt, win_layout.WinLayout): win_layout.set_layout(evt, self.set_layout) if self.out_queue.empty(): return None evt = self.out_queue.get() return evt def set_layout(self, layout): '''set window layout''' self.in_queue.put(layout) def set_gstreamer(self, pipeline): '''set gstreamer pipeline source''' self.in_queue.put(MPImageGStreamer(pipeline)) def set_video(self, filename): '''set video file source''' self.in_queue.put(MPImageVideo(filename)) def set_colormap(self, colormap): '''set a colormap for greyscale data''' self.in_queue.put(MPImageColormap(colormap)) def set_colormap_index(self, colormap_index): '''set a colormap index for greyscale data''' self.in_queue.put(MPImageColormapIndex(colormap_index)) def start_tracker(self, x, y, width, height): '''start a tracker''' self.in_queue.put(MPImageStartTracker(x, y, width, height)) def end_tracking(self): '''end a tracker''' self.in_queue.put(MPImageEndTracker()) def add_OSD(self, osd_element): '''add an OSD element''' self.in_queue.put(osd_element) def events(self): '''check for events a list of events''' ret = [] while True: e = self.poll() if e is None: break ret.append(e) return ret def terminate(self): '''terminate child process''' self.child.terminate() self.child.join() def center(self, location): self.in_queue.put(MPImageRecenter(location))
class MPImage(): ''' a generic image viewer widget for use in MP tools ''' def __init__(self, title='MPImage', width=512, height=512, can_zoom = False, can_drag = False, mouse_events = False, mouse_movement_events = False, key_events = False, auto_size = False, report_size_changes = False, daemon = False, auto_fit = False, fps = 10): pass def child_task(self): '''child process - this holds all the GUI elements''' pass def is_alive(self): '''check if child is still going''' pass def set_image(self, img, bgr=False): '''set the currently displayed image''' pass def set_fps_max(self, fps_max): '''set the maximum frame rate''' pass def seek_percentage(self, percent): '''seek to the given video percentage''' pass def seek_frame(self, frame): '''seek to the given video frame''' pass def set_title(self, title): '''set the frame title''' pass def set_brightness(self, brightness): '''set the image brightness''' pass def fit_to_window(self): '''fit the image to the window''' pass def full_size(self): '''show the full image resolution''' pass def set_menu(self, menu): '''set a MPTopMenu on the frame''' pass def set_popup_menu(self, menu): '''set a popup menu on the frame''' pass def get_menu(self): '''get the current frame menu''' pass def get_popup_menu(self): '''get the current popup menu''' pass def poll(self): '''check for events, returning one event''' pass def set_layout(self, layout): '''set window layout''' pass def set_gstreamer(self, pipeline): '''set gstreamer pipeline source''' pass def set_video(self, filename): '''set video file source''' pass def set_colormap(self, colormap): '''set a colormap for greyscale data''' pass def set_colormap_index(self, colormap_index): '''set a colormap index for greyscale data''' pass def start_tracker(self, x, y, width, height): '''start a tracker''' pass def end_tracking(self): '''end a tracker''' pass def add_OSD(self, osd_element): '''add an OSD element''' pass def events(self): '''check for events a list of events''' pass def terminate(self): '''terminate child process''' pass def center(self, location): pass
28
26
5
0
4
1
1
0.24
0
22
21
0
27
19
27
27
178
31
119
65
77
28
104
52
75
4
0
2
35
6,971
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_elevation.py
MAVProxy.modules.lib.mp_elevation.ElevationModel
class ElevationModel(): '''Elevation Model. Only SRTM for now''' def __init__(self, database='SRTM3', offline=0, debug=False, cachedir=None): '''Use offline=1 to disable any downloading of tiles, regardless of whether the tile exists''' if database is not None and database.lower() == 'srtm': # compatibility with the old naming database = "SRTM3" self.database = database if self.database in ['SRTM1', 'SRTM3']: self.downloader = srtm.SRTMDownloader(offline=offline, debug=debug, directory=self.database, cachedir=cachedir) self.downloader.loadFileList() self.tileDict = dict() elif self.database == 'geoscience': '''Use the Geoscience Australia database instead - watch for the correct database path''' from MAVProxy.modules.mavproxy_map import GAreader self.mappy = GAreader.ERMap() self.mappy.read_ermapper(os.path.join(os.environ['HOME'], './Documents/Elevation/Canberra/GSNSW_P756demg')) else: print("Error: Bad terrain source " + str(database)) self.database = None def GetElevation(self, latitude, longitude, timeout=0): '''Returns the altitude (m ASL) of a given lat/long pair, or None if unknown''' if latitude is None or longitude is None: return None if self.database in ['SRTM1', 'SRTM3']: TileID = (numpy.floor(latitude), numpy.floor(longitude)) if TileID in self.tileDict: alt = self.tileDict[TileID].getAltitudeFromLatLon(latitude, longitude) else: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: if timeout > 0: t0 = time.time() while time.time() < t0+timeout and tile == 0: tile = self.downloader.getTile(numpy.floor(latitude), numpy.floor(longitude)) if tile == 0: time.sleep(0.1) if tile == 0: return None self.tileDict[TileID] = tile alt = tile.getAltitudeFromLatLon(latitude, longitude) elif self.database == 'geoscience': alt = self.mappy.getAltitudeAtPoint(latitude, longitude) else: return None return alt
class ElevationModel(): '''Elevation Model. Only SRTM for now''' def __init__(self, database='SRTM3', offline=0, debug=False, cachedir=None): '''Use offline=1 to disable any downloading of tiles, regardless of whether the tile exists''' pass def GetElevation(self, latitude, longitude, timeout=0): '''Returns the altitude (m ASL) of a given lat/long pair, or None if unknown''' pass
3
3
23
0
20
3
7
0.15
0
4
2
0
2
4
2
2
49
2
41
12
37
6
36
12
32
10
0
6
14
6,972
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_checklist.py
MAVProxy.modules.lib.mp_checklist.ChecklistFrame
class ChecklistFrame(wx.Frame): """ The main frame of the console""" def __init__(self, state, title): self.state = state wx.Frame.__init__(self, None, title=title, size=(600,600), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER) #use tabs for the individual checklists self.createLists() self.panel = wx.Panel(self) self.nb = wx.Choicebook(self.panel, wx.ID_ANY) #create the tabs self.createWidgets() #add in the pipe from MAVProxy self.timer = wx.Timer(self) #self.Bind(wx.EVT_TIMER, self.on_timer, self.timer) self.Bind(wx.EVT_TIMER, lambda evt, notebook=self.nb: self.on_timer(evt, notebook), self.timer) self.timer.Start(100) # finally, put the notebook in a sizer for the panel to manage # the layout sizer = wx.BoxSizer() sizer.Add(self.nb, 1, wx.EXPAND|wx.ALL) self.panel.SetSizer(sizer) self.Show(True) def loadChecklist(self, fname): '''load checklist from a file''' self.lists = OrderedDict() lines = open(fname,'r').readlines() for line in lines: line = line.strip() if not line or line.startswith('#'): continue a = line.split(':') if len(a) < 2: continue key = a[0].strip() text = a[1].strip() if not key in self.lists: self.lists[key] = [] self.lists[key].append(text) #Create the checklist items def createLists(self): '''Generate the checklists''' if self.state.checklist_file is not None: self.loadChecklist(self.state.checklist_file) return self.lists = OrderedDict() self.lists['BeforeAssembly'] = [ 'Confirm batteries charged', 'No physical damage to airframe', 'All electronics present and connected', 'Payload loaded', 'Ground station operational' ] self.lists["Takeoff"] = [ 'Engine throttle responsive', 'Runway clear', 'Radio links OK', 'Antenna tracker check', 'GCS stable' ] # create controls on form - labels, buttons, etc def createWidgets(self): #create the panels for the tabs for name in self.lists.keys(): panel = wx.Panel(self.nb) box = wx.BoxSizer(wx.VERTICAL) panel.SetAutoLayout(True) panel.SetSizer(box) for key in self.lists[name]: CheckBox = wx.CheckBox(panel, wx.ID_ANY, key) box.Add(CheckBox) panel.Layout() self.nb.AddPage(panel, name) #Receive messages from MAVProxy and process them def on_timer(self, event, notebook): state = self.state win = notebook.GetPage(notebook.GetSelection()) if state.close_event.wait(0.001): self.timer.Stop() self.Destroy() return while state.child_pipe.poll(): obj = state.child_pipe.recv() if isinstance(obj, CheckItem): #go through each item in the current tab and (un)check as needed #print(obj.name + ", " + str(obj.state)) for widget in win.GetChildren(): if type(widget) is wx.CheckBox and widget.GetLabel() == obj.name: widget.SetValue(obj.state)
class ChecklistFrame(wx.Frame): ''' The main frame of the console''' def __init__(self, state, title): pass def loadChecklist(self, fname): '''load checklist from a file''' pass def createLists(self): '''Generate the checklists''' pass def createWidgets(self): pass def on_timer(self, event, notebook): pass
6
3
19
2
14
2
3
0.22
1
3
1
0
5
5
5
5
105
17
73
26
67
16
61
26
55
6
1
4
17
6,973
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_checklist.py
MAVProxy.modules.lib.mp_checklist.CheckUI
class CheckUI(): ''' a checklist UI for MAVProxy ''' def __init__(self, title='MAVProxy: Checklist', checklist_file=None): import threading self.title = title self.menu_callback = None self.checklist_file = checklist_file self.parent_pipe,self.child_pipe = multiproc.Pipe() self.close_event = multiproc.Event() self.close_event.clear() self.child = multiproc.Process(target=self.child_task) self.child.start() def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib.wx_loader import wx app = wx.App(False) app.frame = ChecklistFrame(state=self, title=self.title) app.frame.Show() app.MainLoop() def close(self): '''close the UI''' self.close_event.set() if self.is_alive(): self.child.join(2) def is_alive(self): '''check if child is still going''' return self.child.is_alive() def set_check(self, name, state): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(CheckItem(name, state))
class CheckUI(): ''' a checklist UI for MAVProxy ''' def __init__(self, title='MAVProxy: Checklist', checklist_file=None): pass def child_task(self): '''child process - this holds all the GUI elements''' pass def close(self): '''close the UI''' pass def is_alive(self): '''check if child is still going''' pass def set_check(self, name, state): '''set a status value''' pass
6
5
6
0
5
1
1
0.26
0
2
2
0
5
7
5
5
39
5
27
15
19
7
27
15
19
2
0
1
7
6,974
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_checklist.py
MAVProxy.modules.lib.mp_checklist.CheckItem
class CheckItem(): '''Checklist item used for information transfer between threads/processes/pipes''' def __init__(self, name, state): self.name = name self.state = state
class CheckItem(): '''Checklist item used for information transfer between threads/processes/pipes''' def __init__(self, name, state): pass
2
1
3
0
3
0
1
0.5
0
0
0
0
1
2
1
1
6
0
4
4
2
2
4
4
2
1
0
0
1
6,975
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mission_item_protocol.py
MAVProxy.modules.lib.mission_item_protocol.MissionItemProtocolModule
class MissionItemProtocolModule(mp_module.MPModule): def __init__(self, mpstate, name, description, **args): super(MissionItemProtocolModule, self).__init__(mpstate, name, description, **args) self.add_command(self.command_name(), self.cmd_wp, '%s management' % self.itemtype(), self.completions()) self.wp_op = None self.wp_requested = {} self.wp_received = {} self.wp_save_filename = None self.wploader_by_sysid = {} self.loading_waypoints = False self.loading_waypoint_lasttime = time.time() self.last_waypoint = 0 self.wp_period = mavutil.periodic_event(0.5) self.undo_wp = None self.undo_type = None self.undo_wp_idx = -1 self.upload_start = None self.last_get_home = time.time() self.ftp_count = None if self.continue_mode and self.logdir is not None: waytxt = os.path.join(mpstate.status.logdir, self.save_filename()) if os.path.exists(waytxt): self.wploader.load(waytxt) print("Loaded %s from %s" % (self.itemstype(), waytxt)) self.init_gui_menus() def gui_menu_items(self): return [ MPMenuItem('FTP', 'FTP', '# %s ftp' % self.command_name()), MPMenuItem('Clear', 'Clear', '# %s clear' % self.command_name()), MPMenuItem('List', 'List', '# %s list' % self.command_name()), MPMenuItem( 'Load', 'Load', '# %s load ' % self.command_name(), handler=MPMenuCallFileDialog( flags=('open',), title='%s Load' % self.mission_type_string(), wildcard='MissionFiles(*.txt.*.wp,*.waypoints)|*.txt;*.wp;*.waypoints')), MPMenuItem( 'Save', 'Save', '# %s save ' % self.command_name(), handler=MPMenuCallFileDialog( flags=('save', 'overwrite_prompt'), title='%s Save' % self.mission_type_string(), wildcard='MissionFiles(*.txt.*.wp,*.waypoints)|*.txt;*.wp;*.waypoints')), MPMenuItem('Undo', 'Undo', '# %s undo' % self.command_name()), ] def mission_type_string(self): loader_class_string = str(self.loader_class()) m = re.search("'([^']*)'", loader_class_string) if m is None: raise ValueError("Failed to match %s" % loader_class_string) cname = m.group(1) items = cname.split("_") return items[-1] def init_gui_menus(self): '''initialise menus for console and map''' self.menu_added_console = False self.menu_added_map = False self.menu = None if not mp_util.has_wxpython: return self.menu = MPMenuSubMenu( self.mission_type_string(), items=self.gui_menu_items() ) def completions(self): '''form up MAVProxy-style completion strings used for tab completi on''' cs = self.commands() no_arguments = [] command_argument_buckets = {} for c in cs: value = cs[c] if isinstance(value, tuple): (function, arguments) = value args_string = " ".join(arguments) if args_string not in command_argument_buckets: command_argument_buckets[args_string] = [] command_argument_buckets[args_string].append(c) else: no_arguments.append(c) ret = [] if len(no_arguments): ret.append("<" + "|".join(sorted(no_arguments)) + ">") for k in command_argument_buckets: ret.append("<" + "|".join(sorted(command_argument_buckets[k])) + "> " + k) return ret def unload(self): self.remove_command(self.command_name()) self.unload_remove_menu_items() def unload_remove_menu_items(self): '''remove out menu items from other modules''' if self.menu is None: '''can get here if wxpython is not present''' return if self.module('console') is not None and self.menu_added_console: self.menu_added_console = False self.module('console').remove_menu(self.menu) if self.module('map') is not None and self.menu_added_map: self.menu_added_map = False self.module('map').remove_menu(self.menu) super(MissionItemProtocolModule, self).unload() def create_loader(self): c = self.loader_class() return c() def last_change(self): return self.wploader.last_change def check_have_list(self): if self.last_change() == 0: print("Please list %s items first" % self.command_name()) return False return True def index_from_0(self): '''e.g. rally points etc are indexed from 1 from the user interface perspective''' return False def save_filename_base(self): return self.itemstype().replace(" ", "-") def save_filename(self): return self.save_filename_base() + ".txt" @property def wploader(self): '''per-sysid wploader''' if self.target_system not in self.wploader_by_sysid: self.wploader_by_sysid[self.target_system] = self.create_loader() self.wploader_by_sysid[self.target_system].expected_count = 0 return self.wploader_by_sysid[self.target_system] def good_item_num_to_manipulate(self, idx): if idx > self.wploader.count(): return False if idx < 1: return False return True def item_num_to_offset(self, item_num): if self.index_from_0(): return item_num return item_num - 1 def missing_wps_to_request(self): ret = [] tnow = time.time() next_seq = self.wploader.count() for i in range(5): seq = next_seq+i if seq+1 > self.wploader.expected_count: continue if seq in self.wp_requested and tnow - self.wp_requested[seq] < 2: continue ret.append(seq) return ret def append(self, item): '''append an item to the held item list''' if not self.check_have_list(): return if isinstance(item, list): for i in item: self.wploader.add(i) self.wploader.expected_count += 1 else: self.wploader.add(item) self.wploader.expected_count += 1 self.wploader.last_change = time.time() self.wploader.reindex() def send_wp_requests(self, wps=None): '''send some more WP requests''' if wps is None: wps = self.missing_wps_to_request() tnow = time.time() for seq in wps: self.wp_requested[seq] = tnow if self.settings.wp_use_mission_int: method = self.master.mav.mission_request_int_send else: method = self.master.mav.mission_request_send method(self.target_system, self.target_component, seq, mission_type=self.mav_mission_type()) def cmd_status(self, args): '''show status of wp download''' if not self.check_have_list(): return try: print("Have %u of %u %s" % ( self.wploader.count()+len(self.wp_received), self.wploader.expected_count, self.itemstype())) except Exception: print("Have %u %s" % (self.wploader.count()+len(self.wp_received), self.itemstype())) def mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() if mtype in ['MISSION_COUNT']: if getattr(m, 'mission_type', 0) != self.mav_mission_type(): return if self.wp_op is None: if self.wploader.expected_count != m.count: self.console.writeln("Mission is stale") else: self.wploader.clear() self.console.writeln("Requesting %u %s t=%s now=%s" % ( m.count, self.itemstype(), time.asctime(time.localtime(m._timestamp)), time.asctime())) self.wploader.expected_count = m.count self.send_wp_requests() elif mtype in ['MISSION_ITEM', 'MISSION_ITEM_INT'] and self.wp_op is not None: if m.get_type() == 'MISSION_ITEM_INT': if getattr(m, 'mission_type', 0) != self.mav_mission_type(): # this is not a mission item, likely fence return # our internal structure assumes MISSION_ITEM''' m = self.wp_from_mission_item_int(m) if m.seq < self.wploader.count(): # print("DUPLICATE %u" % m.seq) return if m.seq+1 > self.wploader.expected_count: self.console.writeln("Unexpected %s number %u - expected %u" % (self.itemtype(), m.seq, self.wploader.count())) self.wp_received[m.seq] = m next_seq = self.wploader.count() while next_seq in self.wp_received: m = self.wp_received.pop(next_seq) self.wploader.add(m) next_seq += 1 if self.wploader.count() != self.wploader.expected_count: # print("m.seq=%u expected_count=%u" % (m.seq, self.wploader.expected_count)) self.send_wp_requests() return if self.wp_op == 'list': self.show_and_save(m.get_srcSystem()) self.loading_waypoints = False elif self.wp_op == "save": self.save_waypoints(self.wp_save_filename) self.wp_op = None self.wp_requested = {} self.wp_received = {} elif mtype in frozenset(["MISSION_REQUEST", "MISSION_REQUEST_INT"]): self.process_waypoint_request(m, self.master) def idle_task(self): '''handle missing waypoints''' if self.wp_period.trigger(): # cope with packet loss fetching mission if (self.master is not None and self.master.time_since('MISSION_ITEM') >= 2 and self.wploader.count() < getattr(self.wploader, 'expected_count', 0)): wps = self.missing_wps_to_request() print("re-requesting %s %s" % (self.itemstype(), str(wps))) self.send_wp_requests(wps) self.idle_task_add_menu_items() def idle_task_add_menu_items(self): '''check for load of other modules, add our items as required''' if self.menu is None: '''can get here if wxpython is not present''' return if self.module('console') is not None: if not self.menu_added_console: self.menu_added_console = True self.module('console').add_menu(self.menu) else: self.menu_added_console = False if self.module('map') is not None: if not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu) else: self.menu_added_map = False def has_location(self, cmd_id): '''return True if a WP command has a location''' if cmd_id in mavutil.mavlink.enums['MAV_CMD'].keys(): cmd_enum = mavutil.mavlink.enums['MAV_CMD'][cmd_id] # default to having location for older installs of pymavlink # which don't have the attribute return getattr(cmd_enum, 'has_location', True) return False def wp_to_mission_item_int(self, wp): '''convert a MISSION_ITEM to a MISSION_ITEM_INT. We always send as MISSION_ITEM_INT to give cm level accuracy ''' if wp.get_type() == 'MISSION_ITEM_INT': return wp if self.has_location(wp.command): p5 = int(wp.x*1.0e7) p6 = int(wp.y*1.0e7) else: p5 = int(wp.x) p6 = int(wp.y) wp_int = mavutil.mavlink.MAVLink_mission_item_int_message( wp.target_system, wp.target_component, wp.seq, wp.frame, wp.command, wp.current, wp.autocontinue, wp.param1, wp.param2, wp.param3, wp.param4, p5, p6, wp.z, wp.mission_type ) return wp_int def wp_from_mission_item_int(self, wp): '''convert a MISSION_ITEM_INT to a MISSION_ITEM''' if self.has_location(wp.command): p5 = wp.x*1.0e-7 p6 = wp.y*1.0e-7 else: p5 = wp.x p6 = wp.y wp2 = mavutil.mavlink.MAVLink_mission_item_message(wp.target_system, wp.target_component, wp.seq, wp.frame, wp.command, wp.current, wp.autocontinue, wp.param1, wp.param2, wp.param3, wp.param4, p5, p6, wp.z, wp.mission_type) # preserve srcSystem as that is used for naming waypoint file wp2._header.srcSystem = wp.get_srcSystem() wp2._header.srcComponent = wp.get_srcComponent() return wp2 def process_waypoint_request(self, m, master): '''process a waypoint request from the master''' if m.mission_type != self.mav_mission_type(): return # print("Processing %s request: (%s)" % (self.itemtype(), str(m))) if (m.target_system != self.settings.source_system or m.target_component != self.settings.source_component): # self.console.error("Mission request is not for me") return if (not self.loading_waypoints or time.time() > self.loading_waypoint_lasttime + 10.0): self.loading_waypoints = False # self.console.error("not loading waypoints") return if m.seq >= self.wploader.count(): self.console.error("Request for bad %s %u (max %u)" % (self.itemtype, m.seq, self.wploader.count())) return wp = self.wploader.wp(m.seq) wp.target_system = self.target_system wp.target_component = self.target_component if self.settings.wp_use_mission_int: wp_send = self.wp_to_mission_item_int(wp) else: wp_send = wp if wp.mission_type != self.mav_mission_type(): print("Wrong mission type in (%s)" % str(wp)) self.master.mav.send(wp_send) self.loading_waypoint_lasttime = time.time() # update the user on our progress: self.mpstate.console.set_status(self.itemtype(), '%s %u/%u' % (self.itemtype(), m.seq, self.wploader.count()-1)) # see if the transfer is complete: if m.seq == self.wploader.count() - 1: self.loading_waypoints = False print("Loaded %u %s in %.2fs" % ( self.wploader.count(), self.itemstype(), time.time() - self.upload_start)) self.console.writeln( "Sent all %u %s" % (self.wploader.count(), self.itemstype())) def send_all_waypoints(self): return self.send_all_items() def send_all_items(self): '''send all waypoints to vehicle''' self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.upload_start = time.time() self.master.mav.mission_count_send( self.target_system, self.target_component, self.wploader.count(), mission_type=self.mav_mission_type()) def load_waypoints(self, filename): '''load waypoints from a file''' self.wploader.target_system = self.target_system self.wploader.target_component = self.target_component try: # need to remove the leading and trailing quotes in filename self.wploader.load(filename.strip('"')) except Exception as msg: print("Unable to load %s - %s" % (filename, msg)) return print("Loaded %u %s from %s" % (self.wploader.count(), self.itemstype(), filename)) self.wploader.expected_count = self.wploader.count() self.send_all_waypoints() def update_waypoints(self, filename, wpnum): '''update waypoints from a file''' self.wploader.target_system = self.target_system self.wploader.target_component = self.target_component try: self.wploader.load(filename) except Exception as msg: print("Unable to load %s - %s" % (filename, msg)) return if self.wploader.count() == 0: print("No %s found in %s" % (self.itemstype(), filename)) return if wpnum == -1: print("Loaded %u updated %s from %s" % (self.wploader.count(), self.itemstype(), filename)) elif wpnum >= self.wploader.count(): print("Invalid %s number %u" % (self.itemtype(), wpnum)) return else: print("Loaded updated %s %u from %s" % (self.itemtype(), wpnum, filename)) self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() if wpnum == -1: start = 0 end = self.wploader.count()-1 else: start = wpnum end = wpnum self.master.mav.mission_write_partial_list_send( self.target_system, self.target_component, start, end, self.mav_mission_type()) def save_waypoints(self, filename): '''save waypoints to a file''' try: # need to remove the leading and trailing quotes in filename self.wploader.save(filename.strip('"')) except Exception as msg: print("Failed to save %s - %s" % (filename, msg)) return print("Saved %u %s to %s" % (self.wploader.count(), self.itemstype(), filename)) def save_waypoints_csv(self, filename): '''save waypoints to a file in a human readable CSV file''' try: # need to remove the leading and trailing quotes in filename self.wploader.savecsv(filename.strip('"')) except Exception as msg: print("Failed to save %s - %s" % (filename, msg)) return print("Saved %u %s to CSV %s" % (self.wploader.count(), self.itemstype(), filename)) def cmd_move(self, args): '''handle wp move''' if len(args) != 1: print("usage: wp move WPNUM") return idx = int(args[0]) if not self.good_item_num_to_manipulate(idx): print("Invalid %s number %u" % (self.itemtype(), idx)) return offset = self.item_num_to_offset(idx) latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return wp = self.wploader.wp(offset) # setup for undo self.undo_wp = copy.copy(wp) self.undo_wp_idx = idx self.undo_type = "move" (lat, lon) = latlon if (len(self.module_matching('terrain')) > 0 and wp.frame == mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT and self.settings.wpterrainadjust): alt1 = self.module('terrain').ElevationModel.GetElevation(lat, lon) alt2 = self.module('terrain').ElevationModel.GetElevation(wp.x, wp.y) if alt1 is not None and alt2 is not None: wp.z += alt1 - alt2 wp.x = lat wp.y = lon wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, offset) self.wploader.last_change = time.time() print("Moving %s %u to %f, %f at %.1fm" % (self.itemtype(), idx, lat, lon, wp.z)) self.send_single_waypoint(offset) def send_single_waypoint(self, idx): self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.upload_start = time.time() self.master.mav.mission_write_partial_list_send( self.target_system, self.target_component, idx, idx, self.mav_mission_type() ) def is_location_command(self, cmd): '''see if cmd is a MAV_CMD with a latitude/longitude''' mav_cmd = mavutil.mavlink.enums['MAV_CMD'] if cmd not in mav_cmd: return False return getattr(mav_cmd[cmd], 'has_location', True) def is_location_wp(self, w): '''see if w.command is a MAV_CMD with a latitude/longitude''' if w.x == 0 and w.y == 0: return False return self.is_location_command(w.command) def cmd_movemulti(self, args, latlon=None): '''handle wp move of multiple waypoints''' if len(args) < 3: print("usage: wp movemulti WPNUM WPSTART WPEND <rotation>") return idx = int(args[0]) if not self.good_item_num_to_manipulate(idx): print("Invalid move %s number %u" % (self.itemtype(), idx)) return wpstart = int(args[1]) if not self.good_item_num_to_manipulate(wpstart): print("Invalid start %s number %u" % (self.itemtype(), wpstart)) return wpend = int(args[2]) if not self.good_item_num_to_manipulate(wpend): print("Invalid end %s number %u" % (self.itemtype(), wpend)) return if idx < wpstart or idx > wpend: print("WPNUM must be between WPSTART and WPEND") return # optional rotation about center point if len(args) > 3: rotation = float(args[3]) else: rotation = 0 if latlon is None: latlon = self.mpstate.click_location if latlon is None: print("No map click position available") return idx_offset = self.item_num_to_offset(idx) wp = self.wploader.wp(idx_offset) if not self.is_location_wp(wp): print("WP must be a location command") return (lat, lon) = latlon distance = mp_util.gps_distance(wp.x, wp.y, lat, lon) bearing = mp_util.gps_bearing(wp.x, wp.y, lat, lon) wpstart_offset = self.item_num_to_offset(wpstart) wpend_offset = self.item_num_to_offset(wpend) for wpnum in range(wpstart_offset, wpend_offset+1): wp = self.wploader.wp(wpnum) if wp is None or not self.is_location_wp(wp): continue (newlat, newlon) = mp_util.gps_newpos(wp.x, wp.y, bearing, distance) if wpnum != idx and rotation != 0: # add in rotation d2 = mp_util.gps_distance(lat, lon, newlat, newlon) b2 = mp_util.gps_bearing(lat, lon, newlat, newlon) (newlat, newlon) = mp_util.gps_newpos(lat, lon, b2+rotation, d2) if (len(self.module_matching('terrain')) > 0 and wp.frame != mavutil.mavlink.MAV_FRAME_GLOBAL_TERRAIN_ALT and self.settings.wpterrainadjust): alt1 = self.module('terrain').ElevationModel.GetElevation(newlat, newlon) alt2 = self.module('terrain').ElevationModel.GetElevation(wp.x, wp.y) if alt1 is not None and alt2 is not None: wp.z += alt1 - alt2 wp.x = newlat wp.y = newlon wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, wpnum) self.wploader.last_change = time.time() self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send( self.target_system, self.target_component, wpstart_offset, wpend_offset) print("Moved %s %u:%u to %f, %f rotation=%.1f" % (self.itemstype(), wpstart, wpend, lat, lon, rotation)) def change_mission_item_range(self, args, desc, changer, newvalstr): if not self.check_have_list(): return idx = int(args[0]) if not self.good_item_num_to_manipulate(idx): print("Invalid %s number %u" % (self.itemtype(), idx)) return if len(args) >= 2: count = int(args[1]) else: count = 1 if not self.good_item_num_to_manipulate(idx+count-1): print("Invalid %s number %u" % (self.itemtype(), idx+count-1)) return for wpnum in range(idx, idx+count): offset = self.item_num_to_offset(wpnum) wp = self.wploader.wp(offset) if wp is None: continue if not self.wploader.is_location_command(wp.command): continue changer(wp) wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, offset) self.wploader.last_change = time.time() self.upload_start = time.time() self.loading_waypoints = True self.loading_waypoint_lasttime = time.time() self.master.mav.mission_write_partial_list_send( self.target_system, self.target_component, self.item_num_to_offset(idx), self.item_num_to_offset(idx+count), mission_type=self.mav_mission_type()) print("Changed %s for WPs %u:%u to %s" % (desc, idx, idx+(count-1), newvalstr)) def cmd_changealt(self, args): '''handle wp change target alt of multiple waypoints''' if len(args) < 2: print("usage: %s changealt WPNUM NEWALT <NUMWP>" % self.command_name()) return value = float(args[1]) del args[1] def changer(wp): wp.z = value self.change_mission_item_range(args, "alt", changer, str(value)) def cmd_changeframe(self, args): '''handle wp change frame of multiple waypoints''' if len(args) < 2: print("usage: %s changeframe WPNUM NEWFRAME <NUMWP>" % self.command_name()) return value = int(args[1]) del args[1] def changer(wp): wp.frame = value self.change_mission_item_range(args, "frame", changer, str(value)) def fix_jumps(self, idx, delta): # nothing by default as only waypoints need worry pass def cmd_remove(self, args): '''handle wp remove''' if len(args) != 1: print("usage: %s remove WPNUM" % self.command_name()) return idx = int(args[0]) if not self.good_item_num_to_manipulate(idx): print("Invalid %s number %u" % (self.itemtype(), idx)) return offset = self.item_num_to_offset(idx) wp = self.wploader.wp(offset) # setup for undo self.undo_wp = copy.copy(wp) self.undo_wp_idx = idx self.undo_type = "remove" self.wploader.remove(wp) self.wploader.expected_count -= 1 self.wploader.last_change = time.time() self.fix_jumps(offset, -1) self.send_all_waypoints() print("Removed %s %u" % (self.itemtype(), idx)) def cmd_undo(self, args): '''handle wp undo''' if self.undo_wp_idx == -1 or self.undo_wp is None: print("No undo information") return wp = self.undo_wp if self.undo_type == 'move': wp.target_system = self.target_system wp.target_component = self.target_component offset = self.item_num_to_offset(self.undo_wp_idx) self.wploader.set(wp, offset) self.wploader.last_change = time.time() self.send_single_waypoint(offset) print("Undid %s move" % self.itemtype()) elif self.undo_type == 'remove': offset = self.item_num_to_offset(self.undo_wp_idx) self.wploader.insert(offset, wp) self.wploader.expected_count += 1 self.wploader.last_change = time.time() self.fix_jumps(self.undo_wp_idx, 1) self.send_all_waypoints() print("Undid %s remove" % self.itemtype()) else: print("bad undo type") self.undo_wp = None self.undo_wp_idx = -1 def cmd_param(self, args): '''handle wp parameter change''' if len(args) < 2: print("usage: wp param WPNUM PNUM <VALUE>") return idx = int(args[0]) if not self.good_item_num_to_manipulate(idx): print("Invalid %s number %u" % (self.itemtype(), idx)) return offset = self.item_num_to_offset(idx) wp = self.wploader.wp(offset) param = [wp.param1, wp.param2, wp.param3, wp.param4] pnum = int(args[1]) if pnum < 1 or pnum > 4: print("Invalid param number %u" % pnum) return if len(args) == 2: print("Param %u: %f" % (pnum, param[pnum-1])) return param[pnum-1] = float(args[2]) wp.param1 = param[0] wp.param2 = param[1] wp.param3 = param[2] wp.param4 = param[3] wp.target_system = self.target_system wp.target_component = self.target_component self.wploader.set(wp, idx) self.wploader.last_change = time.time() self.send_single_waypoint(idx) def cmd_clear(self, args): self.master.mav.mission_clear_all_send( self.target_system, self.target_component, mission_type=self.mav_mission_type()) self.wploader.clear() if getattr(self.wploader, 'expected_count', None) is not None: self.wploader.expected_count = 0 self.wploader.expected_count = 0 self.loading_waypoint_lasttime = time.time() def cmd_list(self, args): self.wp_op = "list" self.request_list_send() def cmd_load(self, args): if len(args) != 1: print("usage: %s load FILENAME" % self.command_name()) return self.load_waypoints(args[0]) def cmd_save(self, args): if len(args) != 1: print("usage: %s save <filename>" % self.command_name()) return self.wp_save_filename = args[0] self.wp_op = "save" self.request_list_send() def cmd_savecsv(self, args): if len(args) != 1: print("usage: wp savecsv <filename.csv>") return self.savecsv(args[0]) def cmd_savelocal(self, args): if len(args) != 1: print("usage: wp savelocal <filename>") return self.wploader.save(args[0]) def cmd_show(self, args): if len(args) != 1: print("usage: wp show <filename>") return self.wploader.load(args[0]) def cmd_update(self, args): if not self.check_have_list(): return if len(args) < 1: print("usage: %s update <filename> <wpnum>" % self.command_name()) return if len(args) == 2: wpnum = int(args[1]) else: wpnum = -1 self.update_waypoints(args[0], wpnum) def commands(self): if self.master and not self.master.mavlink20(): print("%s module not available; use old compat modules" % str(self.itemtype())) return return { "ftp": self.wp_ftp_download, "ftpload": self.wp_ftp_upload, "clear": self.cmd_clear, "list": self.cmd_list, "load": (self.cmd_load, ["(FILENAME)"]), "remove": self.cmd_remove, "save": (self.cmd_save, ["(FILENAME)"]), "savecsv": (self.cmd_savecsv, ["(FILENAME)"]), "savelocal": self.cmd_savelocal, "show": (self.cmd_show, ["(FILENAME)"]), "status": self.cmd_status, } def usage(self): subcommands = "|".join(sorted(self.commands().keys())) return "usage: %s <%s>" % (self.command_name(), subcommands) def cmd_wp(self, args): '''waypoint commands''' if len(args) < 1: print(self.usage()) return commands = self.commands() if args[0] not in commands: print(self.usage()) return function = commands[args[0]] if isinstance(function, tuple): (function, function_arguments) = function # TODO: do some argument validation here, remove same from # cmd_* function(args[1:]) def pretty_enum_value(self, enum_name, enum_value): if enum_name == "MAV_FRAME": if enum_value == 0: return "Abs" elif enum_value == 1: return "Local" elif enum_value == 2: return "Mission" elif enum_value == 3: return "Rel" elif enum_value == 4: return "Local ENU" elif enum_value == 5: return "Global (INT)" elif enum_value == 10: return "AGL" ret = mavutil.mavlink.enums[enum_name][enum_value].name ret = ret[len(enum_name)+1:] return ret def csv_line(self, line): '''turn a list of values into a CSV line''' self.csv_sep = "," return self.csv_sep.join(['"' + str(x) + '"' for x in line]) def pretty_parameter_value(self, value): '''pretty parameter value''' return value def savecsv(self, filename): '''save waypoints to a file in human-readable CSV file''' f = open(filename, mode='w') # headers = ["Seq", "Frame", "Cmd", "P1", "P2", "P3", "P4", "X", "Y", "Z"] for w in self.wploader.wpoints: if getattr(w, 'comment', None): # f.write("# %s\n" % w.comment) pass out_list = [ w.seq, self.pretty_enum_value('MAV_FRAME', w.frame), self.pretty_enum_value('MAV_CMD', w.command), self.pretty_parameter_value(w.param1), self.pretty_parameter_value(w.param2), self.pretty_parameter_value(w.param3), self.pretty_parameter_value(w.param4), self.pretty_parameter_value(w.x), self.pretty_parameter_value(w.y), self.pretty_parameter_value(w.z), ] f.write(self.csv_line(out_list) + "\n") f.close() def fetch(self): """Download wpts from vehicle (this operation is public to support other modules)""" if self.wp_op is None: # If we were already doing a list or save, just restart the fetch without changing the operation # noqa self.wp_op = "fetch" self.request_list_send() def request_list_send(self): self.master.mav.mission_request_list_send( self.target_system, self.target_component, mission_type=self.mav_mission_type()) def wp_ftp_download(self, args): '''Download items from vehicle with ftp''' ftp = self.mpstate.module('ftp') if ftp is None: print("Need ftp module") return self.ftp_count = None ftp.cmd_get([self.mission_ftp_name()], callback=self.ftp_callback, callback_progress=self.ftp_callback_progress) def ftp_callback_progress(self, fh, total_size): '''progress callback from ftp fetch of mission items''' if self.ftp_count is None and total_size >= 10: ofs = fh.tell() fh.seek(0) buf = fh.read(10) fh.seek(ofs) magic2, dtype, options, start, num_items = struct.unpack("<HHHHH", buf) if magic2 == 0x763d: self.ftp_count = num_items if self.ftp_count is not None: mavmsg = mavutil.mavlink.MAVLink_mission_item_int_message item_size = mavmsg.unpacker.size done = (total_size - 10) // item_size self.mpstate.console.set_status('Mission', 'Mission %u/%u' % (done, self.ftp_count)) def ftp_callback(self, fh): '''callback from ftp fetch of mission items''' if fh is None: print("mission: failed ftp download") return magic = 0x763d data = fh.read() magic2, dtype, options, start, num_items = struct.unpack("<HHHHH", data[0:10]) if magic != magic2: print("%s: bad magic 0x%x expected 0x%x" % (self.itemtype(), magic2, magic)) return if dtype != self.mav_mission_type(): print("%s: bad data type %u" % (self.itemtype(), dtype)) return self.wploader.clear() data = data[10:] mavmsg = mavutil.mavlink.MAVLink_mission_item_int_message item_size = mavmsg.unpacker.size while len(data) >= item_size: mdata = data[:item_size] data = data[item_size:] msg = mavmsg.unpacker.unpack(mdata) tlist = list(msg) t = tlist[:] for i in range(0, len(tlist)): tlist[i] = t[mavmsg.orders[i]] t = tuple(tlist) w = mavmsg(*t) w = self.wp_from_mission_item_int(w) self.wploader.add(w) self.show_and_save(self.target_system) def show_and_save(self, source_system): '''display waypoints and save''' for i in range(self.wploader.count()): w = self.wploader.wp(i) print("%u %u %.10f %.10f %f p1=%.1f p2=%.1f p3=%.1f p4=%.1f cur=%u auto=%u" % ( w.command, w.frame, w.x, w.y, w.z, w.param1, w.param2, w.param3, w.param4, w.current, w.autocontinue)) if self.logdir is not None: fname = self.save_filename() if source_system != 1: fname = '%s_%u.txt' % (self.save_filename_base(), source_system) waytxt = os.path.join(self.logdir, fname) self.save_waypoints(waytxt) print("Saved %s to %s" % (self.itemstype(), waytxt)) def wp_ftp_upload(self, args): '''upload waypoints to vehicle with ftp''' filename = args[0] ftp = self.mpstate.module('ftp') if ftp is None: print("Need ftp module") return self.wploader.target_system = self.target_system self.wploader.target_component = self.target_component try: # need to remove the leading and trailing quotes in filename self.wploader.load(filename.strip('"')) except Exception as msg: print("Unable to load %s - %s" % (filename, msg)) return print("Loaded %u %s from %s" % (self.wploader.count(), self.itemstype(), filename)) print("Sending %s with ftp" % self.itemstype()) fh = SIO() fh.write(struct.pack("<HHHHH", 0x763d, self.mav_mission_type(), 0, 0, self.wploader.count())) mavmsg = mavutil.mavlink.MAVLink_mission_item_int_message for i in range(self.wploader.count()): w = self.wploader.wp(i) w = self.wp_to_mission_item_int(w) tlist = [] for field in mavmsg.ordered_fieldnames: tlist.append(getattr(w, field)) tlist = tuple(tlist) buf = mavmsg.unpacker.pack(*tlist) fh.write(buf) fh.seek(0) self.upload_start = time.time() ftp.cmd_put([self.mission_ftp_name(), self.mission_ftp_name()], fh=fh, callback=self.ftp_upload_callback, progress_callback=self.ftp_upload_progress) def ftp_upload_progress(self, proportion): '''callback from ftp put of items''' if proportion is None: self.mpstate.console.set_status('Mission', 'Mission ERR') else: count = self.wploader.count() self.mpstate.console.set_status('Mission', 'Mission %u/%u' % (int(proportion*count), count)) def ftp_upload_callback(self, dlen): '''callback from ftp put of items''' if dlen is None: print("Failed to send %s" % self.itemstype()) else: mavmsg = mavutil.mavlink.MAVLink_mission_item_int_message item_size = mavmsg.unpacker.size print("Sent %s of length %u in %.2fs" % (self.itemtype(), (dlen - 10) // item_size, time.time() - self.upload_start))
class MissionItemProtocolModule(mp_module.MPModule): def __init__(self, mpstate, name, description, **args): pass def gui_menu_items(self): pass def mission_type_string(self): pass def init_gui_menus(self): '''initialise menus for console and map''' pass def completions(self): '''form up MAVProxy-style completion strings used for tab completi on''' pass def unload(self): pass def unload_remove_menu_items(self): '''remove out menu items from other modules''' pass def create_loader(self): pass def last_change(self): pass def check_have_list(self): pass def index_from_0(self): '''e.g. rally points etc are indexed from 1 from the user interface perspective''' pass def save_filename_base(self): pass def save_filename_base(self): pass @property def wploader(self): '''per-sysid wploader''' pass def good_item_num_to_manipulate(self, idx): pass def item_num_to_offset(self, item_num): pass def missing_wps_to_request(self): pass def append(self, item): '''append an item to the held item list''' pass def send_wp_requests(self, wps=None): '''send some more WP requests''' pass def cmd_status(self, args): '''show status of wp download''' pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass def idle_task(self): '''handle missing waypoints''' pass def idle_task_add_menu_items(self): '''check for load of other modules, add our items as required''' pass def has_location(self, cmd_id): '''return True if a WP command has a location''' pass def wp_to_mission_item_int(self, wp): '''convert a MISSION_ITEM to a MISSION_ITEM_INT. We always send as MISSION_ITEM_INT to give cm level accuracy ''' pass def wp_from_mission_item_int(self, wp): '''convert a MISSION_ITEM_INT to a MISSION_ITEM''' pass def process_waypoint_request(self, m, master): '''process a waypoint request from the master''' pass def send_all_waypoints(self): pass def send_all_items(self): '''send all waypoints to vehicle''' pass def load_waypoints(self, filename): '''load waypoints from a file''' pass def update_waypoints(self, filename, wpnum): '''update waypoints from a file''' pass def save_waypoints(self, filename): '''save waypoints to a file''' pass def save_waypoints_csv(self, filename): '''save waypoints to a file in a human readable CSV file''' pass def cmd_move(self, args): '''handle wp move''' pass def send_single_waypoint(self, idx): pass def is_location_command(self, cmd): '''see if cmd is a MAV_CMD with a latitude/longitude''' pass def is_location_wp(self, w): '''see if w.command is a MAV_CMD with a latitude/longitude''' pass def cmd_movemulti(self, args, latlon=None): '''handle wp move of multiple waypoints''' pass def change_mission_item_range(self, args, desc, changer, newvalstr): pass def cmd_changealt(self, args): '''handle wp change target alt of multiple waypoints''' pass def changer(wp): pass def cmd_changeframe(self, args): '''handle wp change frame of multiple waypoints''' pass def changer(wp): pass def fix_jumps(self, idx, delta): pass def cmd_remove(self, args): '''handle wp remove''' pass def cmd_undo(self, args): '''handle wp undo''' pass def cmd_param(self, args): '''handle wp parameter change''' pass def cmd_clear(self, args): pass def cmd_list(self, args): pass def cmd_load(self, args): pass def cmd_save(self, args): pass def cmd_savecsv(self, args): pass def cmd_savelocal(self, args): pass def cmd_show(self, args): pass def cmd_update(self, args): pass def commands(self): pass def usage(self): pass def cmd_wp(self, args): '''waypoint commands''' pass def pretty_enum_value(self, enum_name, enum_value): pass def csv_line(self, line): '''turn a list of values into a CSV line''' pass def pretty_parameter_value(self, value): '''pretty parameter value''' pass def savecsv(self, filename): '''save waypoints to a file in human-readable CSV file''' pass def fetch(self): '''Download wpts from vehicle (this operation is public to support other modules)''' pass def request_list_send(self): pass def wp_ftp_download(self, args): '''Download items from vehicle with ftp''' pass def ftp_callback_progress(self, fh, total_size): '''progress callback from ftp fetch of mission items''' pass def ftp_callback_progress(self, fh, total_size): '''callback from ftp fetch of mission items''' pass def show_and_save(self, source_system): '''display waypoints and save''' pass def wp_ftp_upload(self, args): '''upload waypoints to vehicle with ftp''' pass def ftp_upload_progress(self, proportion): '''callback from ftp put of items''' pass def ftp_upload_callback(self, dlen): '''callback from ftp put of items''' pass
73
41
14
1
13
1
3
0.09
1
13
3
3
69
21
69
107
1,089
115
901
222
828
80
737
214
665
15
2
3
220
6,976
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/mp_image.py
MAVProxy.modules.lib.mp_image.MPImageFrameCounter
class MPImageFrameCounter: '''frame counter''' def __init__(self, frame): self.frame = frame
class MPImageFrameCounter: '''frame counter''' def __init__(self, frame): pass
2
1
2
0
2
0
1
0.33
0
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
0
0
1
6,977
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_gimbal.py
MAVProxy.modules.mavproxy_gimbal.GimbalModule
class GimbalModule(mp_module.MPModule): def __init__(self, mpstate): super(GimbalModule, self).__init__(mpstate, "gimbal", "gimbal control module") self.add_command('gimbal', self.cmd_gimbal, "gimbal link control", ['<rate|point|roi|roivel|mode|status>']) if mp_util.has_wxpython: self.menu = MPMenuSubMenu('Mount', items=[MPMenuItem('GPS targeting Mode', 'GPS Mode', '# gimbal mode gps'), MPMenuItem('MAVLink targeting Mode', 'MAVLink Mode', '# gimbal mode mavlink'), MPMenuItem('RC targeting Mode', 'RC Mode', '# gimbal mode rc'), MPMenuItem('Point At', 'Point At', '# gimbal roi')]) self.menu_added_map = False else: self.menu = None def idle_task(self): '''called on idle''' if self.menu is not None and self.module('map') is not None and not self.menu_added_map: self.menu_added_map = True self.module('map').add_menu(self.menu) def cmd_gimbal(self, args): '''control gimbal''' usage = 'Usage: gimbal <rate|point|roi|roivel|mode|status>' if len(args) == 0: print(usage) return if args[0] == 'rate': self.cmd_gimbal_rate(args[1:]) elif args[0] == 'point': self.cmd_gimbal_point(args[1:]) elif args[0] == 'roi': self.cmd_gimbal_roi(args[1:]) elif args[0] == 'mode': self.cmd_gimbal_mode(args[1:]) elif args[0] == 'status': self.cmd_gimbal_status(args[1:]) elif args[0] == 'roivel': self.cmd_gimbal_roi_vel(args[1:]) def cmd_gimbal_mode(self, args): '''control gimbal mode''' if len(args) != 1: print("usage: gimbal mode <RETRACT|NEUTRAL|GPS|MAVLink|RC>") return if args[0].upper() == "RETRACT": mode = mavutil.mavlink.MAV_MOUNT_MODE_RETRACT elif args[0].upper() == "NEUTRAL": mode = mavutil.mavlink.MAV_MOUNT_MODE_NEUTRAL elif args[0].upper() == 'GPS': mode = mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT elif args[0].upper() == 'MAVLINK': mode = mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING elif args[0].upper() == 'RC': mode = mavutil.mavlink.MAV_MOUNT_MODE_RC_TARGETING else: print("Unsupported mode %s" % args[0]) self.master.mav.mount_configure_send(self.target_system, self.target_component, mode, 1, 1, 1) def cmd_gimbal_roi(self, args): '''control roi position''' latlon = None alt = 0 if len(args) == 0: latlon = self.mpstate.click_location elif len(args) == 3: latlon = [float(i) for i in args[0:2]] alt = float(args[2]) if latlon is None and len(args) == 0: print("No map click position available and no parameters set") return elif latlon is None: print("usage: gimbal roi [LAT LON RELHOMEALT]") return self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_DO_MOUNT_CONTROL, 0, # confirmation 0, # param1 0, # param2 0, # param3 alt, # param4 - alt (exception to the usual rule about where this goes) int(latlon[0]*1e7), # lat int(latlon[1]*1e7), # lon mavutil.mavlink.MAV_MOUNT_MODE_GPS_POINT) # param7 def cmd_gimbal_roi_vel(self, args): '''control roi position and velocity''' if len(args) != 0 and len(args) != 3 and len(args) != 6: print("usage: gimbal roivel [VEL_NORTH VEL_EAST VEL_DOWN] [ACC_NORTH ACC_EASY ACC_DOWN]") return latlon = None vel = [0,0,0] acc = [0,0,0] if (len(args) >= 3): vel[0:3] = args[0:3] if (len(args) == 6): acc[0:3] = args[3:6] latlon = self.mpstate.click_location if latlon is None: print("No map click position available") latlon = (0,0,0) self.master.mav.set_roi_global_int_send(0, #time_boot_ms 1, #target_system 1, #target_component mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, 0, #type_mask 0, #roi_index 0, #timeout_ms int(latlon[0]*1e7), #lat int int(latlon[1]*1e7), #lng int float(0), #alt float(vel[0]), #vx float(vel[1]), #vy float(vel[2]), #vz float(acc[0]), #ax float(acc[1]), #ay float(acc[2])) #az def cmd_gimbal_rate(self, args): '''control gimbal rate''' if len(args) != 3: print("usage: gimbal rate ROLL PITCH YAW") return (roll, pitch, yaw) = (float(args[0]), float(args[1]), float(args[2])) self.master.mav.gimbal_manager_set_attitude_send( self.target_system, self.target_component, 0, # flags 0, # instance, 0 is primary [float("NaN"), float("NaN"), float("NaN"), float("NaN")], radians(roll), radians(pitch), radians(yaw) ) def cmd_gimbal_point(self, args): '''control gimbal pointing''' if len(args) != 3: print("usage: gimbal point ROLL PITCH YAW") return (roll, pitch, yaw) = (float(args[0]), float(args[1]), float(args[2])) self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_DO_MOUNT_CONTROL, 0, # confirmation pitch, # param1 roll, # param2 yaw, # param3 0, # param4 0, # lat 0, # lon mavutil.mavlink.MAV_MOUNT_MODE_MAVLINK_TARGETING) # param7 def cmd_gimbal_status(self, args): '''show gimbal status''' master = self.master if 'GIMBAL_REPORT' in master.messages: print(master.messages['GIMBAL_REPORT']) else: print("No GIMBAL_REPORT messages") def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if not self.mpstate.map: # don't draw if no map return for n in frozenset(['ATTITUDE', 'GLOBAL_POSITION_INT']): if not n in self.master.messages: return gpi = self.master.messages['GLOBAL_POSITION_INT'] att = self.master.messages['ATTITUDE'] rotmat_copter_gimbal = Matrix3() if m.get_type() == 'GIMBAL_REPORT': rotmat_copter_gimbal.from_euler312(m.joint_roll, m.joint_el, m.joint_az) elif m.get_type() == 'GIMBAL_DEVICE_ATTITUDE_STATUS': r, p, y = pymavlink.quaternion.Quaternion(m.q).euler # rotate back from earth-frame on roll and pitch to body-frame r -= att.roll p -= att.pitch rotmat_copter_gimbal.from_euler(r, p, y) else: return # clear the camera icon self.mpstate.map.add_object(mp_slipmap.SlipClearLayer('GimbalView')) vehicle_dcm = Matrix3() vehicle_dcm.from_euler(att.roll, att.pitch, att.yaw) gimbal_dcm = vehicle_dcm * rotmat_copter_gimbal lat = gpi.lat * 1.0e-7 lon = gpi.lon * 1.0e-7 alt = gpi.relative_alt * 1.0e-3 # ground plane ground_plane = Plane() # the position of the camera in the air, remembering its a right # hand coordinate system, so +ve z is down camera_point = Vector3(0, 0, -alt) # get view point of camera when not rotated view_point = Vector3(1, 0, 0) # rotate view_point to form current view vector rot_point = gimbal_dcm * view_point # a line from the camera to the ground line = Line(camera_point, rot_point) # find the intersection with the ground pt = line.plane_intersection(ground_plane, forward_only=True) if pt is None: # its pointing up into the sky return None (view_lat, view_lon) = mp_util.gps_offset(lat, lon, pt.y, pt.x) icon = self.mpstate.map.icon('camera-small-red.png') self.mpstate.map.add_object(mp_slipmap.SlipIcon('gimbalview', (view_lat,view_lon), icon, layer='GimbalView', rotation=0, follow=False))
class GimbalModule(mp_module.MPModule): def __init__(self, mpstate): pass def idle_task(self): '''called on idle''' pass def cmd_gimbal(self, args): '''control gimbal''' pass def cmd_gimbal_mode(self, args): '''control gimbal mode''' pass def cmd_gimbal_roi(self, args): '''control roi position''' pass def cmd_gimbal_roi_vel(self, args): '''control roi position and velocity''' pass def cmd_gimbal_rate(self, args): '''control gimbal rate''' pass def cmd_gimbal_point(self, args): '''control gimbal pointing''' pass def cmd_gimbal_status(self, args): '''show gimbal status''' pass def mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass
11
9
22
2
19
6
4
0.3
1
8
4
0
10
2
10
48
233
25
188
41
177
57
116
41
105
8
2
2
42
6,978
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_gopro.py
MAVProxy.modules.mavproxy_gopro.GoProModule
class GoProModule(mp_module.MPModule): def __init__(self, mpstate): super(GoProModule, self).__init__(mpstate, "gopro", "gopro handling") self.add_command('gopro', self.cmd_gopro, 'gopro control', [ 'status', 'shutter <start|stop>', 'mode <video|camera>', 'power <on|off>']) def cmd_gopro(self, args): '''gopro commands''' usage = "status, shutter <start|stop>, mode <video|camera>, power <on|off>" mav = self.master.mav if args[0] == "status": self.cmd_gopro_status(args[1:]) return if args[0] == "shutter": name = args[1].lower() if name == 'start': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_SHUTTER, [1, 0 ,0 , 0]) return elif name == 'stop': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_SHUTTER, [0, 0 ,0 , 0]) return else: print("unrecognized") return if args[0] == "mode": name = args[1].lower() if name == 'video': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_CAPTURE_MODE, [0, 0 ,0 , 0]) return elif name == 'camera': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_CAPTURE_MODE, [1, 0 ,0 , 0]) return else: print("unrecognized") return if args[0] == "power": name = args[1].lower() if name == 'on': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_POWER, [1, 0 ,0 , 0]) return elif name == 'off': mav.gopro_set_request_send(self.target_system, mavutil.mavlink.MAV_COMP_ID_GIMBAL, mavutil.mavlink.GOPRO_COMMAND_POWER, [0, 0 ,0 , 0]) return else: print("unrecognized") return print(usage) def cmd_gopro_status(self, args): '''show gopro status''' master = self.master if 'GOPRO_HEARTBEAT' in master.messages: print(master.messages['GOPRO_HEARTBEAT']) else: print("No GOPRO_HEARTBEAT messages")
class GoProModule(mp_module.MPModule): def __init__(self, mpstate): pass def cmd_gopro(self, args): '''gopro commands''' pass def cmd_gopro_status(self, args): '''show gopro status''' pass
4
2
22
2
20
1
5
0.03
1
1
0
0
3
0
3
41
71
9
60
8
56
2
43
8
39
11
2
2
14
6,979
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_graph.py
MAVProxy.modules.mavproxy_graph.Graph
class Graph(): '''a graph instance''' def __init__(self, state, fields): self.fields = fields[:] self.field_types = [] self.msg_types = set() self.state = state for i in range(len(self.fields)): # special handling for NAMED_VALUE_FLOAT m = re.match("^NAMED_VALUE_FLOAT\[([A-Z0-9_]+)\]\.(.*)$", self.fields[i]) if m: self.fields[i] = "NAMED_VALUE_FLOAT['%s'].%s" % (m.group(1), m.group(2)) 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) print("Adding graph: %s" % self.fields) fields = [ self.pretty_print_fieldname(x) for x in self.fields ] labels = [] for i in range(len(fields)): f = fields[i] f1 = f.find("<") f2 = f.find(">") if f1 > 0 and f2 > f1: labels.append(f[f1+1:f2]) fields[i] = f[:f1] else: labels.append(None) self.fields = fields[:] self.values = [None] * len(self.fields) self.livegraph = live_graph.LiveGraph(fields, timespan=state.timespan, tickresolution=state.tickresolution, title=fields[0] if labels[0] is None else labels[0], labels=labels) def pretty_print_fieldname(self, fieldname): if fieldname in self.state.legend: return self.state.legend[fieldname] return fieldname def is_alive(self): '''check if this graph is still alive''' if self.livegraph: return self.livegraph.is_alive() return False def close(self): '''close this graph''' if self.livegraph: self.livegraph.close() self.livegraph = None def add_mavlink_packet(self, msg): '''add data to the graph''' mtype = msg.get_type() if mtype not in self.msg_types: return have_value = False for i in range(len(self.fields)): if mtype not in self.field_types[i]: continue f = self.fields[i] self.values[i] = mavutil.evaluate_expression(f, self.state.master.messages) if self.values[i] is not None: have_value = True if have_value and self.livegraph is not None: self.livegraph.add_values(self.values)
class Graph(): '''a graph instance''' def __init__(self, state, fields): pass def pretty_print_fieldname(self, fieldname): pass def is_alive(self): '''check if this graph is still alive''' pass def close(self): '''close this graph''' pass def add_mavlink_packet(self, msg): '''add data to the graph''' pass
6
4
13
1
12
1
4
0.08
0
3
1
0
5
6
5
5
73
8
60
24
54
5
55
24
49
7
0
2
19
6,980
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.NavigationToolbar2Wx
class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): def __init__(self, canvas): wx.ToolBar.__init__(self, canvas.GetParent(), -1) NavigationToolbar2.__init__(self, canvas) self.canvas = canvas self._idle = True self.statbar = None def get_canvas(self, frame, fig): return FigureCanvasWx(frame, -1, fig) def _init_toolbar(self): DEBUG_MSG("_init_toolbar", 1, self) self._parent = self.canvas.GetParent() self.wx_ids = {} for text, tooltip_text, image_file, callback in self.toolitems: if text is None: self.AddSeparator() continue self.wx_ids[text] = wx.NewId() if text in ['Pan', 'Zoom']: self.AddCheckTool(self.wx_ids[text], _load_bitmap(image_file + '.png'), shortHelp=text, longHelp=tooltip_text) else: self.AddSimpleTool(self.wx_ids[text], _load_bitmap(image_file + '.png'), text, tooltip_text) bind(self, wx.EVT_TOOL, getattr(self, callback), id=self.wx_ids[text]) self.Realize() def zoom(self, *args): self.ToggleTool(self.wx_ids['Pan'], False) NavigationToolbar2.zoom(self, *args) def pan(self, *args): self.ToggleTool(self.wx_ids['Zoom'], False) NavigationToolbar2.pan(self, *args) def configure_subplots(self, evt): frame = wx.Frame(None, -1, "Configure subplots") toolfig = Figure((6,3)) canvas = self.get_canvas(frame, toolfig) # Create a figure manager to manage things figmgr = FigureManager(canvas, 1, frame) # Now put all into a sizer sizer = wx.BoxSizer(wx.VERTICAL) # This way of adding to sizer allows resizing sizer.Add(canvas, 1, wx.LEFT|wx.TOP|wx.GROW) frame.SetSizer(sizer) frame.Fit() tool = SubplotTool(self.canvas.figure, toolfig) frame.Show() def save_figure(self, *args): # Fetch the required filename and file type. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() default_file = self.canvas.get_default_filename() dlg = wx.FileDialog(self._parent, "Save to file", "", default_file, filetypes, wx.SAVE|wx.OVERWRITE_PROMPT) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() == wx.ID_OK: dirname = dlg.GetDirectory() filename = dlg.GetFilename() DEBUG_MSG('Save file dir:%s name:%s' % (dirname, filename), 3, self) format = exts[dlg.GetFilterIndex()] basename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format!=ext: #looks like they forgot to set the image type drop #down, going with the extension. warnings.warn('extension %s did not match the selected image type %s; going with %s'%(ext, format, ext), stacklevel=0) format = ext try: self.canvas.print_figure( os.path.join(dirname, filename), format=format) except Exception as e: error_msg_wx(str(e)) def set_cursor(self, cursor): cursor =wx.StockCursor(cursord[cursor]) self.canvas.SetCursor( cursor ) def release(self, event): try: del self.lastrect except AttributeError: pass def dynamic_update(self): d = self._idle self._idle = False if d: self.canvas.draw() self._idle = True def draw_rubberband(self, event, x0, y0, x1, y1): 'adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744' canvas = self.canvas dc =wx.ClientDC(canvas) # Set logical function to XOR for rubberbanding dc.SetLogicalFunction(wx.XOR) # Set dc brush and pen # Here I set brush and pen to white and grey respectively # You can set it to your own choices # The brush setting is not really needed since we # dont do any filling of the dc. It is set just for # the sake of completion. wbrush =wx.Brush(wx.Colour(255,255,255), wx.TRANSPARENT) wpen =wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID) dc.SetBrush(wbrush) dc.SetPen(wpen) dc.ResetBoundingBox() dc.BeginDrawing() height = self.canvas.figure.bbox.height y1 = height - y1 y0 = height - y0 if y1<y0: y0, y1 = y1, y0 if x1<y0: x0, x1 = x1, x0 w = x1 - x0 h = y1 - y0 rect = int(x0), int(y0), int(w), int(h) try: lastrect = self.lastrect except AttributeError: pass else: dc.DrawRectangle(*lastrect) #erase last self.lastrect = rect dc.DrawRectangle(*rect) dc.EndDrawing() def set_status_bar(self, statbar): self.statbar = statbar def set_message(self, s): if self.statbar is not None: self.statbar.set_function(s) def set_history_buttons(self): can_backward = (self._views._pos > 0) can_forward = (self._views._pos < len(self._views._elements) - 1) self.EnableTool(self.wx_ids['Back'], can_backward) self.EnableTool(self.wx_ids['Forward'], can_forward)
class NavigationToolbar2Wx(NavigationToolbar2, wx.ToolBar): def __init__(self, canvas): pass def get_canvas(self, frame, fig): pass def _init_toolbar(self): pass def zoom(self, *args): pass def pan(self, *args): pass def configure_subplots(self, evt): pass def save_figure(self, *args): pass def set_cursor(self, cursor): pass def release(self, event): pass def dynamic_update(self): pass def draw_rubberband(self, event, x0, y0, x1, y1): '''adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189744''' pass def set_status_bar(self, statbar): pass def set_message(self, s): pass def set_history_buttons(self): pass
15
1
10
1
8
1
2
0.14
2
5
1
0
14
6
14
14
155
30
111
47
96
15
113
46
98
5
1
2
27
6,981
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.MenuButtonWx
class MenuButtonWx(wx.Button): """ wxPython does not permit a menu to be incorporated directly into a toolbar. This class simulates the effect by associating a pop-up menu with a button in the toolbar, and managing this as though it were a menu. """ def __init__(self, parent): wx.Button.__init__(self, parent, _NTB_AXISMENU_BUTTON, "Axes: ", style=wx.BU_EXACTFIT) self._toolbar = parent self._menu =wx.Menu() self._axisId = [] # First two menu items never change... self._allId =wx.NewId() self._invertId =wx.NewId() self._menu.Append(self._allId, "All", "Select all axes", False) self._menu.Append(self._invertId, "Invert", "Invert axes selected", False) self._menu.AppendSeparator() bind(self, wx.EVT_BUTTON, self._onMenuButton, id=_NTB_AXISMENU_BUTTON) bind(self, wx.EVT_MENU, self._handleSelectAllAxes, id=self._allId) bind(self, wx.EVT_MENU, self._handleInvertAxesSelected, id=self._invertId) def Destroy(self): self._menu.Destroy() self.Destroy() def _onMenuButton(self, evt): """Handle menu button pressed.""" x, y = self.GetPositionTuple() w, h = self.GetSizeTuple() self.PopupMenuXY(self._menu, x, y+h-4) # When menu returned, indicate selection in button evt.Skip() def _handleSelectAllAxes(self, evt): """Called when the 'select all axes' menu item is selected.""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _handleInvertAxesSelected(self, evt): """Called when the invert all menu item is selected""" if len(self._axisId) == 0: return for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): self._menu.Check(self._axisId[i], False) else: self._menu.Check(self._axisId[i], True) self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def _onMenuItemSelected(self, evt): """Called whenever one of the specific axis menu items is selected""" current = self._menu.IsChecked(evt.GetId()) if current: new = False else: new = True self._menu.Check(evt.GetId(), new) # Lines above would be deleted based on svn tracker ID 2841525; # not clear whether this matters or not. self._toolbar.set_active(self.getActiveAxes()) evt.Skip() def updateAxes(self, maxAxis): """Ensures that there are entries for max_axis axes in the menu (selected by default).""" if maxAxis > len(self._axisId): for i in range(len(self._axisId) + 1, maxAxis + 1, 1): menuId =wx.NewId() self._axisId.append(menuId) self._menu.Append(menuId, "Axis %d" % i, "Select axis %d" % i, True) self._menu.Check(menuId, True) bind(self, wx.EVT_MENU, self._onMenuItemSelected, id=menuId) elif maxAxis < len(self._axisId): for menuId in self._axisId[maxAxis:]: self._menu.Delete(menuId) self._axisId = self._axisId[:maxAxis] self._toolbar.set_active(range(maxAxis)) def getActiveAxes(self): """Return a list of the selected axes.""" active = [] for i in range(len(self._axisId)): if self._menu.IsChecked(self._axisId[i]): active.append(i) return active def updateButtonText(self, lst): """Update the list of selected axes in the menu button""" axis_txt = '' for e in lst: axis_txt += '%d,' % (e+1) # remove trailing ',' and add to button string self.SetLabel("Axes: %s" % axis_txt[:-1])
class MenuButtonWx(wx.Button): ''' wxPython does not permit a menu to be incorporated directly into a toolbar. This class simulates the effect by associating a pop-up menu with a button in the toolbar, and managing this as though it were a menu. ''' def __init__(self, parent): pass def Destroy(self): pass def _onMenuButton(self, evt): '''Handle menu button pressed.''' pass def _handleSelectAllAxes(self, evt): '''Called when the 'select all axes' menu item is selected.''' pass def _handleInvertAxesSelected(self, evt): '''Called when the invert all menu item is selected''' pass def _onMenuItemSelected(self, evt): '''Called whenever one of the specific axis menu items is selected''' pass def updateAxes(self, maxAxis): '''Ensures that there are entries for max_axis axes in the menu (selected by default).''' pass def getActiveAxes(self): '''Return a list of the selected axes.''' pass def updateButtonText(self, lst): '''Update the list of selected axes in the menu button''' pass
10
8
10
0
8
1
2
0.25
1
1
0
0
9
5
9
9
100
10
72
27
62
18
69
27
59
5
1
2
22
6,982
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.GraphicsContextWx
class GraphicsContextWx(GraphicsContextBase): """ The graphics context provides the color, line styles, etc... This class stores a reference to a wxMemoryDC, and a wxGraphicsContext that draws to it. Creating a wxGraphicsContext seems to be fairly heavy, so these objects are cached based on the bitmap object that is passed in. The base GraphicsContext stores colors as a RGB tuple on the unit interval, eg, (0.5, 0.0, 1.0). wxPython uses an int interval, but since wxPython colour management is rather simple, I have not chosen to implement a separate colour manager class. """ _capd = { 'butt': wx.CAP_BUTT, 'projecting': wx.CAP_PROJECTING, 'round': wx.CAP_ROUND } _joind = { 'bevel': wx.JOIN_BEVEL, 'miter': wx.JOIN_MITER, 'round': wx.JOIN_ROUND } _dashd_wx = { 'solid': wx.SOLID, 'dashed': wx.SHORT_DASH, 'dashdot': wx.DOT_DASH, 'dotted': wx.DOT } _cache = weakref.WeakKeyDictionary() def __init__(self, bitmap, renderer): GraphicsContextBase.__init__(self) #assert self.Ok(), "wxMemoryDC not OK to use" DEBUG_MSG("__init__()", 1, self) dc, gfx_ctx = self._cache.get(bitmap, (None, None)) if dc is None: dc = wx.MemoryDC() dc.SelectObject(bitmap) gfx_ctx = wx.GraphicsContext.Create(dc) gfx_ctx._lastcliprect = None self._cache[bitmap] = dc, gfx_ctx self.bitmap = bitmap self.dc = dc self.gfx_ctx = gfx_ctx self._pen = wx.Pen('BLACK', 1, wx.SOLID) gfx_ctx.SetPen(self._pen) self._style = wx.SOLID self.renderer = renderer def select(self): """ Select the current bitmap into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(self.bitmap) self.IsSelected = True def unselect(self): """ Select a Null bitmasp into this wxDC instance """ if sys.platform=='win32': self.dc.SelectObject(wx.NullBitmap) self.IsSelected = False def set_foreground(self, fg, isRGBA=None): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ # Implementation note: wxPython has a separate concept of pen and # brush - the brush fills any outline trace left by the pen. # Here we set both to the same colour - if a figure is not to be # filled, the renderer will set the brush to be transparent # Same goes for text foreground... DEBUG_MSG("set_foreground()", 1, self) self.select() GraphicsContextBase.set_foreground(self, fg, isRGBA) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_graylevel(self, frac): """ Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. """ DEBUG_MSG("set_graylevel()", 1, self) self.select() GraphicsContextBase.set_graylevel(self, frac) self._pen.SetColour(self.get_wxcolour(self.get_rgb())) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linewidth(self, w): """ Set the line width. """ DEBUG_MSG("set_linewidth()", 1, self) self.select() if w>0 and w<1: w = 1 GraphicsContextBase.set_linewidth(self, w) lw = int(self.renderer.points_to_pixels(self._linewidth)) if lw==0: lw = 1 self._pen.SetWidth(lw) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_capstyle(self, cs): """ Set the capstyle as a string in ('butt', 'round', 'projecting') """ DEBUG_MSG("set_capstyle()", 1, self) self.select() GraphicsContextBase.set_capstyle(self, cs) self._pen.SetCap(GraphicsContextWx._capd[self._capstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_joinstyle(self, js): """ Set the join style to be one of ('miter', 'round', 'bevel') """ DEBUG_MSG("set_joinstyle()", 1, self) self.select() GraphicsContextBase.set_joinstyle(self, js) self._pen.SetJoin(GraphicsContextWx._joind[self._joinstyle]) self.gfx_ctx.SetPen(self._pen) self.unselect() def set_linestyle(self, ls): """ Set the line style to be one of """ DEBUG_MSG("set_linestyle()", 1, self) self.select() GraphicsContextBase.set_linestyle(self, ls) try: self._style = GraphicsContextWx._dashd_wx[ls] except KeyError: self._style = wx.LONG_DASH# Style not used elsewhere... # On MS Windows platform, only line width of 1 allowed for dash lines if wx.Platform == '__WXMSW__': self.set_linewidth(1) self._pen.SetStyle(self._style) self.gfx_ctx.SetPen(self._pen) self.unselect() def get_wxcolour(self, color): """return a wx.Colour from RGB format""" DEBUG_MSG("get_wx_color()", 1, self) if len(color) == 3: r, g, b = color r *= 255 g *= 255 b *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b)) else: r, g, b, a = color r *= 255 g *= 255 b *= 255 a *= 255 return wx.Colour(red=int(r), green=int(g), blue=int(b), alpha=int(a))
class GraphicsContextWx(GraphicsContextBase): ''' The graphics context provides the color, line styles, etc... This class stores a reference to a wxMemoryDC, and a wxGraphicsContext that draws to it. Creating a wxGraphicsContext seems to be fairly heavy, so these objects are cached based on the bitmap object that is passed in. The base GraphicsContext stores colors as a RGB tuple on the unit interval, eg, (0.5, 0.0, 1.0). wxPython uses an int interval, but since wxPython colour management is rather simple, I have not chosen to implement a separate colour manager class. ''' def __init__(self, bitmap, renderer): pass def select(self): ''' Select the current bitmap into this wxDC instance ''' pass def unselect(self): ''' Select a Null bitmasp into this wxDC instance ''' pass def set_foreground(self, fg, isRGBA=None): ''' Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. ''' pass def set_graylevel(self, frac): ''' Set the foreground color. fg can be a matlab format string, a html hex color string, an rgb unit tuple, or a float between 0 and 1. In the latter case, grayscale is used. ''' pass def set_linewidth(self, w): ''' Set the line width. ''' pass def set_capstyle(self, cs): ''' Set the capstyle as a string in ('butt', 'round', 'projecting') ''' pass def set_joinstyle(self, js): ''' Set the join style to be one of ('miter', 'round', 'bevel') ''' pass def set_linestyle(self, ls): ''' Set the line style to be one of ''' pass def get_wxcolour(self, color): '''return a wx.Colour from RGB format''' pass
11
10
13
1
9
4
2
0.47
1
2
0
0
10
7
10
10
170
20
103
26
92
48
97
26
86
3
1
1
18
6,983
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.FigureManagerWx
class FigureManagerWx(FigureManagerBase): """ This class contains the FigureCanvas and GUI frame It is instantiated by GcfWx whenever a new figure is created. GcfWx is responsible for managing multiple instances of FigureManagerWx. public attrs canvas - a FigureCanvasWx(wx.Panel) instance window - a wxFrame instance - http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin_wxframe.html#wxframe """ def __init__(self, canvas, num, frame): DEBUG_MSG("__init__()", 1, self) FigureManagerBase.__init__(self, canvas, num) self.frame = frame self.window = frame self.tb = frame.GetToolBar() self.toolbar = self.tb # consistent with other backends def notify_axes_change(fig): 'this will be called whenever the current axes is changed' if self.tb != None: self.tb.update() self.canvas.figure.add_axobserver(notify_axes_change) def show(self): self.frame.Show() def destroy(self, *args): DEBUG_MSG("destroy()", 1, self) self.frame.Destroy() #if self.tb is not None: self.tb.Destroy() #wx.GetApp().ProcessIdle() wx.WakeUpIdle() def get_window_title(self): return self.window.GetTitle() def set_window_title(self, title): self.window.SetTitle(title) def resize(self, width, height): 'Set the canvas size in pixels' self.canvas.SetInitialSize(wx.Size(width, height)) self.window.GetSizer().Fit(self.window)
class FigureManagerWx(FigureManagerBase): ''' This class contains the FigureCanvas and GUI frame It is instantiated by GcfWx whenever a new figure is created. GcfWx is responsible for managing multiple instances of FigureManagerWx. public attrs canvas - a FigureCanvasWx(wx.Panel) instance window - a wxFrame instance - http://www.lpthe.jussieu.fr/~zeitlin/wxWindows/docs/wxwin_wxframe.html#wxframe ''' def __init__(self, canvas, num, frame): pass def notify_axes_change(fig): '''this will be called whenever the current axes is changed''' pass def show(self): pass def destroy(self, *args): pass def get_window_title(self): pass def set_window_title(self, title): pass def resize(self, width, height): '''Set the canvas size in pixels''' pass
8
3
4
0
4
1
1
0.54
1
0
0
0
6
4
6
6
45
9
24
12
16
13
25
12
17
2
1
1
8
6,984
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.FigureFrameWx
class FigureFrameWx(wx.Frame): def __init__(self, num, fig): # On non-Windows platform, explicitly set the position - fix # positioning bug on some Linux platforms if wx.Platform == '__WXMSW__': pos = wx.DefaultPosition else: pos =wx.Point(20,20) l,b,w,h = fig.bbox.bounds wx.Frame.__init__(self, parent=None, id=-1, pos=pos, title="Figure %d" % num) # Frame will be sized later by the Fit method DEBUG_MSG("__init__()", 1, self) self.num = num statbar = StatusBarWx(self) self.SetStatusBar(statbar) self.canvas = self.get_canvas(fig) self.canvas.SetInitialSize(wx.Size(fig.bbox.width, fig.bbox.height)) self.canvas.SetFocus() self.sizer =wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version self.toolbar = self._get_toolbar(statbar) if self.toolbar is not None: self.toolbar.Realize() # On Windows platform, default window size is incorrect, so set # toolbar width to figure width. tw, th = self.toolbar.GetSizeTuple() fw, fh = self.canvas.GetSizeTuple() # By adding toolbar in sizer, we are able to put it at the bottom # of the frame - so appearance is closer to GTK version. self.toolbar.SetSize(wx.Size(fw, th)) self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self.canvas.SetMinSize((2, 2)) # give the window a matplotlib icon rather than the stock one. # This is not currently working on Linux and is untested elsewhere. #icon_path = os.path.join(matplotlib.rcParams['datapath'], # 'images', 'matplotlib.png') #icon = wx.IconFromBitmap(wx.Bitmap(icon_path)) # for xpm type icons try: #icon = wx.Icon(icon_path, wx.BITMAP_TYPE_XPM) #self.SetIcon(icon) self.figmgr = FigureManagerWx(self.canvas, num, self) bind(self, wx.EVT_CLOSE, self._onClose) def _get_toolbar(self, statbar): if rcParams['toolbar']=='classic': toolbar = NavigationToolbarWx(self.canvas, True) elif rcParams['toolbar']=='toolbar2': toolbar = NavigationToolbar2Wx(self.canvas) toolbar.set_status_bar(statbar) else: toolbar = None return toolbar def get_canvas(self, fig): return FigureCanvasWx(self, -1, fig) def get_figure_manager(self): DEBUG_MSG("get_figure_manager()", 1, self) return self.figmgr def _onClose(self, evt): DEBUG_MSG("onClose()", 1, self) self.canvas.close_event() self.canvas.stop_event_loop() Gcf.destroy(self.num) #self.Destroy() def GetToolBar(self): """Override wxFrame::GetToolBar as we don't have managed toolbar""" return self.toolbar def Destroy(self, *args, **kwargs): try: self.canvas.mpl_disconnect(self.toolbar._idDrag) # Rationale for line above: see issue 2941338. except AttributeError: pass # classic toolbar lacks the attribute wx.Frame.Destroy(self, *args, **kwargs) if self.toolbar is not None: self.toolbar.Destroy() wxapp = wx.GetApp() if wxapp: wxapp.Yield() return True
class FigureFrameWx(wx.Frame): def __init__(self, num, fig): pass def _get_toolbar(self, statbar): pass def get_canvas(self, fig): pass def get_figure_manager(self): pass def _onClose(self, evt): pass def GetToolBar(self): '''Override wxFrame::GetToolBar as we don't have managed toolbar''' pass def Destroy(self, *args, **kwargs): pass
8
1
13
1
9
3
2
0.33
1
6
5
0
7
5
7
7
96
13
63
20
55
21
59
20
51
4
1
1
14
6,985
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.FigureCanvasWx
class FigureCanvasWx(FigureCanvasBase, wx.Panel): """ The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wx.Sizer to control the displayed control size - but we give a hint as to our preferred minimum size. """ keyvald = { wx.WXK_CONTROL : 'control', wx.WXK_SHIFT : 'shift', wx.WXK_ALT : 'alt', wx.WXK_LEFT : 'left', wx.WXK_UP : 'up', wx.WXK_RIGHT : 'right', wx.WXK_DOWN : 'down', wx.WXK_ESCAPE : 'escape', wx.WXK_F1 : 'f1', wx.WXK_F2 : 'f2', wx.WXK_F3 : 'f3', wx.WXK_F4 : 'f4', wx.WXK_F5 : 'f5', wx.WXK_F6 : 'f6', wx.WXK_F7 : 'f7', wx.WXK_F8 : 'f8', wx.WXK_F9 : 'f9', wx.WXK_F10 : 'f10', wx.WXK_F11 : 'f11', wx.WXK_F12 : 'f12', wx.WXK_SCROLL : 'scroll_lock', wx.WXK_PAUSE : 'break', wx.WXK_BACK : 'backspace', wx.WXK_RETURN : 'enter', wx.WXK_INSERT : 'insert', wx.WXK_DELETE : 'delete', wx.WXK_HOME : 'home', wx.WXK_END : 'end', #wx.WXK_PRIOR : 'pageup', #wx.WXK_NEXT : 'pagedown', wx.WXK_PAGEUP : 'pageup', wx.WXK_PAGEDOWN : 'pagedown', wx.WXK_NUMPAD0 : '0', wx.WXK_NUMPAD1 : '1', wx.WXK_NUMPAD2 : '2', wx.WXK_NUMPAD3 : '3', wx.WXK_NUMPAD4 : '4', wx.WXK_NUMPAD5 : '5', wx.WXK_NUMPAD6 : '6', wx.WXK_NUMPAD7 : '7', wx.WXK_NUMPAD8 : '8', wx.WXK_NUMPAD9 : '9', wx.WXK_NUMPAD_ADD : '+', wx.WXK_NUMPAD_SUBTRACT : '-', wx.WXK_NUMPAD_MULTIPLY : '*', wx.WXK_NUMPAD_DIVIDE : '/', wx.WXK_NUMPAD_DECIMAL : 'dec', wx.WXK_NUMPAD_ENTER : 'enter', wx.WXK_NUMPAD_UP : 'up', wx.WXK_NUMPAD_RIGHT : 'right', wx.WXK_NUMPAD_DOWN : 'down', wx.WXK_NUMPAD_LEFT : 'left', #wx.WXK_NUMPAD_PRIOR : 'pageup', #wx.WXK_NUMPAD_NEXT : 'pagedown', wx.WXK_NUMPAD_PAGEUP : 'pageup', wx.WXK_NUMPAD_PAGEDOWN : 'pagedown', wx.WXK_NUMPAD_HOME : 'home', wx.WXK_NUMPAD_END : 'end', wx.WXK_NUMPAD_INSERT : 'insert', wx.WXK_NUMPAD_DELETE : 'delete', } def __init__(self, parent, id, figure): """ Initialise a FigureWx instance. - Initialise the FigureCanvasBase and wxPanel parents. - Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event) """ FigureCanvasBase.__init__(self, figure) # Set preferred window size hint - helps the sizer (if one is # connected) l,b,w,h = figure.bbox.bounds w = int(math.ceil(w)) h = int(math.ceil(h)) wx.Panel.__init__(self, parent, id, size=wx.Size(w, h)) def do_nothing(*args, **kwargs): warnings.warn('could not find a setinitialsize function for backend_wx; please report your wxpython version=%s to the matplotlib developers list'%backend_version) pass # try to find the set size func across wx versions try: getattr(self, 'SetInitialSize') except AttributeError: self.SetInitialSize = getattr(self, 'SetBestFittingSize', do_nothing) if not hasattr(self,'IsShownOnScreen'): self.IsShownOnScreen = getattr(self, 'IsVisible', lambda *args: True) # Create the drawing bitmap self.bitmap =wx.EmptyBitmap(w, h) DEBUG_MSG("__init__() - bitmap w:%d h:%d" % (w,h), 2, self) # TODO: Add support for 'point' inspection and plot navigation. self._isDrawn = False bind(self, wx.EVT_SIZE, self._onSize) bind(self, wx.EVT_PAINT, self._onPaint) bind(self, wx.EVT_ERASE_BACKGROUND, self._onEraseBackground) bind(self, wx.EVT_KEY_DOWN, self._onKeyDown) bind(self, wx.EVT_KEY_UP, self._onKeyUp) bind(self, wx.EVT_RIGHT_DOWN, self._onRightButtonDown) bind(self, wx.EVT_RIGHT_DCLICK, self._onRightButtonDClick) bind(self, wx.EVT_RIGHT_UP, self._onRightButtonUp) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel) bind(self, wx.EVT_LEFT_DOWN, self._onLeftButtonDown) bind(self, wx.EVT_LEFT_DCLICK, self._onLeftButtonDClick) bind(self, wx.EVT_LEFT_UP, self._onLeftButtonUp) bind(self, wx.EVT_MOTION, self._onMotion) bind(self, wx.EVT_LEAVE_WINDOW, self._onLeave) bind(self, wx.EVT_ENTER_WINDOW, self._onEnter) bind(self, wx.EVT_IDLE, self._onIdle) #Add middle button events bind(self, wx.EVT_MIDDLE_DOWN, self._onMiddleButtonDown) bind(self, wx.EVT_MIDDLE_DCLICK, self._onMiddleButtonDClick) bind(self, wx.EVT_MIDDLE_UP, self._onMiddleButtonUp) self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM) self.macros = {} # dict from wx id to seq of macros # printer attributes and methods deprecated, 2010/06/19 self._printerData = None self._printerPageData = None self.printer_width = 5.5 self.printer_margin = 0.5 def Destroy(self, *args, **kwargs): wx.Panel.Destroy(self, *args, **kwargs) def Copy_to_Clipboard(self, event=None): "copy bitmap of canvas to system clipboard" bmp_obj = wx.BitmapDataObject() bmp_obj.SetBitmap(self.bitmap) if not wx.TheClipboard.IsOpened(): open_success = wx.TheClipboard.Open() if open_success: wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Close() wx.TheClipboard.Flush() def draw_idle(self): """ Delay rendering until the GUI is idle. """ DEBUG_MSG("draw_idle()", 1, self) self._isDrawn = False # Force redraw # Create a timer for handling draw_idle requests # If there are events pending when the timer is # complete, reset the timer and continue. The # alternative approach, binding to wx.EVT_IDLE, # doesn't behave as nicely. if hasattr(self,'_idletimer'): self._idletimer.Restart(IDLE_DELAY) else: self._idletimer = wx.FutureCall(IDLE_DELAY,self._onDrawIdle) # FutureCall is a backwards-compatible alias; # CallLater became available in 2.7.1.1. def _onDrawIdle(self, *args, **kwargs): if wx.GetApp().Pending(): self._idletimer.Restart(IDLE_DELAY, *args, **kwargs) else: del self._idletimer # GUI event or explicit draw call may already # have caused the draw to take place if not self._isDrawn: self.draw(*args, **kwargs) def draw(self, drawDC=None): """ Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. """ DEBUG_MSG("draw()", 1, self) self.renderer = RendererWx(self.bitmap, self.figure.dpi) self.figure.draw(self.renderer) self._isDrawn = True self.gui_repaint(drawDC=drawDC) def new_timer(self, *args, **kwargs): """ Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. optional arguments: *interval* Timer interval in milliseconds *callbacks* Sequence of (func, args, kwargs) where func(*args, **kwargs) will be executed by the timer every *interval*. """ return TimerWx(self, *args, **kwargs) def flush_events(self): wx.Yield() def start_event_loop(self, timeout=0): """ Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. Call signature:: start_event_loop(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. Raises RuntimeError if event loop is already running. """ if hasattr(self, '_event_loop'): raise RuntimeError("Event loop already running") id = wx.NewId() timer = wx.Timer(self, id=id) if timeout > 0: timer.Start(timeout*1000, oneShot=True) bind(self, wx.EVT_TIMER, self.stop_event_loop, id=id) # Event loop handler for start/stop event loop self._event_loop = wx.EventLoop() self._event_loop.Run() timer.Stop() def stop_event_loop(self, event=None): """ Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) """ if hasattr(self,'_event_loop'): if self._event_loop.IsRunning(): self._event_loop.Exit() del self._event_loop def _get_imagesave_wildcards(self): 'return the wildcard string for the filesave dialog' default_filetype = self.get_default_filetype() filetypes = self.get_supported_filetypes_grouped() sorted_filetypes = filetypes.items() sorted_filetypes.sort() wildcards = [] extensions = [] filter_index = 0 for i, (name, exts) in enumerate(sorted_filetypes): ext_list = ';'.join(['*.%s' % ext for ext in exts]) extensions.append(exts[0]) wildcard = '%s (%s)|%s' % (name, ext_list, ext_list) if default_filetype in exts: filter_index = i wildcards.append(wildcard) wildcards = '|'.join(wildcards) return wildcards, extensions, filter_index def gui_repaint(self, drawDC=None): """ Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image. """ DEBUG_MSG("gui_repaint()", 1, self) if self.IsShownOnScreen(): if drawDC is None: drawDC=wx.ClientDC(self) #drawDC.BeginDrawing() drawDC.DrawBitmap(self.bitmap, 0, 0) #drawDC.EndDrawing() #wx.GetApp().Yield() else: pass filetypes = FigureCanvasBase.filetypes.copy() filetypes['bmp'] = 'Windows bitmap' filetypes['jpeg'] = 'JPEG' filetypes['jpg'] = 'JPEG' filetypes['pcx'] = 'PCX' filetypes['png'] = 'Portable Network Graphics' filetypes['tif'] = 'Tagged Image Format File' filetypes['tiff'] = 'Tagged Image Format File' filetypes['xpm'] = 'X pixmap' def print_figure(self, filename, *args, **kwargs): # Use pure Agg renderer to draw FigureCanvasBase.print_figure(self, filename, *args, **kwargs) # Restore the current view; this is needed because the # artist contains methods rely on particular attributes # of the rendered figure for determining things like # bounding boxes. if self._isDrawn: self.draw() def print_bmp(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_BMP, *args, **kwargs) if not _has_pil: def print_jpeg(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_JPEG, *args, **kwargs) print_jpg = print_jpeg def print_pcx(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PCX, *args, **kwargs) def print_png(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_PNG, *args, **kwargs) if not _has_pil: def print_tiff(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_TIF, *args, **kwargs) print_tif = print_tiff def print_xpm(self, filename, *args, **kwargs): return self._print_image(filename, wx.BITMAP_TYPE_XPM, *args, **kwargs) def _print_image(self, filename, filetype, *args, **kwargs): origBitmap = self.bitmap l,b,width,height = self.figure.bbox.bounds width = int(math.ceil(width)) height = int(math.ceil(height)) self.bitmap = wx.EmptyBitmap(width, height) renderer = RendererWx(self.bitmap, self.figure.dpi) gc = renderer.new_gc() self.figure.draw(renderer) # image is the object that we call SaveFile on. image = self.bitmap # set the JPEG quality appropriately. Unfortunately, it is only possible # to set the quality on a wx.Image object. So if we are saving a JPEG, # convert the wx.Bitmap to a wx.Image, and set the quality. if filetype == wx.BITMAP_TYPE_JPEG: jpeg_quality = kwargs.get('quality',rcParams['savefig.jpeg_quality']) image = self.bitmap.ConvertToImage() image.SetOption(wx.IMAGE_OPTION_QUALITY,str(jpeg_quality)) # Now that we have rendered into the bitmap, save it # to the appropriate file type and clean up if is_string_like(filename): if not image.SaveFile(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError('Could not save figure to %s\n' % (filename)) elif is_writable_file_like(filename): if not isinstance(image,wx.Image): image = image.ConvertToImage() if not image.SaveStream(filename, filetype): DEBUG_MSG('print_figure() file save error', 4, self) raise RuntimeError('Could not save figure to %s\n' % (filename)) # Restore everything to normal self.bitmap = origBitmap # Note: draw is required here since bits of state about the # last renderer are strewn about the artist draw methods. Do # not remove the draw without first verifying that these have # been cleaned up. The artist contains() methods will fail # otherwise. if self._isDrawn: self.draw() self.Refresh() def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ DEBUG_MSG("_onPaint()", 1, self) drawDC = wx.PaintDC(self) if not self._isDrawn: self.draw(drawDC=drawDC) else: self.gui_repaint(drawDC=drawDC) evt.Skip() def _onEraseBackground(self, evt): """ Called when window is redrawn; since we are blitting the entire image, we can leave this blank to suppress flicker. """ pass def _onSize(self, evt): """ Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. """ DEBUG_MSG("_onSize()", 2, self) # Create a new, correctly sized bitmap self._width, self._height = self.GetClientSize() self.bitmap =wx.EmptyBitmap(self._width, self._height) self._isDrawn = False if self._width <= 1 or self._height <= 1: return # Empty figure dpival = self.figure.dpi winch = self._width/dpival hinch = self._height/dpival self.figure.set_size_inches(winch, hinch) # Rendering will happen on the associated paint event # so no need to do anything here except to make sure # the whole background is repainted. self.Refresh(eraseBackground=False) FigureCanvasBase.resize_event(self) def _get_key(self, evt): keyval = evt.m_keyCode if keyval in self.keyvald: key = self.keyvald[keyval] elif keyval < 256: key = chr(keyval) # wx always returns an uppercase, so make it lowercase if the shift # key is not depressed (NOTE: this will not handle Caps Lock) if not evt.ShiftDown(): key = key.lower() else: key = None for meth, prefix in ( [evt.AltDown, 'alt'], [evt.ControlDown, 'ctrl'], ): if meth(): key = '{0}+{1}'.format(prefix, key) return key def _onIdle(self, evt): 'a GUI idle event' evt.Skip() FigureCanvasBase.idle_event(self, guiEvent=evt) def _onKeyDown(self, evt): """Capture key press.""" key = self._get_key(evt) evt.Skip() FigureCanvasBase.key_press_event(self, key, guiEvent=evt) def _onKeyUp(self, evt): """Release key.""" key = self._get_key(evt) #print 'release key', key evt.Skip() FigureCanvasBase.key_release_event(self, key, guiEvent=evt) def _onRightButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 3, guiEvent=evt) def _onRightButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 3, dblclick=True,guiEvent=evt) def _onRightButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 3, guiEvent=evt) def _onLeftButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, guiEvent=evt) def _onLeftButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 1, dblclick=True, guiEvent=evt) def _onLeftButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() #print 'release button', 1 evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 1, guiEvent=evt) #Add middle button events def _onMiddleButtonDown(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 2, guiEvent=evt) def _onMiddleButtonDClick(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() self.CaptureMouse() FigureCanvasBase.button_press_event(self, x, y, 2, dblclick=True, guiEvent=evt) def _onMiddleButtonUp(self, evt): """End measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() #print 'release button', 1 evt.Skip() if self.HasCapture(): self.ReleaseMouse() FigureCanvasBase.button_release_event(self, x, y, 2, guiEvent=evt) def _onMouseWheel(self, evt): """Translate mouse wheel events into matplotlib events""" # Determine mouse location x = evt.GetX() y = self.figure.bbox.height - evt.GetY() # Convert delta/rotation/rate into a floating point step size delta = evt.GetWheelDelta() rotation = evt.GetWheelRotation() rate = evt.GetLinesPerAction() #print "delta,rotation,rate",delta,rotation,rate step = rate*float(rotation)/delta # Done handling event evt.Skip() # Mac is giving two events for every wheel event # Need to skip every second one if wx.Platform == '__WXMAC__': if not hasattr(self,'_skipwheelevent'): self._skipwheelevent = True elif self._skipwheelevent: self._skipwheelevent = False return # Return without processing event else: self._skipwheelevent = True # Convert to mpl event FigureCanvasBase.scroll_event(self, x, y, step, guiEvent=evt) def _onMotion(self, evt): """Start measuring on an axis.""" x = evt.GetX() y = self.figure.bbox.height - evt.GetY() evt.Skip() FigureCanvasBase.motion_notify_event(self, x, y, guiEvent=evt) def _onLeave(self, evt): """Mouse has left the window.""" evt.Skip() FigureCanvasBase.leave_notify_event(self, guiEvent = evt) def _onEnter(self, evt): """Mouse has entered the window.""" FigureCanvasBase.enter_notify_event(self, guiEvent = evt)
class FigureCanvasWx(FigureCanvasBase, wx.Panel): ''' The FigureCanvas contains the figure and does event handling. In the wxPython backend, it is derived from wxPanel, and (usually) lives inside a frame instantiated by a FigureManagerWx. The parent window probably implements a wx.Sizer to control the displayed control size - but we give a hint as to our preferred minimum size. ''' def __init__(self, parent, id, figure): ''' Initialise a FigureWx instance. - Initialise the FigureCanvasBase and wxPanel parents. - Set event handlers for: EVT_SIZE (Resize event) EVT_PAINT (Paint event) ''' pass def do_nothing(*args, **kwargs): pass def Destroy(self, *args, **kwargs): pass def Copy_to_Clipboard(self, event=None): '''copy bitmap of canvas to system clipboard''' pass def draw_idle(self): ''' Delay rendering until the GUI is idle. ''' pass def _onDrawIdle(self, *args, **kwargs): pass def draw_idle(self): ''' Render the figure using RendererWx instance renderer, or using a previously defined renderer if none is specified. ''' pass def new_timer(self, *args, **kwargs): ''' Creates a new backend-specific subclass of :class:`backend_bases.Timer`. This is useful for getting periodic events through the backend's native event loop. Implemented only for backends with GUIs. optional arguments: *interval* Timer interval in milliseconds *callbacks* Sequence of (func, args, kwargs) where func(*args, **kwargs) will be executed by the timer every *interval*. ''' pass def flush_events(self): pass def start_event_loop(self, timeout=0): ''' Start an event loop. This is used to start a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. This should not be confused with the main GUI event loop, which is always running and has nothing to do with this. Call signature:: start_event_loop(self,timeout=0) This call blocks until a callback function triggers stop_event_loop() or *timeout* is reached. If *timeout* is <=0, never timeout. Raises RuntimeError if event loop is already running. ''' pass def stop_event_loop(self, event=None): ''' Stop an event loop. This is used to stop a blocking event loop so that interactive functions, such as ginput and waitforbuttonpress, can wait for events. Call signature:: stop_event_loop_default(self) ''' pass def _get_imagesave_wildcards(self): '''return the wildcard string for the filesave dialog''' pass def gui_repaint(self, drawDC=None): ''' Performs update of the displayed image on the GUI canvas, using the supplied device context. If drawDC is None, a ClientDC will be used to redraw the image. ''' pass def print_figure(self, filename, *args, **kwargs): pass def print_bmp(self, filename, *args, **kwargs): pass def print_jpeg(self, filename, *args, **kwargs): pass def print_pcx(self, filename, *args, **kwargs): pass def print_png(self, filename, *args, **kwargs): pass def print_tiff(self, filename, *args, **kwargs): pass def print_xpm(self, filename, *args, **kwargs): pass def _print_image(self, filename, filetype, *args, **kwargs): pass def _onPaint(self, evt): ''' Called when wxPaintEvt is generated ''' pass def _onEraseBackground(self, evt): ''' Called when window is redrawn; since we are blitting the entire image, we can leave this blank to suppress flicker. ''' pass def _onSize(self, evt): ''' Called when wxEventSize is generated. In this application we attempt to resize to fit the window, so it is better to take the performance hit and redraw the whole window. ''' pass def _get_key(self, evt): pass def _onIdle(self, evt): '''a GUI idle event''' pass def _onKeyDown(self, evt): '''Capture key press.''' pass def _onKeyUp(self, evt): '''Release key.''' pass def _onRightButtonDown(self, evt): '''Start measuring on an axis.''' pass def _onRightButtonDClick(self, evt): '''Start measuring on an axis.''' pass def _onRightButtonUp(self, evt): '''End measuring on an axis.''' pass def _onLeftButtonDown(self, evt): '''Start measuring on an axis.''' pass def _onLeftButtonDClick(self, evt): '''Start measuring on an axis.''' pass def _onLeftButtonUp(self, evt): '''End measuring on an axis.''' pass def _onMiddleButtonDown(self, evt): '''Start measuring on an axis.''' pass def _onMiddleButtonDClick(self, evt): '''Start measuring on an axis.''' pass def _onMiddleButtonUp(self, evt): '''End measuring on an axis.''' pass def _onMouseWheel(self, evt): '''Translate mouse wheel events into matplotlib events''' pass def _onMotion(self, evt): '''Start measuring on an axis.''' pass def _onLeave(self, evt): '''Mouse has left the window.''' pass def _onEnter(self, evt): '''Mouse has entered the window.''' pass
42
29
12
1
7
3
2
0.41
2
8
2
0
40
15
40
40
603
93
365
114
323
149
301
114
259
8
1
2
77
6,986
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_agg.py
MAVProxy.modules.lib.MacOS.backend_agg.RendererAgg
class RendererAgg(RendererBase): """ The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles """ debug=1 # we want to cache the fonts at the class level so that when # multiple figures are created we can reuse them. This helps with # a bug on windows where the creation of too many figures leads to # too many open file handles. However, storing them at the class # level is not thread safe. The solution here is to let the # FigureCanvas acquire a lock on the fontd at the start of the # draw, and release it when it is done. This allows multiple # renderers to share the cached fonts, but only one figure can # draw at at time and so the font cache is used by only one # renderer at a time lock = threading.RLock() _fontd = maxdict(50) def __init__(self, width, height, dpi): if __debug__: verbose.report('RendererAgg.__init__', 'debug-annoying') RendererBase.__init__(self) self.texd = maxdict(50) # a cache of tex image rasters self.dpi = dpi self.width = width self.height = height if __debug__: verbose.report('RendererAgg.__init__ width=%s, height=%s'%(width, height), 'debug-annoying') self._renderer = _RendererAgg(int(width), int(height), dpi, debug=False) self._filter_renderers = [] if __debug__: verbose.report('RendererAgg.__init__ _RendererAgg done', 'debug-annoying') self._update_methods() self.mathtext_parser = MathTextParser('Agg') self.bbox = Bbox.from_bounds(0, 0, self.width, self.height) if __debug__: verbose.report('RendererAgg.__init__ done', 'debug-annoying') def _get_hinting_flag(self): if rcParams['text.hinting']: return LOAD_FORCE_AUTOHINT else: return LOAD_NO_HINTING # for filtering to work with rasterization, methods needs to be wrapped. # maybe there is better way to do it. def draw_markers(self, *kl, **kw): return self._renderer.draw_markers(*kl, **kw) def draw_path_collection(self, *kl, **kw): return self._renderer.draw_path_collection(*kl, **kw) def _update_methods(self): #self.draw_path = self._renderer.draw_path # see below #self.draw_markers = self._renderer.draw_markers #self.draw_path_collection = self._renderer.draw_path_collection self.draw_quad_mesh = self._renderer.draw_quad_mesh self.draw_gouraud_triangle = self._renderer.draw_gouraud_triangle self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles self.draw_image = self._renderer.draw_image self.copy_from_bbox = self._renderer.copy_from_bbox def tostring_rgba_minimized(self): extents = self._renderer.get_content_extents() bbox = [[extents[0], self.height - (extents[1] + extents[3])], [extents[0] + extents[2], self.height - extents[1]]] region = self._renderer.copy_from_bbox(bbox) return np.array(region), extents def draw_path(self, gc, path, transform, rgbFace=None): """ Draw the path """ nmax = rcParams['agg.path.chunksize'] # here at least for testing npts = path.vertices.shape[0] if (nmax > 100 and npts > nmax and path.should_simplify and rgbFace is None and gc.get_hatch() is None): nch = np.ceil(npts/float(nmax)) chsize = int(np.ceil(npts/nch)) i0 = np.arange(0, npts, chsize) i1 = np.zeros_like(i0) i1[:-1] = i0[1:] - 1 i1[-1] = npts for ii0, ii1 in zip(i0, i1): v = path.vertices[ii0:ii1,:] c = path.codes if c is not None: c = c[ii0:ii1] c[0] = Path.MOVETO # move to end of last chunk p = Path(v, c) self._renderer.draw_path(gc, p, transform, rgbFace) else: self._renderer.draw_path(gc, path, transform, rgbFace) def draw_mathtext(self, gc, x, y, s, prop, angle): """ Draw the math text using matplotlib.mathtext """ if __debug__: verbose.report('RendererAgg.draw_mathtext', 'debug-annoying') ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) xd = descent * np.sin(np.deg2rad(angle)) yd = descent * np.cos(np.deg2rad(angle)) x = np.round(x + ox + xd) y = np.round(y - oy + yd) self._renderer.draw_text_image(font_image, x, y + 1, angle, gc) def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): """ Render the text """ if __debug__: verbose.report('RendererAgg.draw_text', 'debug-annoying') if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) flags = get_hinting_flag() font = self._get_agg_font(prop) if font is None: return None if len(s) == 1 and ord(s) > 127: font.load_char(ord(s), flags=flags) else: # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). font.set_text(s, 0, flags=flags) font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased']) d = font.get_descent() / 64.0 # The descent needs to be adjusted for the angle xd = -d * np.sin(np.deg2rad(angle)) yd = d * np.cos(np.deg2rad(angle)) #print x, y, int(x), int(y), s self._renderer.draw_text_image( font.get_image(), np.round(x - xd), np.round(y + yd) + 1, angle, gc) def get_text_width_height_descent(self, s, prop, ismath): """ get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend """ if rcParams['text.usetex']: # todo: handle props size = prop.get_size_in_points() texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent(s, fontsize, renderer=self) return w, h, d if ismath: ox, oy, width, height, descent, fonts, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) return width, height, descent flags = get_hinting_flag() font = self._get_agg_font(prop) font.set_text(s, 0.0, flags=flags) # the width and height of unrotated string w, h = font.get_width_height() d = font.get_descent() w /= 64.0 # convert from subpixels h /= 64.0 d /= 64.0 return w, h, d def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None): # todo, handle props, angle, origins size = prop.get_size_in_points() texmanager = self.get_texmanager() key = s, size, self.dpi, angle, texmanager.get_font_config() im = self.texd.get(key) if im is None: Z = texmanager.get_grey(s, size, self.dpi) Z = np.array(Z * 255.0, np.uint8) w, h, d = self.get_text_width_height_descent(s, prop, ismath) xd = d * np.sin(np.deg2rad(angle)) yd = d * np.cos(np.deg2rad(angle)) x = np.round(x + xd) y = np.round(y + yd) self._renderer.draw_text_image(Z, x, y, angle, gc) def get_canvas_width_height(self): 'return the canvas width and height in display coords' return self.width, self.height def _get_agg_font(self, prop): """ Get the font for text instance t, cacheing for efficiency """ if __debug__: verbose.report('RendererAgg._get_agg_font', 'debug-annoying') key = hash(prop) font = RendererAgg._fontd.get(key) if font is None: fname = findfont(prop) font = RendererAgg._fontd.get(fname) if font is None: font = FT2Font( str(fname), hinting_factor=rcParams['text.hinting_factor']) RendererAgg._fontd[fname] = font RendererAgg._fontd[key] = font font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font def points_to_pixels(self, points): """ convert point measures to pixes using dpi and the pixels per inch of the display """ if __debug__: verbose.report('RendererAgg.points_to_pixels', 'debug-annoying') return points*self.dpi/72.0 def tostring_rgb(self): if __debug__: verbose.report('RendererAgg.tostring_rgb', 'debug-annoying') return self._renderer.tostring_rgb() def tostring_argb(self): if __debug__: verbose.report('RendererAgg.tostring_argb', 'debug-annoying') return self._renderer.tostring_argb() def buffer_rgba(self): if __debug__: verbose.report('RendererAgg.buffer_rgba', 'debug-annoying') return self._renderer.buffer_rgba() def clear(self): self._renderer.clear() def option_image_nocomposite(self): # It is generally faster to composite each image directly to # the Figure, and there's no file size benefit to compositing # with the Agg backend return True def option_scale_image(self): """ agg backend support arbitrary scaling of image. """ return True def restore_region(self, region, bbox=None, xy=None): """ Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. *xy* (a tuple of two floasts) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored. >>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1)) """ if bbox is not None or xy is not None: if bbox is None: x1, y1, x2, y2 = region.get_extents() elif isinstance(bbox, BboxBase): x1, y1, x2, y2 = bbox.extents else: x1, y1, x2, y2 = bbox if xy is None: ox, oy = x1, y1 else: ox, oy = xy self._renderer.restore_region2(region, x1, y1, x2, y2, ox, oy) else: self._renderer.restore_region(region) def start_filter(self): """ Start filtering. It simply create a new canvas (the old one is saved). """ self._filter_renderers.append(self._renderer) self._renderer = _RendererAgg(int(self.width), int(self.height), self.dpi) self._update_methods() def stop_filter(self, post_processing): """ Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. """ # WARNING. # For agg_filter to work, the rendere's method need # to overridden in the class. See draw_markers, and draw_path_collections from matplotlib._image import fromarray width, height = int(self.width), int(self.height) buffer, bounds = self._renderer.tostring_rgba_minimized() l, b, w, h = bounds self._renderer = self._filter_renderers.pop() self._update_methods() if w > 0 and h > 0: img = np.fromstring(buffer, np.uint8) img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255., self.dpi) image = fromarray(img, 1) image.flipud_out() gc = self.new_gc() self._renderer.draw_image(gc, l+ox, height - b - h +oy, image)
class RendererAgg(RendererBase): ''' The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles ''' def __init__(self, width, height, dpi): pass def _get_hinting_flag(self): pass def draw_markers(self, *kl, **kw): pass def draw_path_collection(self, *kl, **kw): pass def _update_methods(self): pass def tostring_rgba_minimized(self): pass def draw_path_collection(self, *kl, **kw): ''' Draw the path ''' pass def draw_mathtext(self, gc, x, y, s, prop, angle): ''' Draw the math text using matplotlib.mathtext ''' pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): ''' Render the text ''' pass def get_text_width_height_descent(self, s, prop, ismath): ''' get the width and height in display coords of the string s with FontPropertry prop # passing rgb is a little hack to make cacheing in the # texmanager more efficient. It is not meant to be used # outside the backend ''' pass def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): pass def get_canvas_width_height(self): '''return the canvas width and height in display coords''' pass def _get_agg_font(self, prop): ''' Get the font for text instance t, cacheing for efficiency ''' pass def points_to_pixels(self, points): ''' convert point measures to pixes using dpi and the pixels per inch of the display ''' pass def tostring_rgba_minimized(self): pass def tostring_argb(self): pass def buffer_rgba(self): pass def clear(self): pass def option_image_nocomposite(self): pass def option_scale_image(self): ''' agg backend support arbitrary scaling of image. ''' pass def restore_region(self, region, bbox=None, xy=None): ''' Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. *xy* (a tuple of two floasts) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored. >>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1)) ''' pass def start_filter(self): ''' Start filtering. It simply create a new canvas (the old one is saved). ''' pass def stop_filter(self, post_processing): ''' Save the plot in the current canvas as a image and apply the *post_processing* function. def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. ''' pass
24
12
13
1
9
3
2
0.45
1
4
0
0
23
13
23
23
349
59
204
90
179
91
189
90
164
5
1
3
51
6,987
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_agg.py
MAVProxy.modules.lib.MacOS.backend_agg.FigureCanvasAgg
class FigureCanvasAgg(FigureCanvasBase): """ The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance """ def copy_from_bbox(self, bbox): renderer = self.get_renderer() return renderer.copy_from_bbox(bbox) def restore_region(self, region, bbox=None, xy=None): renderer = self.get_renderer() return renderer.restore_region(region, bbox, xy) def draw(self): """ Draw the figure using the renderer """ if __debug__: verbose.report('FigureCanvasAgg.draw', 'debug-annoying') self.renderer = self.get_renderer(cleared=True) # acquire a lock on the shared font cache RendererAgg.lock.acquire() try: self.figure.draw(self.renderer) finally: RendererAgg.lock.release() def get_renderer(self, cleared=False): l, b, w, h = self.figure.bbox.bounds key = w, h, self.figure.dpi try: self._lastKey, self.renderer except AttributeError: need_new_renderer = True else: need_new_renderer = (self._lastKey != key) if need_new_renderer: self.renderer = RendererAgg(w, h, self.figure.dpi) self._lastKey = key elif cleared: self.renderer.clear() return self.renderer def tostring_rgb(self): if __debug__: verbose.report('FigureCanvasAgg.tostring_rgb', 'debug-annoying') return self.renderer.tostring_rgb() def tostring_argb(self): if __debug__: verbose.report('FigureCanvasAgg.tostring_argb', 'debug-annoying') return self.renderer.tostring_argb() def buffer_rgba(self): if __debug__: verbose.report('FigureCanvasAgg.buffer_rgba', 'debug-annoying') return self.renderer.buffer_rgba() def print_raw(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = open(filename_or_obj, 'wb') close = True else: close = False try: renderer._renderer.write_rgba(filename_or_obj) finally: if close: filename_or_obj.close() renderer.dpi = original_dpi print_rgba = print_raw def print_png(self, filename_or_obj, *args, **kwargs): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi if is_string_like(filename_or_obj): filename_or_obj = open(filename_or_obj, 'wb') close = True else: close = False try: _png.write_png(renderer._renderer.buffer_rgba(), renderer.width, renderer.height, filename_or_obj, self.figure.dpi) finally: if close: filename_or_obj.close() renderer.dpi = original_dpi def print_to_buffer(self): FigureCanvasAgg.draw(self) renderer = self.get_renderer() original_dpi = renderer.dpi renderer.dpi = self.figure.dpi result = (renderer._renderer.buffer_rgba(), (int(renderer.width), int(renderer.height))) renderer.dpi = original_dpi return result
class FigureCanvasAgg(FigureCanvasBase): ''' The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc... Public attribute figure - A Figure instance ''' def copy_from_bbox(self, bbox): pass def restore_region(self, region, bbox=None, xy=None): pass def draw(self): ''' Draw the figure using the renderer ''' pass def get_renderer(self, cleared=False): pass def tostring_rgb(self): pass def tostring_argb(self): pass def buffer_rgba(self): pass def print_raw(self, filename_or_obj, *args, **kwargs): pass def print_png(self, filename_or_obj, *args, **kwargs): pass def print_to_buffer(self): pass
11
2
9
0
8
0
2
0.12
1
2
0
0
10
2
10
10
110
17
83
28
72
10
78
28
67
4
1
2
21
6,988
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/LowPassFilter2p.py
MAVProxy.modules.lib.LowPassFilter2p.LowPassFilter2p
class LowPassFilter2p: def __init__(self, sample_freq, cutoff_freq): self.cutoff_freq = cutoff_freq self.sample_freq = sample_freq self.a1 = 0.0 self.a2 = 0.0 self.b0 = 0.0 self.b1 = 0.0 self.b2 = 0.0 self.delay_element_1 = None self.delay_element_2 = None self.set_cutoff_frequency(sample_freq, cutoff_freq) def set_cutoff_frequency(self, sample_freq, cutoff_freq): self.cutoff_freq = cutoff_freq if self.cutoff_freq <= 0.0: return fr = self.sample_freq/self.cutoff_freq ohm = tan(pi/fr) c = 1.0+2.0*cos(pi/4.0)*ohm + ohm*ohm self.b0 = ohm*ohm/c self.b1 = 2.0*self.b0 self.b2 = self.b0 self.a1 = 2.0*(ohm*ohm-1.0)/c self.a2 = (1.0-2.0*cos(pi/4.0)*ohm+ohm*ohm)/c def apply(self, sample): if self.delay_element_1 is None: self.delay_element_1 = sample self.delay_element_2 = sample delay_element_0 = sample - (self.delay_element_1 * self.a1) - (self.delay_element_2 * self.a2) output = (delay_element_0 * self.b0) + (self.delay_element_1 * self.b1) + (self.delay_element_2 * self.b2) self.delay_element_2 = self.delay_element_1 self.delay_element_1 = delay_element_0 return output
class LowPassFilter2p: def __init__(self, sample_freq, cutoff_freq): pass def set_cutoff_frequency(self, sample_freq, cutoff_freq): pass def apply(self, sample): pass
4
0
11
1
11
0
2
0
0
0
0
0
3
9
3
3
37
4
33
18
29
0
33
18
29
2
0
1
5
6,989
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/ANUGA/geo_reference.py
MAVProxy.modules.lib.ANUGA.geo_reference.Geo_reference
class Geo_reference: """ Attributes of the Geo_reference class: .zone The UTM zone (default is -1) .false_easting ?? .false_northing ?? .datum The Datum used (default is wgs84) .projection The projection used (default is 'UTM') .units The units of measure used (default metres) .xllcorner The X coord of origin (default is 0.0 wrt UTM grid) .yllcorner The y coord of origin (default is 0.0 wrt UTM grid) .is_absolute ?? """ ## # @brief Instantiate an instance of class Geo_reference. # @param zone The UTM zone. # @param xllcorner X coord of origin of georef. # @param yllcorner Y coord of origin of georef. # @param datum ?? # @param projection The projection used (default UTM). # @param units Units used in measuring distance (default m). # @param false_easting ?? # @param false_northing ?? # @param NetCDFObject NetCDF file *handle* to write to. # @param ASCIIFile ASCII text file *handle* to write to. # @param read_title Title of the georeference text. def __init__(self, zone=DEFAULT_ZONE, xllcorner=0.0, yllcorner=0.0, datum=DEFAULT_DATUM, projection=DEFAULT_PROJECTION, units=DEFAULT_UNITS, false_easting=DEFAULT_FALSE_EASTING, false_northing=DEFAULT_FALSE_NORTHING, NetCDFObject=None, ASCIIFile=None, read_title=None): """ input: NetCDFObject - a handle to the netCDF file to be written to ASCIIFile - a handle to the text file read_title - the title of the georeference text, if it was read in. If the function that calls this has already read the title line, it can't unread it, so this info has to be passed. If you know of a way to unread this info, then tell us. Note, the text file only saves a sub set of the info the points file does. Currently the info not written in text must be the default info, since ANUGA assumes it isn't changing. """ if zone is None: zone = DEFAULT_ZONE self.false_easting = int(false_easting) self.false_northing = int(false_northing) self.datum = datum self.projection = projection self.zone = int(zone) self.units = units self.xllcorner = float(xllcorner) self.yllcorner = float(yllcorner) if NetCDFObject is not None: self.read_NetCDF(NetCDFObject) if ASCIIFile is not None: self.read_ASCII(ASCIIFile, read_title=read_title) # Set flag for absolute points (used by get_absolute) self.absolute = num.allclose([self.xllcorner, self.yllcorner], 0) def get_xllcorner(self): return self.xllcorner ## # @brief Get the Y coordinate of the origin of this georef. def get_yllcorner(self): return self.yllcorner ## # @brief Get the zone of this georef. def get_zone(self): return self.zone ## # @brief Write <something> to an open NetCDF file. # @param outfile Handle to open NetCDF file. def write_NetCDF(self, outfile): outfile.xllcorner = self.xllcorner outfile.yllcorner = self.yllcorner outfile.zone = self.zone outfile.false_easting = self.false_easting outfile.false_northing = self.false_northing outfile.datum = self.datum outfile.projection = self.projection outfile.units = self.units ## # @brief Read data from an open NetCDF file. # @param infile Handle to open NetCDF file. def read_NetCDF(self, infile): self.xllcorner = float(infile.xllcorner[0]) self.yllcorner = float(infile.yllcorner[0]) self.zone = int(infile.zone[0]) try: self.false_easting = int(infile.false_easting[0]) self.false_northing = int(infile.false_northing[0]) self.datum = infile.datum self.projection = infile.projection self.units = infile.units except: pass if self.false_easting != DEFAULT_FALSE_EASTING: print("WARNING: False easting of %f specified." % self.false_easting) print("Default false easting is %f." % DEFAULT_FALSE_EASTING) print("ANUGA does not correct for differences in False Eastings.") if self.false_northing != DEFAULT_FALSE_NORTHING: print("WARNING: False northing of %f specified." % self.false_northing) print("Default false northing is %f." % DEFAULT_FALSE_NORTHING) print("ANUGA does not correct for differences in False Northings.") if self.datum.upper() != DEFAULT_DATUM.upper(): print("WARNING: Datum of %s specified." % self.datum) print("Default Datum is %s." % DEFAULT_DATUM) print("ANUGA does not correct for differences in datums.") if self.projection.upper() != DEFAULT_PROJECTION.upper(): print("WARNING: Projection of %s specified." % self.projection) print("Default Projection is %s." % DEFAULT_PROJECTION) print("ANUGA does not correct for differences in Projection.") if self.units.upper() != DEFAULT_UNITS.upper(): print("WARNING: Units of %s specified." % self.units) print("Default units is %s." % DEFAULT_UNITS) print("ANUGA does not correct for differences in units.") ################################################################################ # ASCII files with geo-refs are currently not used ################################################################################ ## # @brief Write georef data to an open text file. # @param fd Handle to open text file. def write_ASCII(self, fd): fd.write(TITLE) fd.write(str(self.zone) + "\n") fd.write(str(self.xllcorner) + "\n") fd.write(str(self.yllcorner) + "\n") ## # @brief Read georef data from an open text file. # @param fd Handle to open text file. def read_ASCII(self, fd, read_title=None): try: if read_title is None: read_title = fd.readline() # remove the title line if read_title[0:2].upper() != TITLE[0:2].upper(): msg = ('File error. Expecting line: %s. Got this line: %s' % (TITLE, read_title)) raise ValueError(msg) self.zone = int(fd.readline()) self.xllcorner = float(fd.readline()) self.yllcorner = float(fd.readline()) except SyntaxError: msg = 'File error. Got syntax error while parsing geo reference' raise ValueError(msg) # Fix some assertion failures if isinstance(self.zone, num.ndarray) and self.zone.shape == (): self.zone = self.zone[0] if (isinstance(self.xllcorner, num.ndarray) and self.xllcorner.shape == ()): self.xllcorner = self.xllcorner[0] if (isinstance(self.yllcorner, num.ndarray) and self.yllcorner.shape == ()): self.yllcorner = self.yllcorner[0] assert (type(self.xllcorner) == types.FloatType) assert (type(self.yllcorner) == types.FloatType) assert (type(self.zone) == types.IntType) ################################################################################ ## # @brief Change points to be absolute wrt new georef 'points_geo_ref'. # @param points The points to change. # @param points_geo_ref The new georef to make points absolute wrt. # @return The changed points. # @note If 'points' is a list then a changed list is returned. def change_points_geo_ref(self, points, points_geo_ref=None): """Change the geo reference of a list or numeric array of points to be this reference.(The reference used for this object) If the points do not have a geo ref, assume 'absolute' values """ import copy # remember if we got a list is_list = isinstance(points, list) points = ensure_numeric(points, num.float) # sanity checks if len(points.shape) == 1: #One point has been passed msg = 'Single point must have two elements' assert len(points) == 2, msg points = num.reshape(points, (1,2)) msg = 'Points array must be two dimensional.\n' msg += 'I got %d dimensions' %len(points.shape) assert len(points.shape) == 2, msg msg = 'Input must be an N x 2 array or list of (x,y) values. ' msg += 'I got an %d x %d array' %points.shape assert points.shape[1] == 2, msg # FIXME (Ole): Could also check if zone, xllcorner, yllcorner # are identical in the two geo refs. if points_geo_ref is not self: # If georeferences are different points = copy.copy(points) # Don't destroy input if not points_geo_ref is None: # Convert points to absolute coordinates points[:,0] += points_geo_ref.xllcorner points[:,1] += points_geo_ref.yllcorner # Make points relative to primary geo reference points[:,0] -= self.xllcorner points[:,1] -= self.yllcorner if is_list: points = points.tolist() return points def is_absolute(self): """Return True if xllcorner==yllcorner==0 indicating that points in question are absolute. """ # FIXME(Ole): It is unfortunate that decision about whether points # are absolute or not lies with the georeference object. Ross pointed this out. # Moreover, this little function is responsible for a large fraction of the time # using in data fitting (something in like 40 - 50%. # This was due to the repeated calls to allclose. # With the flag method fitting is much faster (18 Mar 2009). # FIXME(Ole): HACK to be able to reuse data already cached (18 Mar 2009). # Remove at some point if not hasattr(self, 'absolute'): self.absolute = num.allclose([self.xllcorner, self.yllcorner], 0) # Return absolute flag return self.absolute def get_absolute(self, points): """Given a set of points geo referenced to this instance, return the points as absolute values. """ # remember if we got a list is_list = isinstance(points, list) points = ensure_numeric(points, num.float) if len(points.shape) == 1: # One point has been passed msg = 'Single point must have two elements' if not len(points) == 2: raise ValueError(msg) msg = 'Input must be an N x 2 array or list of (x,y) values. ' msg += 'I got an %d x %d array' %points.shape if not points.shape[1] == 2: raise ValueError(msg) # Add geo ref to points if not self.is_absolute(): points = copy.copy(points) # Don't destroy input points[:,0] += self.xllcorner points[:,1] += self.yllcorner if is_list: points = points.tolist() return points ## # @brief Convert points to relative measurement. # @param points Points to convert to relative measurements. # @return A set of points relative to the geo_reference instance. def get_relative(self, points): """Given a set of points in absolute UTM coordinates, make them relative to this geo_reference instance, return the points as relative values. This is the inverse of get_absolute. """ # remember if we got a list is_list = isinstance(points, list) points = ensure_numeric(points, num.float) if len(points.shape) == 1: #One point has been passed msg = 'Single point must have two elements' if not len(points) == 2: raise ValueError(msg) if not points.shape[1] == 2: msg = ('Input must be an N x 2 array or list of (x,y) values. ' 'I got an %d x %d array' % points.shape) raise ValueError(msg) # Subtract geo ref from points if not self.is_absolute(): points = copy.copy(points) # Don't destroy input points[:,0] -= self.xllcorner points[:,1] -= self.yllcorner if is_list: points = points.tolist() return points ## # @brief ?? # @param other ?? def reconcile_zones(self, other): if other is None: other = Geo_reference() if (self.zone == other.zone or self.zone == DEFAULT_ZONE and other.zone == DEFAULT_ZONE): pass elif self.zone == DEFAULT_ZONE: self.zone = other.zone elif other.zone == DEFAULT_ZONE: other.zone = self.zone else: msg = ('Geospatial data must be in the same ' 'ZONE to allow reconciliation. I got zone %d and %d' % (self.zone, other.zone)) raise ValueError(msg) #def easting_northing2geo_reffed_point(self, x, y): # return [x-self.xllcorner, y - self.xllcorner] #def easting_northing2geo_reffed_points(self, x, y): # return [x-self.xllcorner, y - self.xllcorner] ## # @brief Get origin of this geo_reference. # @return (zone, xllcorner, yllcorner). def get_origin(self): return (self.zone, self.xllcorner, self.yllcorner) ## # @brief Get a string representation of this geo_reference instance. def __repr__(self): return ('(zone=%i easting=%f, northing=%f)' % (self.zone, self.xllcorner, self.yllcorner)) ## # @brief Compare two geo_reference instances. # @param self This geo_reference instance. # @param other Another geo_reference instance to compare against. # @return 0 if instances have the same attributes, else 1. # @note Attributes are: zone, xllcorner, yllcorner. def __cmp__(self, other): # FIXME (DSG) add a tolerance if other is None: return 1 cmp = 0 if not (self.xllcorner == self.xllcorner): cmp = 1 if not (self.yllcorner == self.yllcorner): cmp = 1 if not (self.zone == self.zone): cmp = 1 return cmp
class Geo_reference: ''' Attributes of the Geo_reference class: .zone The UTM zone (default is -1) .false_easting ?? .false_northing ?? .datum The Datum used (default is wgs84) .projection The projection used (default is 'UTM') .units The units of measure used (default metres) .xllcorner The X coord of origin (default is 0.0 wrt UTM grid) .yllcorner The y coord of origin (default is 0.0 wrt UTM grid) .is_absolute ?? ''' def __init__(self, zone=DEFAULT_ZONE, xllcorner=0.0, yllcorner=0.0, datum=DEFAULT_DATUM, projection=DEFAULT_PROJECTION, units=DEFAULT_UNITS, false_easting=DEFAULT_FALSE_EASTING, false_northing=DEFAULT_FALSE_NORTHING, NetCDFObject=None, ASCIIFile=None, read_title=None): ''' input: NetCDFObject - a handle to the netCDF file to be written to ASCIIFile - a handle to the text file read_title - the title of the georeference text, if it was read in. If the function that calls this has already read the title line, it can't unread it, so this info has to be passed. If you know of a way to unread this info, then tell us. Note, the text file only saves a sub set of the info the points file does. Currently the info not written in text must be the default info, since ANUGA assumes it isn't changing. ''' pass def get_xllcorner(self): pass def get_yllcorner(self): pass def get_zone(self): pass def write_NetCDF(self, outfile): pass def read_NetCDF(self, infile): pass def write_ASCII(self, fd): pass def read_ASCII(self, fd, read_title=None): pass def change_points_geo_ref(self, points, points_geo_ref=None): '''Change the geo reference of a list or numeric array of points to be this reference.(The reference used for this object) If the points do not have a geo ref, assume 'absolute' values ''' pass def is_absolute(self): '''Return True if xllcorner==yllcorner==0 indicating that points in question are absolute. ''' pass def get_absolute(self, points): '''Given a set of points geo referenced to this instance, return the points as absolute values. ''' pass def get_relative(self, points): '''Given a set of points in absolute UTM coordinates, make them relative to this geo_reference instance, return the points as relative values. This is the inverse of get_absolute. ''' pass def reconcile_zones(self, other): pass def get_origin(self): pass def __repr__(self): pass def __cmp__(self, other): pass
17
6
19
3
13
4
3
0.65
0
7
0
0
16
9
16
16
395
66
202
47
173
131
178
36
160
7
0
2
54
6,990
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/mavproxy.py
MAVProxy.mavproxy.MPStatus
class MPStatus(object): '''hold status information about the mavproxy''' def __init__(self): self.gps = None self.msgs = {} self.msg_count = {} self.counters = {'MasterIn' : [], 'MasterOut' : 0, 'FGearIn' : 0, 'FGearOut' : 0, 'Slave' : 0} self.bytecounters = {'MasterIn': []} self.setup_mode = opts.setup self.mav_error = 0 self.altitude = 0 self.last_distance_announce = 0.0 self.exit = False self.flightmode = 'MAV' self.last_mode_announce = 0 self.last_mode_announced = 'MAV' self.logdir = None self.last_heartbeat = 0 self.last_message = 0 self.heartbeat_error = False self.last_apm_msg = None self.last_apm_msg_time = 0 self.statustexts_by_sysidcompid = {} self.highest_msec = {} self.have_gps_lock = False self.lost_gps_lock = False self.last_gps_lock = 0 self.watch = None self.watch_verbose = False self.last_streamrate1 = -1 self.last_streamrate2 = -1 self.last_seq = 0 self.armed = False self.last_bytecounter_calc = 0 class ByteCounter(object): def __init__(self): self.total_count = 0 self.current_count = 0 self.buckets = [] self.max_buckets = 10 # 10 seconds def update(self, bytecount): self.total_count += bytecount self.current_count += bytecount def rotate(self): '''move current count into a bucket, zero count''' # huge assumption made that we're called rapidly enough to # not need to rotate multiple buckets. self.buckets.append(self.current_count) self.current_count = 0 if len(self.buckets) > self.max_buckets: self.buckets = self.buckets[-self.max_buckets:] def rate(self): if len(self.buckets) == 0: return 0 total = 0 for bucket in self.buckets: total += bucket return total/float(len(self.buckets)) def total(self): return self.total_count def update_bytecounters(self): '''rotate bytecounter buckets if required''' now = time.time() time_delta = now - self.last_bytecounter_calc if time_delta < 1: return self.last_bytecounter_calc = now for counter in self.bytecounters['MasterIn']: counter.rotate() def show(self, f, pattern=None, verbose=False): '''write status to status.txt''' if pattern is None: f.write('Counters: ') for c in self.counters: f.write('%s:%s ' % (c, self.counters[c])) f.write('\n') f.write('MAV Errors: %u\n' % self.mav_error) f.write(str(self.gps)+'\n') for m in sorted(self.msgs.keys()): if pattern is not None: if not fnmatch.fnmatch(str(m).upper(), pattern.upper()): continue if getattr(self.msgs[m], '_instance_field', None) is not None and m.find('[') == -1 and pattern.find('*') != -1: # noqa:E501 # only show instance versions for patterns continue msg = None sysid = mpstate.settings.target_system for mav in mpstate.mav_master: if sysid not in mav.sysid_state: continue if m not in mav.sysid_state[sysid].messages: continue msg2 = mav.sysid_state[sysid].messages[m] if msg is None or msg2._timestamp > msg._timestamp: msg = msg2 if msg is None: continue if verbose: try: mavutil.dump_message_verbose(f, msg) f.write("\n") except AttributeError as e: if "has no attribute 'dump_message_verbose'" in str(e): print("pymavlink update required for --verbose") else: raise e else: f.write("%u: %s\n" % (self.msg_count[m], str(msg))) def write(self): '''write status to status.txt''' f = open('status.txt', mode='w') self.show(f) f.close()
class MPStatus(object): '''hold status information about the mavproxy''' def __init__(self): pass class ByteCounter(object): def __init__(self): pass def update(self, bytecount): pass def rotate(self): '''move current count into a bucket, zero count''' pass def rate(self): pass def total(self): pass def update_bytecounters(self): '''rotate bytecounter buckets if required''' pass def show(self, f, pattern=None, verbose=False): '''write status to status.txt''' pass def write(self): '''write status to status.txt''' pass
11
5
12
0
11
1
3
0.1
1
2
0
0
4
31
4
4
122
9
105
59
94
10
103
58
92
15
1
4
28
6,991
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/mavproxy.py
MAVProxy.mavproxy.MPState
class MPState(object): '''holds state of mavproxy''' def __init__(self): self.console = textconsole.SimpleConsole() self.command_map = None self.map = None self.map_functions = {} self.click_location = None self.click_time = None self.vehicle_type = None self.vehicle_name = None self.aircraft_dir = None self.logqueue_raw = None self.logqueue = None self.rl = None self.input_queue = None self.input_count = None self.empty_input_count = None from MAVProxy.modules.lib.mp_settings import MPSettings, MPSetting self.settings = MPSettings([ MPSetting('link', int, 1, 'Primary Link', tab='Link', range=(0, 100), increment=1), MPSetting('streamrate', int, 4, 'Stream rate link1', range=(-1, 500), increment=1), MPSetting('streamrate2', int, 4, 'Stream rate link2', range=(-1, 500), increment=1), MPSetting('heartbeat', float, 1, 'Heartbeat rate (Hz)', range=(0, 100), increment=0.1), MPSetting('mavfwd', bool, True, 'Allow forwarded control'), MPSetting('mavfwd_disarmed', bool, True, 'Allow forwarded control when disarmed'), MPSetting('mavfwd_rate', bool, False, 'Allow forwarded rate control'), MPSetting('mavfwd_link', int, -1, 'Forward to a specific link'), MPSetting('shownoise', bool, True, 'Show non-MAVLink data'), MPSetting('baudrate', int, opts.baudrate, 'baudrate for new links', range=(0, 10000000), increment=1), MPSetting('rtscts', bool, opts.rtscts, 'enable flow control'), MPSetting('select_timeout', float, 0.01, 'select timeout'), MPSetting('altreadout', int, 10, 'Altitude Readout', range=(0, 100), increment=1, tab='Announcements'), MPSetting('distreadout', int, 200, 'Distance Readout', range=(0, 10000), increment=1), MPSetting('moddebug', int, opts.moddebug, 'Module Debug Level', range=(0, 4), increment=1, tab='Debug'), MPSetting('script_fatal', bool, False, 'fatal error on bad script', tab='Debug'), MPSetting('compdebug', int, 0, 'Computation Debug Mask', range=(0, 3), tab='Debug'), MPSetting('flushlogs', bool, False, 'Flush logs on every packet'), MPSetting('requireexit', bool, False, 'Require exit command'), MPSetting('wpupdates', bool, True, 'Announce waypoint updates'), MPSetting('wpterrainadjust', bool, True, 'Adjust alt of moved wp using terrain'), MPSetting('wp_use_mission_int', bool, True, 'use MISSION_ITEM_INT messages'), MPSetting('wp_use_waypoint_set_current', bool, False, 'use deprecated WAYPOINT_SET_CURRENT message'), MPSetting('basealt', int, 0, 'Base Altitude', range=(0, 30000), increment=1, tab='Altitude'), MPSetting('wpalt', int, 100, 'Default WP Altitude', range=(0, 10000), increment=1), MPSetting('rallyalt', int, 90, 'Default Rally Altitude', range=(0, 10000), increment=1), MPSetting('terrainalt', str, 'Auto', 'Use terrain altitudes', choice=['Auto', 'True', 'False']), MPSetting('guidedalt', int, 100, 'Default "Fly To" Altitude', range=(0, 10000), increment=1), MPSetting('guided_use_reposition', bool, True, 'Use MAV_CMD_DO_REPOSITION for guided fly-to'), MPSetting('rally_breakalt', int, 40, 'Default Rally Break Altitude', range=(0, 10000), increment=1), MPSetting('rally_flags', int, 0, 'Default Rally Flags', range=(0, 10000), increment=1), MPSetting('source_system', int, 255, 'MAVLink Source system', range=(0, 255), increment=1, tab='MAVLink'), MPSetting('source_component', int, 230, 'MAVLink Source component', range=(0, 255), increment=1), MPSetting('target_system', int, 0, 'MAVLink target system', range=(0, 255), increment=1), MPSetting('target_component', int, 0, 'MAVLink target component', range=(0, 255), increment=1), MPSetting('state_basedir', str, None, 'base directory for logs and aircraft directories'), MPSetting('allow_unsigned', bool, True, 'whether unsigned packets will be accepted'), MPSetting('dist_unit', str, 'm', 'distance unit', choice=['m', 'nm', 'miles'], tab='Units'), MPSetting('height_unit', str, 'm', 'height unit', choice=['m', 'feet']), MPSetting('speed_unit', str, 'm/s', 'height unit', choice=['m/s', 'knots', 'mph']), MPSetting('flytoframe', str, 'AboveHome', 'frame for FlyTo', choice=['AboveHome', 'AGL', 'AMSL']), MPSetting('fwdpos', bool, False, 'Forward GLOBAL_POSITION_INT on all links'), MPSetting('checkdelay', bool, True, 'check for link delay'), MPSetting('param_ftp', bool, True, 'try ftp for parameter download'), MPSetting('param_docs', bool, True, 'show help for parameters'), MPSetting('vehicle_name', str, '', 'Vehicle Name', tab='Vehicle'), MPSetting('sys_status_error_warn_interval', int, 30, 'interval to warn of autopilot software failure'), MPSetting('inhibit_screensaver_when_armed', bool, False, 'inhibit screensaver while vehicle armed'), MPSetting('timeout', int, 5, 'Number of seconds with no packets for a link to considered down', range=(0, 255), increment=1), # noqa ]) self.completions = { "script" : ["(FILENAME)"], "set" : ["(SETTING)"], "status" : ["(VARIABLE)"], "module" : ["list", "load (AVAILMODULES)", "<unload|reload> (LOADEDMODULES)"] } self.status = MPStatus() # master mavlink device self.mav_master = None # mavlink outputs self.mav_outputs = [] self.sysid_outputs = {} # Mapping of all detected sysid's to links # Key is link id, value is all detected sysid's/compid's in that link # Dict of self.vehicle_link_map[linknumber] = set([(sysid1,compid1), (sysid2,compid2), ...]) self.vehicle_link_map = {} # SITL output self.sitl_output = None self.mav_param_by_sysid = {} self.mav_param_by_sysid[(self.settings.target_system, self.settings.target_component)] = mavparm.MAVParmDict() self.modules = [] self.public_modules = {} self.functions = MAVFunctions() self.select_extra = {} self.continue_mode = False self.aliases = {} import platform self.system = platform.system() self.multi_instance = {} self.instance_count = {} self.is_sitl = False self.start_time_s = time.time() self.attitude_time_s = 0 self.position = None @property def mav_param(self): '''map mav_param onto the current target system parameters''' compid = self.settings.target_component if compid == 0: compid = 1 sysid = (self.settings.target_system, compid) if sysid not in self.mav_param_by_sysid: self.mav_param_by_sysid[sysid] = mavparm.MAVParmDict() return self.mav_param_by_sysid[sysid] def module(self, name): '''Find a public module (most modules are private)''' if name in self.public_modules: return self.public_modules[name] return None def load_module(self, modname, quiet=False, **kwargs): '''load a module''' modpaths = ['MAVProxy.modules.mavproxy_%s' % modname, modname] for (m, pm) in mpstate.modules: if m.name == modname and modname not in mpstate.multi_instance: if not quiet: print("module %s already loaded" % modname) # don't report an error return True ex = None for modpath in modpaths: try: m = import_package(modpath) reload(m) module = m.init(mpstate, **kwargs) if isinstance(module, mp_module.MPModule): mpstate.modules.append((module, m)) if not quiet: if kwargs: print("Loaded module %s with kwargs = %s" % (modname, kwargs)) else: print("Loaded module %s" % (modname,)) return True else: ex = "%s.init did not return a MPModule instance" % modname break except ImportError as msg: ex = msg if mpstate.settings.moddebug > 1: print(get_exception_stacktrace(ex)) help_traceback = "" if mpstate.settings.moddebug < 3: help_traceback = " Use 'set moddebug 3' in the MAVProxy console to enable traceback" print("Failed to load module: %s.%s" % (ex, help_traceback)) return False def unload_module(self, modname): '''unload a module''' for (m, pm) in mpstate.modules: if m.name == modname: if hasattr(m, 'unload'): t = threading.Thread(target=lambda : m.unload(), name="unload %s" % modname) t.start() t.join(timeout=5) if t.is_alive(): print("unload on module %s did not complete" % m.name) mpstate.modules.remove((m, pm)) return False mpstate.modules.remove((m, pm)) if modname in mpstate.public_modules: del mpstate.public_modules[modname] print("Unloaded module %s" % modname) return True print("Unable to find module %s" % modname) return False def master(self, target_sysid=-1): '''return the currently chosen mavlink master object''' if len(self.mav_master) == 0: return None if self.settings.link > len(self.mav_master): self.settings.link = 1 if target_sysid != -1: # if we're looking for a specific system ID then try to find best # link for that best_link = None best_timestamp = 0 for m in self.mav_master: try: tstamp = m.sysid_state[target_sysid].messages['HEARTBEAT']._timestamp except Exception: continue if tstamp > best_timestamp: best_link = m best_timestamp = tstamp if best_link is not None: return best_link # try to use one with no link error if not self.mav_master[self.settings.link-1].linkerror: return self.mav_master[self.settings.link-1] for m in self.mav_master: if not m.linkerror: return m return self.mav_master[self.settings.link-1] def foreach_mav(self, sysid, compid, closure): # Send mavlink message only on all links that contain vehicle (sysid, compid) # More efficient than just blasting all links, when sending targetted messages # Also useful for sending messages to non-selected vehicles for linkNumber, vehicleList in self.vehicle_link_map.items(): if (sysid, compid) not in vehicleList: continue closure(self.mav_master[linkNumber].mav) def notify_click(self): notify_mods = ['map', 'misseditor'] for modname in notify_mods: mod = self.module(modname) if mod is not None: mod.click_updated() def click(self, latlng): if latlng is None: self.click_location = None self.click_time = None self.notify_click() return (lat, lng) = latlng if lat is None: print("Bad Lat") return if lng is None: print("Bad lng") return self.click_location = (lat, lng) self.click_time = time.time() self.notify_click()
class MPState(object): '''holds state of mavproxy''' def __init__(self): pass @property def mav_param(self): '''map mav_param onto the current target system parameters''' pass def module(self, name): '''Find a public module (most modules are private)''' pass def load_module(self, modname, quiet=False, **kwargs): '''load a module''' pass def unload_module(self, modname): '''unload a module''' pass def master(self, target_sysid=-1): '''return the currently chosen mavlink master object''' pass def foreach_mav(self, sysid, compid, closure): pass def notify_click(self): pass def click(self, latlng): pass
11
6
28
2
24
2
5
0.09
1
13
6
0
9
37
9
9
262
28
215
70
202
20
154
68
142
11
1
5
44
6,992
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/mavproxy.py
MAVProxy.mavproxy.MAVFunctions
class MAVFunctions(object): '''core functions available in modules''' def __init__(self): self.process_stdin = add_input self.param_set = param_set self.get_mav_param = get_mav_param self.say = say_text # input handler can be overridden by a module self.input_handler = None
class MAVFunctions(object): '''core functions available in modules''' def __init__(self): pass
2
1
7
0
6
1
1
0.29
1
0
0
0
1
5
1
1
9
0
7
7
5
2
7
7
5
1
1
0
1
6,993
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/tools/MAVExplorer.py
MAVExplorer.XLimits
class XLimits(object): '''A class capturing timestamp limits''' def __init__(self): self.last_xlim = None self.xlim_low = None self.xlim_high = None def timestamp_in_range(self, timestamp): '''check if a timestamp is in current limits return -1 if too low return 1 if too high return 0 if in range ''' if self.xlim_low is not None and timestamp < self.xlim_low: return -1 if self.xlim_high is not None and timestamp > self.xlim_high: return 1 return 0
class XLimits(object): '''A class capturing timestamp limits''' def __init__(self): pass def timestamp_in_range(self, timestamp): '''check if a timestamp is in current limits return -1 if too low return 1 if too high return 0 if in range ''' pass
3
2
8
0
5
3
2
0.55
1
0
0
0
2
3
2
2
18
1
11
6
8
6
11
6
8
3
1
1
4
6,994
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/lib/MacOS/backend_wx.py
MAVProxy.modules.lib.MacOS.backend_wx.NavigationToolbarWx
class NavigationToolbarWx(wx.ToolBar): def __init__(self, canvas, can_kill=False): wx.ToolBar.__init__(self, canvas.GetParent(), -1) DEBUG_MSG("__init__()", 1, self) self.canvas = canvas self._lastControl = None self._mouseOnButton = None self._parent = canvas.GetParent() self._NTB_BUTTON_HANDLER = { _NTB_X_PAN_LEFT : self.panx, _NTB_X_PAN_RIGHT : self.panx, _NTB_X_ZOOMIN : self.zoomx, _NTB_X_ZOOMOUT : self.zoomy, _NTB_Y_PAN_UP : self.pany, _NTB_Y_PAN_DOWN : self.pany, _NTB_Y_ZOOMIN : self.zoomy, _NTB_Y_ZOOMOUT : self.zoomy } self._create_menu() self._create_controls(can_kill) self.Realize() def _create_menu(self): """ Creates the 'menu' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control """ DEBUG_MSG("_create_menu()", 1, self) self._menu = MenuButtonWx(self) self.AddControl(self._menu) self.AddSeparator() def _create_controls(self, can_kill): """ Creates the button controls, and links them to event handlers """ DEBUG_MSG("_create_controls()", 1, self) # Need the following line as Windows toolbars default to 15x16 self.SetToolBitmapSize(wx.Size(16,16)) self.AddSimpleTool(_NTB_X_PAN_LEFT, _load_bitmap('stock_left.xpm'), 'Left', 'Scroll left') self.AddSimpleTool(_NTB_X_PAN_RIGHT, _load_bitmap('stock_right.xpm'), 'Right', 'Scroll right') self.AddSimpleTool(_NTB_X_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase X axis magnification') self.AddSimpleTool(_NTB_X_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease X axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_Y_PAN_UP,_load_bitmap('stock_up.xpm'), 'Up', 'Scroll up') self.AddSimpleTool(_NTB_Y_PAN_DOWN, _load_bitmap('stock_down.xpm'), 'Down', 'Scroll down') self.AddSimpleTool(_NTB_Y_ZOOMIN, _load_bitmap('stock_zoom-in.xpm'), 'Zoom in', 'Increase Y axis magnification') self.AddSimpleTool(_NTB_Y_ZOOMOUT, _load_bitmap('stock_zoom-out.xpm'), 'Zoom out', 'Decrease Y axis magnification') self.AddSeparator() self.AddSimpleTool(_NTB_SAVE, _load_bitmap('stock_save_as.xpm'), 'Save', 'Save plot contents as images') self.AddSeparator() bind(self, wx.EVT_TOOL, self._onLeftScroll, id=_NTB_X_PAN_LEFT) bind(self, wx.EVT_TOOL, self._onRightScroll, id=_NTB_X_PAN_RIGHT) bind(self, wx.EVT_TOOL, self._onXZoomIn, id=_NTB_X_ZOOMIN) bind(self, wx.EVT_TOOL, self._onXZoomOut, id=_NTB_X_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onUpScroll, id=_NTB_Y_PAN_UP) bind(self, wx.EVT_TOOL, self._onDownScroll, id=_NTB_Y_PAN_DOWN) bind(self, wx.EVT_TOOL, self._onYZoomIn, id=_NTB_Y_ZOOMIN) bind(self, wx.EVT_TOOL, self._onYZoomOut, id=_NTB_Y_ZOOMOUT) bind(self, wx.EVT_TOOL, self._onSave, id=_NTB_SAVE) bind(self, wx.EVT_TOOL_ENTER, self._onEnterTool, id=self.GetId()) if can_kill: bind(self, wx.EVT_TOOL, self._onClose, id=_NTB_CLOSE) bind(self, wx.EVT_MOUSEWHEEL, self._onMouseWheel) def set_active(self, ind): """ ind is a list of index numbers for the axes which are to be made active """ DEBUG_MSG("set_active()", 1, self) self._ind = ind if ind != None: self._active = [ self._axes[i] for i in self._ind ] else: self._active = [] # Now update button text wit active axes self._menu.updateButtonText(ind) def get_last_control(self): """Returns the identity of the last toolbar button pressed.""" return self._lastControl def panx(self, direction): DEBUG_MSG("panx()", 1, self) for a in self._active: a.xaxis.pan(direction) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def pany(self, direction): DEBUG_MSG("pany()", 1, self) for a in self._active: a.yaxis.pan(direction) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def zoomx(self, in_out): DEBUG_MSG("zoomx()", 1, self) for a in self._active: a.xaxis.zoom(in_out) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def zoomy(self, in_out): DEBUG_MSG("zoomy()", 1, self) for a in self._active: a.yaxis.zoom(in_out) self.canvas.draw() self.canvas.Refresh(eraseBackground=False) def update(self): """ Update the toolbar menu - e.g., called when a new subplot or axes are added """ DEBUG_MSG("update()", 1, self) self._axes = self.canvas.figure.get_axes() self._menu.updateAxes(len(self._axes)) def _do_nothing(self, d): """A NULL event handler - does nothing whatsoever""" pass # Local event handlers - mainly supply parameters to pan/scroll functions def _onEnterTool(self, evt): toolId = evt.GetSelection() try: self.button_fn = self._NTB_BUTTON_HANDLER[toolId] except KeyError: self.button_fn = self._do_nothing evt.Skip() def _onLeftScroll(self, evt): self.panx(-1) evt.Skip() def _onRightScroll(self, evt): self.panx(1) evt.Skip() def _onXZoomIn(self, evt): self.zoomx(1) evt.Skip() def _onXZoomOut(self, evt): self.zoomx(-1) evt.Skip() def _onUpScroll(self, evt): self.pany(1) evt.Skip() def _onDownScroll(self, evt): self.pany(-1) evt.Skip() def _onYZoomIn(self, evt): self.zoomy(1) evt.Skip() def _onYZoomOut(self, evt): self.zoomy(-1) evt.Skip() def _onMouseEnterButton(self, button): self._mouseOnButton = button def _onMouseLeaveButton(self, button): if self._mouseOnButton == button: self._mouseOnButton = None def _onMouseWheel(self, evt): if evt.GetWheelRotation() > 0: direction = 1 else: direction = -1 self.button_fn(direction) _onSave = NavigationToolbar2Wx.save_figure def _onClose(self, evt): self.GetParent().Destroy()
class NavigationToolbarWx(wx.ToolBar): def __init__(self, canvas, can_kill=False): pass def _create_menu(self): ''' Creates the 'menu' - implemented as a button which opens a pop-up menu since wxPython does not allow a menu as a control ''' pass def _create_controls(self, can_kill): ''' Creates the button controls, and links them to event handlers ''' pass def set_active(self, ind): ''' ind is a list of index numbers for the axes which are to be made active ''' pass def get_last_control(self): '''Returns the identity of the last toolbar button pressed.''' pass def panx(self, direction): pass def pany(self, direction): pass def zoomx(self, in_out): pass def zoomy(self, in_out): pass def update(self): ''' Update the toolbar menu - e.g., called when a new subplot or axes are added ''' pass def _do_nothing(self, d): '''A NULL event handler - does nothing whatsoever''' pass def _onEnterTool(self, evt): pass def _onLeftScroll(self, evt): pass def _onRightScroll(self, evt): pass def _onXZoomIn(self, evt): pass def _onXZoomOut(self, evt): pass def _onUpScroll(self, evt): pass def _onDownScroll(self, evt): pass def _onYZoomIn(self, evt): pass def _onYZoomOut(self, evt): pass def _onMouseEnterButton(self, button): pass def _onMouseLeaveButton(self, button): pass def _onMouseWheel(self, evt): pass def _onClose(self, evt): pass
25
6
7
0
6
1
1
0.13
1
2
1
0
24
10
24
24
196
30
147
42
122
19
128
42
103
2
1
1
33
6,995
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/tools/MAVExplorer.py
MAVExplorer.MEStatus
class MEStatus(object): '''status object to conform with mavproxy structure for modules''' def __init__(self): self.msgs = {}
class MEStatus(object): '''status object to conform with mavproxy structure for modules''' def __init__(self): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
1
1
1
4
0
3
3
1
1
3
3
1
1
1
0
1
6,996
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
MAVProxy.modules.mavproxy_magical.magical_ui.MagicalFrame
class MagicalFrame(wx.Frame): initial_instruction = 'To start calibration, please place your vehicle as the image shows and press start.' countdown_instruction = 'Get ready!' calibration_instructions = ( 'Rotate the vehicle in as many different ways as possible.', 'Some rotations can be repeated from different initial positions.', 'You can take the rotations above as a reference.', 'The image on the right is a visual feedback of the calibration progress.', 'Don\'t worry about the rotation direction (clockwise or counterclockwise), both work.', ) ref_rotations_script = () for yaw in (0, math.pi / 2): ref_rotations_script += ( ('.SetEuler', 0, 0, yaw), ('.SetAngvel', (1, 0, 0), math.pi / 2), ('wait', 4), ('.SetEuler', 0, 0, yaw), ('.SetAngvel', (0, 1, 0), math.pi / 2), ('wait', 4), ('.SetEuler', 0, 0, yaw), ('.SetAngvel', (1, 1, 0), math.pi / 2), ('wait', 4), ('.SetEuler', 0, 0, yaw), ('.SetAngvel', (1, -1, 0), math.pi / 2), ('wait', 4), ) for (roll, pitch, yaw), rotation_axis in ( ((0, 0, 0), 2), ((math.pi, 0, 0), 2), ((-math.pi / 2, 0, 0), 1), ((math.pi / 2, 0, 0), 1), ((0, -math.pi / 2, 0), 0), ((0, math.pi / 2, 0), 0), ): axis = [0, 0, 0] axis[rotation_axis] = 1 ref_rotations_script += ( ('.SetEuler', roll, pitch, yaw), ('.SetAngvel', axis, math.pi / 2), ('wait', 4), ) ref_rotations_script += (('restart',),) def __init__(self, conn): super(MagicalFrame, self).__init__(None, title='Magical') self.state = None self.grid = None self.conn = conn self.button_state = None self.ui_is_active = False self.countdown = 0 self.calibration_instruction_idx = 0 self.InitUI() self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) self.timer.Start(60) self.loader_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnLoaderTimer, self.loader_timer) self.loader_timer.Start(50) self.countdown_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnCountdownTimer, self.countdown_timer) self.calibration_instructions_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnCalibrationInstructionsTimer, self.calibration_instructions_timer) self.SetState('idle') self.main_panel.GetSizer().Fit(self) path = os.path.join(magical.datapath, 'quadcopter.obj') self.vehicle_loader = wv.ParserWorker( wv.ObjParser(filename=path), complete_callback=self.VehicleLoadCompleteCallback, ) self.vehicle_loader.start() def VehicleLoadCompleteCallback(self): wx.CallAfter(self.VehicleLoadComplete) def VehicleLoadComplete(self): self.grid.SetVehicleWavefront(self.vehicle_loader.obj) self.ref_vehicle.SetVehicleWavefront(self.vehicle_loader.obj) self.vehicle_loader = None self.loader_timer.Stop() self.HideLoadProgress() def InitUI(self): font = self.GetFont() font.SetFamily(wx.FONTFAMILY_SWISS) self.SetFont(font) self.main_panel = wx.ScrolledWindow(self) self.main_panel.SetScrollbars(1, 1, 1, 1) self.main_panel.SetBackgroundColour(DARK_BACKGROUND) sizer = wx.BoxSizer(wx.VERTICAL) self.main_panel.SetSizer(sizer) kw = dict(border=32, flag=wx.EXPAND | wx.LEFT | wx.RIGHT) sizer.AddSpacer(16) sizer.Add(self.Header(self.main_panel), **kw) sizer.AddSpacer(23) sizer.Add(self.Body(self.main_panel), proportion=1, **kw) sizer.AddSpacer(23) sizer.Add(self.Footer(self.main_panel), **kw) sizer.AddSpacer(23) def Header(self, parent): header = Panel(parent) header.SetBackgroundColour(LIGHT_BACKGROUND) sizer = wx.BoxSizer(wx.VERTICAL) header.SetSizer(sizer) font = header.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) text = wx.StaticText(header) text.SetLabel('Compass Calibration') text.SetForegroundColour(PRIMARY_HIGHLIGHT) font.SetPointSize(26) text.SetFont(font) sizer.Add(text, border=16, flag=wx.ALL & ~wx.BOTTOM) text = wx.StaticText(header) text.SetLabel('Follow the procedure to calibrate your compass') font.SetPointSize(14) text.SetFont(font) sizer.Add(text, border=16, flag=wx.ALL & ~wx.TOP) return header def Body(self, parent): body = wx.BoxSizer(wx.HORIZONTAL) body.Add(self.InstructionsPanel(parent), proportion=2, flag=wx.EXPAND) body.AddSpacer(23) self.progress_panel = self.ProgressPanel(parent) body.Add(self.progress_panel, proportion=1, flag=wx.EXPAND) return body def InstructionsPanel(self, parent): panel = Panel(parent) panel.SetBackgroundColour(LIGHT_BACKGROUND) self.ref_vehicle = Vehicle(panel) self.ref_vehicle.SetMinSize((430, 430)) self.countdown_window = CountdownText(panel) self.countdown_window.SetMinSize((430, 430)) self.countdown_window.SetBorderColor(SECONDARY_HIGHLIGHT) self.countdown_window.SetForegroundColour(PRIMARY_HIGHLIGHT) font = self.countdown_window.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) self.countdown_window.SetFont(font) self.instruction = InstructionText(panel) self.instruction.SetMinLines(3) font = self.instruction.GetFont() font.SetPointSize(26) self.instruction.SetFont(font) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) sizer.AddStretchSpacer() sizer.Add(self.ref_vehicle, flag=wx.ALIGN_CENTER) sizer.Add(self.countdown_window, flag=wx.ALIGN_CENTER) sizer.AddStretchSpacer() sizer.Add(self.instruction, border=10, flag=wx.ALL | wx.EXPAND) sizer.AddStretchSpacer() sizer.Hide(self.countdown_window) return panel def ProgressPanel(self, parent): panel = Panel(parent) panel.SetBackgroundColour(LIGHT_BACKGROUND) self.progress = wx.StaticText(panel, label='0%') font = self.progress.GetFont() font.SetPointSize(70) font.SetWeight(wx.FONTWEIGHT_BOLD) self.progress.SetFont(font) self.grid = GeodesicGrid(panel) self.grid.SetMinSize((365, 365)) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) sizer.AddStretchSpacer() sizer.Add(self.grid, flag=wx.ALIGN_CENTER) sizer.AddStretchSpacer() sizer.AddSpacer(16) sizer.Add(self.progress, flag=wx.ALIGN_CENTER) sizer.AddStretchSpacer() return panel def Footer(self, parent): footer = wx.BoxSizer(wx.HORIZONTAL) self.button = button = Button(parent, size=(180, -1)) button.SetPadding((0, 16)) button.SetBackgroundColour(LIGHT_BACKGROUND) button.SetBorderRadius(10) button.SetBorderWidth(2) font = button.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) font.SetPointSize(20) button.SetFont(font) self.Bind(wx.EVT_BUTTON, self.OnButton, button) footer.Add(self.LoaderProgress(parent), proportion=1, flag=wx.EXPAND) footer.Add(button) return footer def LoaderProgress(self, parent): panel = wx.Panel(parent) panel.SetBackgroundColour(parent.GetBackgroundColour()) font = panel.GetFont() font.MakeItalic() panel.SetFont(font) self.load_progress = wx.Gauge(panel, size=(-1, 10)) self.load_progress_last_time = time.time() self.load_text = wx.StaticText(panel) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) sizer.Add(self.load_progress, border=10, flag=wx.EXPAND | wx.LEFT | wx.RIGHT) sizer.Add(self.load_text, border=10, flag=wx.LEFT | wx.RIGHT) return panel def UpdateLoaderProgress(self, text, value, range): if value == -1: t = time.time() if t - self.load_progress_last_time > .001: self.load_progress.Pulse() self.load_progress_last_time = t else: self.load_progress.SetRange(range) self.load_progress.SetValue(value) if text != self.load_text.GetLabel(): self.load_text.SetLabel(text) self.ShowLoadProgress() def ShowLoadProgress(self): sizer = self.load_progress.GetContainingSizer() sizer.Show(self.load_progress) sizer.Show(self.load_text) def HideLoadProgress(self): sizer = self.load_progress.GetContainingSizer() sizer.Hide(self.load_progress) sizer.Hide(self.load_text) def SetState(self, state): if self.state == state: return if self.state == 'countdown': self.countdown = 0 self.countdown_timer.Stop() self.countdown_window.SetValue(self.countdown) sizer = self.countdown_window.GetContainingSizer() sizer.Show(self.ref_vehicle) sizer.Hide(self.countdown_window) sizer.Layout() elif self.state == 'running': self.calibration_instructions_timer.Stop() self.ref_vehicle.StopScript() self.ref_vehicle.SetEuler(0, 0, 0) if state == 'idle': self.SetInstructionText(self.initial_instruction) self.SetButtonState('start') elif state == 'countdown': self.countdown = 5 self.countdown_window.SetValue(self.countdown) self.SetInstructionText(self.countdown_instruction) self.countdown_timer.Start(1000) self.SetButtonState('cancel') sizer = self.countdown_window.GetContainingSizer() sizer.Show(self.countdown_window) sizer.Hide(self.ref_vehicle) sizer.Layout() elif state == 'start': self.conn.send('start') elif state == 'running': self.calibration_instruction_idx = 0 self.SetInstructionText(self.calibration_instructions[0]) self.calibration_instructions_timer.Start(5000) self.SetButtonState('cancel') self.ref_vehicle.RunScript(self.ref_rotations_script) elif state == 'cancel': self.conn.send('cancel') if self.state == 'countdown': self.SetState('idle') self.state = state def OnButton(self, evt): if self.button_state == 'start': self.SetState('countdown') elif self.button_state == 'cancel': self.SetState('cancel') def SetInstructionText(self, text): self.instruction.SetText(text) self.instruction.GetContainingSizer().Layout() def OnCountdownTimer(self, evt): self.countdown -= 1 self.countdown_window.SetValue(self.countdown) if not self.countdown: self.SetState('start') def OnLoaderTimer(self, evt): if self.vehicle_loader and self.vehicle_loader.is_alive(): i, num_lines = self.vehicle_loader.get_progress() self.UpdateLoaderProgress('Loading 3D vehicle object...', i, num_lines) def OnTimer(self, evt): close_requested = False while self.conn.poll(): msg = self.conn.recv() if msg['name'] == 'ui_is_active': self.ui_is_active = msg['value'] elif msg['name'] == 'close': close_requested = True elif msg['name'] == 'running': if msg['value']: self.SetState('running') else: if self.state != 'countdown': self.SetState('idle') elif msg['name'] == 'progress_update': self.UpdateProgress(msg['pct'], msg['sections']) elif msg['name'] == 'report': self.Report(msg['messages'], self.ui_is_active) elif msg['name'] == 'attitude': self.grid.SetAttitude(msg['roll'], msg['pitch'], msg['yaw'], msg['timestamp']) elif msg['name'] == 'mag': self.grid.SetMag(msg['x'], msg['y'], msg['z']) if close_requested: self.timer.Stop() self.Destroy() def OnCalibrationInstructionsTimer(self, evt): self.calibration_instruction_idx += 1 self.calibration_instruction_idx %= len(self.calibration_instructions) text = self.calibration_instructions[self.calibration_instruction_idx] self.SetInstructionText(text) def UpdateProgress(self, pct, sections): self.progress.SetLabel("%d%%" % pct) self.progress.GetContainingSizer().Layout() if self.grid: self.grid.UpdateVisibleSections(sections) def SetButtonState(self, state): if state == self.button_state: return if state == 'start': self.button.SetLabel('START') self.button.SetForegroundColour(PRIMARY_HIGHLIGHT) self.button.SetBorderColor(PRIMARY_HIGHLIGHT) elif state == 'cancel': self.button.SetLabel('CANCEL') self.button.SetBorderColor(COMMON_FOREGROUND) self.button.SetForegroundColour(COMMON_FOREGROUND) self.button_state = state self.button.Refresh() def Report(self, mavlink_messages, popup): self.SetState('idle') for m in mavlink_messages: if m.cal_status != mavlink.MAG_CAL_SUCCESS: break else: self.UpdateProgress(100, [True] * 80) if popup: p = ReportDialog(self, mavlink_messages) r = p.ShowModal() if r == wx.ID_REDO: self.SetState('countdown')
class MagicalFrame(wx.Frame): def __init__(self, conn): pass def VehicleLoadCompleteCallback(self): pass def VehicleLoadCompleteCallback(self): pass def InitUI(self): pass def Header(self, parent): pass def Body(self, parent): pass def InstructionsPanel(self, parent): pass def ProgressPanel(self, parent): pass def Footer(self, parent): pass def LoaderProgress(self, parent): pass def UpdateLoaderProgress(self, text, value, range): pass def ShowLoadProgress(self): pass def HideLoadProgress(self): pass def SetState(self, state): pass def OnButton(self, evt): pass def SetInstructionText(self, text): pass def OnCountdownTimer(self, evt): pass def OnLoaderTimer(self, evt): pass def OnTimer(self, evt): pass def OnCalibrationInstructionsTimer(self, evt): pass def UpdateProgress(self, pct, sections): pass def SetButtonState(self, state): pass def Report(self, mavlink_messages, popup): pass
24
0
15
2
13
0
3
0
1
11
9
0
23
22
23
23
415
80
335
84
311
0
286
84
262
12
1
4
58
6,997
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
MAVProxy.modules.mavproxy_magical.magical_ui.Panel
class Panel(wx.Panel): def __init__(self, *k, **kw): super(Panel, self).__init__(*k, **kw) self.SetForegroundColour(COMMON_FOREGROUND)
class Panel(wx.Panel): def __init__(self, *k, **kw): pass
2
0
3
0
3
0
1
0
1
1
0
1
1
0
1
1
4
0
4
2
2
0
4
2
2
1
1
0
1
6,998
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/magical_ui.py
MAVProxy.modules.mavproxy_magical.magical_ui.ReportDialog
class ReportDialog(wx.Dialog): light_background = wx.Colour() light_background.SetFromString(LIGHT_BACKGROUND) light_background = scale_color(light_background, 1.2) class StatusIcon(wx.PyWindow): success_color = '#00ed00' failure_color = '#d81313' def __init__(self, *k, **kw): super(ReportDialog.StatusIcon, self).__init__(*k, **kw) self.success = True self.Bind(wx.EVT_PAINT, self.OnPaint) def Success(self, success): self.success = success self.Refresh() def OnPaint(self, evt): dc = wx.BufferedPaintDC(self) self.Draw(dc) def Draw(self, dc): width, height = self.GetClientSize() if not width or not height: return gcdc = wx.GCDC(dc) gcdc.SetPen(wx.NullPen) bg = self.GetParent().GetBackgroundColour() gcdc.SetBackground(wx.Brush(bg, wx.SOLID)) gcdc.Clear() color = self.success_color if self.success else self.failure_color gcdc.SetBrush(wx.Brush(color)) x = width / 2 y = height / 2 gcdc.DrawCircle(x, y, min(x, y)) class CompassPanel(Panel): def __init__(self, parent, m, *k, **kw): super(ReportDialog.CompassPanel, self).__init__(parent, *k, **kw) self.InitUI() self.compass_text.SetLabel('Compass %d' % m.compass_id) if m.cal_status == mavlink.MAG_CAL_SUCCESS: self.status_icon.Success(True) self.status_text.SetLabel('SUCCESS') else: self.status_icon.Success(False) self.status_text.SetLabel('FAILURE') self.fitness_value_text.SetLabel('%.3f' % m.fitness) texts = ( self.offsets_texts, self.diagonals_texts, self.offdiagonals_texts, ) params = ( (m.ofs_x, m.ofs_y, m.ofs_z), (m.diag_x, m.diag_y, m.diag_z), (m.offdiag_x, m.offdiag_y, m.offdiag_z), ) for targets, values in zip(texts, params): for target, value in zip(targets, values): target.SetLabel('%.2f' % value) def InitUI(self): color = wx.Colour() color.SetFromString(LIGHT_BACKGROUND) self.SetBackgroundColour(scale_color(color, 0.95)) font = self.GetFont() font.SetWeight(wx.FONTWEIGHT_BOLD) font.SetPointSize(24) self.SetFont(font) self.SetMinSize((400, -1)) self.compass_text = wx.StaticText(self) self.fitness_value_text = wx.StaticText(self) font.SetWeight(wx.FONTWEIGHT_NORMAL) self.fitness_value_text.SetFont(font) self.parameters_sizer = self.CalibrationParameters() fitness_sizer = wx.BoxSizer(wx.HORIZONTAL) text = wx.StaticText(self, label='Fitness') text.SetFont(self.fitness_value_text.GetFont()) fitness_sizer.Add(text, proportion=1, flag=wx.EXPAND) fitness_sizer.Add(self.fitness_value_text) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) sizer.AddSpacer(16) sizer.Add(self.compass_text, border=16, flag=wx.LEFT | wx.RIGHT) sizer.AddSpacer(16) sizer.Add(self.StatusPanel(), flag=wx.EXPAND) sizer.AddSpacer(16) sizer.Add(fitness_sizer, border=16, flag=wx.LEFT | wx.RIGHT | wx.EXPAND) sizer.AddSpacer(16) sizer.Add(self.parameters_sizer, border=16, flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND) sizer.Hide(self.parameters_sizer) def StatusPanel(self): panel = Panel(self) panel.SetBackgroundColour(ReportDialog.light_background) self.status_icon = ReportDialog.StatusIcon(panel, size=(44, 44)) self.status_text = wx.StaticText(panel) sizer = wx.BoxSizer(wx.HORIZONTAL) panel.SetSizer(sizer) sizer.AddSpacer(16) sizer.Add(self.status_icon, border=5, flag=wx.TOP | wx.BOTTOM) sizer.AddSpacer(16) sizer.Add(self.status_text, flag=wx.ALIGN_CENTER) sizer.AddSpacer(16) return panel def CalibrationParameters(self): self.offsets_texts = tuple(wx.StaticText(self) for _ in range(3)) self.diagonals_texts = tuple(wx.StaticText(self) for _ in range(3)) self.offdiagonals_texts = tuple(wx.StaticText(self) for _ in range(3)) table = ( ('Offsets', self.offsets_texts), ('Diagonals', self.diagonals_texts), ('Off-diagonals', self.offdiagonals_texts), ) sizer = wx.FlexGridSizer(len(table) + 1, 4, 4, 10) sizer.AddGrowableCol(0) font = self.GetFont() font.SetPointSize(14) font.MakeItalic() text = wx.StaticText(self, label='Parameter') text.SetFont(font) sizer.Add(text) for label in ('X', 'Y', 'Z'): text = wx.StaticText(self, label=label) text.SetFont(font) sizer.Add(text, flag=wx.ALIGN_CENTER) font.SetWeight(wx.FONTWEIGHT_NORMAL) for label, (x, y, z) in table: text = wx.StaticText(self) text.SetLabel(label) text.SetFont(font) x.SetFont(font) y.SetFont(font) z.SetFont(font) sizer.Add(text) sizer.Add(x, flag=wx.ALIGN_RIGHT) sizer.Add(y, flag=wx.ALIGN_RIGHT) sizer.Add(z, flag=wx.ALIGN_RIGHT) return sizer def ShowCompassParameters(self, show): sizer = self.GetSizer() if show: sizer.Show(self.parameters_sizer) else: sizer.Hide(self.parameters_sizer) def __init__(self, parent, mavlink_messages, *k, **kw): super(ReportDialog, self).__init__(parent, *k, **kw) self.compass_parameters_shown = False self.mavlink_messages = mavlink_messages for m in self.mavlink_messages: if m.cal_status != mavlink.MAG_CAL_SUCCESS: self.success = False break else: self.success = True self.InitUI() def InitUI(self): color = wx.Colour() color.SetFromString(DARK_BACKGROUND) self.SetBackgroundColour(scale_color(color, .9)) cols = 2 if len(self.mavlink_messages) > 1 else 1 compass_sizer = wx.GridSizer(0, cols, 2, 2) self.compass_panels = [] for m in self.mavlink_messages: p = self.CompassPanel(self, m) compass_sizer.Add(p) self.compass_panels.append(p) sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) sizer.Add(compass_sizer) sizer.Add(self.Footer(), flag=wx.EXPAND) sizer.Fit(self) def Footer(self): footer = Panel(self) footer.SetBackgroundColour(ReportDialog.light_background) font = footer.GetFont() font.SetPointSize(16) font.SetWeight(wx.FONTWEIGHT_BOLD) footer.SetFont(font) self.show_more_button = Button(footer) self.show_more_button.SetLabel('Show more') self.show_more_button.SetBackgroundColour(wx.TransparentColour) self.Bind(wx.EVT_BUTTON, self.OnShowMoreButton, self.show_more_button) if not self.success: self.try_again_button = Button(footer, wx.ID_REDO) self.try_again_button.SetLabel('TRY AGAIN') self.try_again_button.SetBackgroundColour(wx.TransparentColour) self.try_again_button.SetForegroundColour(PRIMARY_HIGHLIGHT) self.Bind(wx.EVT_BUTTON, self.OnActionButton, self.try_again_button) self.close_button = Button(footer, wx.ID_CLOSE) self.close_button.SetLabel('CLOSE') self.close_button.SetBackgroundColour(wx.TransparentColour) self.close_button.SetForegroundColour(PRIMARY_HIGHLIGHT) self.Bind(wx.EVT_BUTTON, self.OnActionButton, self.close_button) sizer = wx.BoxSizer(wx.HORIZONTAL) footer.SetSizer(sizer) sizer.AddSpacer(16) sizer.Add(self.show_more_button) sizer.AddStretchSpacer() if not self.success: sizer.Add(self.try_again_button) sizer.AddSpacer(32) sizer.Add(self.close_button) sizer.AddSpacer(16) return footer def OnActionButton(self, evt): r = evt.GetEventObject().GetId() if self.IsModal(): self.EndModal(r) else: self.SetReturnCode(r) self.Show(False) def OnShowMoreButton(self, evt): self.compass_parameters_shown = not self.compass_parameters_shown for p in self.compass_panels: p.ShowCompassParameters(self.compass_parameters_shown) if self.compass_parameters_shown: self.show_more_button.SetLabel('Show less') else: self.show_more_button.SetLabel('Show more') self.GetSizer().Fit(self)
class ReportDialog(wx.Dialog): class StatusIcon(wx.PyWindow): def __init__(self, *k, **kw): pass def Success(self, success): pass def OnPaint(self, evt): pass def Draw(self, dc): pass class CompassPanel(Panel): def __init__(self, *k, **kw): pass def InitUI(self): pass def StatusPanel(self): pass def CalibrationParameters(self): pass def ShowCompassParameters(self, show): pass def __init__(self, *k, **kw): pass def InitUI(self): pass def Footer(self): pass def OnActionButton(self, evt): pass def OnShowMoreButton(self, evt): pass
17
0
18
4
15
0
2
0.01
1
4
3
0
5
7
5
5
279
64
215
73
198
2
199
73
182
4
1
2
31
6,999
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_magical/wxgeodesicgrid.py
MAVProxy.modules.mavproxy_magical.wxgeodesicgrid.GeodesicGrid
class GeodesicGrid(glrenderer.GLCanvas): def __init__(self, *k, **kw): super(GeodesicGrid, self).__init__(*k, **kw) self.vehicle_wavefront = None self.dragging = False self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp) self.Bind(wx.EVT_MOTION, self.OnMotion) self.attitude_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnAttitudeTimer, self.attitude_timer) self.attitude_timer.Start(40) self.gyro = Vector3(0, 0, 0) self.mag = Vector3(0, 0, 0) self.filtered_mag = Vector3(0, 0, 0) self.attitude_timer_last = 0 self.attitude_timestamp = 0 def CreateRenderer(self): r, g, b = self.GetParent().GetBackgroundColour() self.renderer = Renderer( background=(r / 255.0, g / 255.0, b / 255.0, 1), ) if self.vehicle_wavefront: self.renderer.set_vehicle_wavefront(self.vehicle_wavefront) self.vehicle_wavefront = None def SetVehicleWavefront(self, vehicle): if self.renderer: self.SetCurrent(self.context) self.renderer.set_vehicle_wavefront(vehicle) self.Refresh() return self.vehicle_wavefront = vehicle def SetMag(self, x, y, z): self.mag = Vector3(x, y, z) def SetAttitude(self, roll, pitch, yaw, timestamp): if not self.renderer: return dt = 0xFFFFFFFF & (timestamp - self.attitude_timestamp) dt *= 0.001 self.attitude_timestamp = timestamp desired_quaternion = quaternion.Quaternion((roll, pitch, yaw)) desired_quaternion.normalize() error = desired_quaternion / self.renderer.common_model_transform.quaternion error.normalize() self.gyro = quaternion_to_axis_angle(error) * (1.0 / dt) def OnAttitudeTimer(self, evt): if not self.renderer: return if self.dragging: return t = time.time() dt = t - self.attitude_timer_last self.attitude_timer_last = t angle = self.gyro.length() angle *= dt self.renderer.rotate(self.gyro, angle) alpha = 0.8 self.filtered_mag = alpha * self.filtered_mag + (1 - alpha) * self.mag self.renderer.set_mag(self.filtered_mag) q = self.renderer.common_model_transform.quaternion diff = q / self.renderer.last_render_quaternion angle = quaternion_to_axis_angle(diff).length() if angle < math.radians(.5): # Save some CPU time return self.Refresh() def CalcRotationVector(self, dx, dy): angle = math.degrees(math.atan2(dy, dx)) # Make angle discrete on multiples of 45 degrees angle = angle + 22.5 - (angle + 22.5) % 45 if angle % 90 == 45: x, y = 1, 1 elif (angle / 90) % 2 == 0: x, y = 1, 0 else: x, y = 0, 1 if abs(angle) > 90: x *= -1 if angle < 0: y *= -1 # NED coordinates from the camera point of view dx, dy, dz = 0, x, y # Get rotation axis by rotating the moving vector -90 degrees on x axis self.rotation_vector = Vector3(dx, dz, -dy) def GetDeltaAngle(self): radius = 60.0 pos = wx.GetMousePosition() d = pos - self.motion_reference self.motion_reference = pos self.CalcRotationVector(d.x, d.y) arc = math.sqrt(d.x**2 + d.y**2) return arc / radius def OnLeftDown(self, evt): self.motion_reference = wx.GetMousePosition() self.dragging = True def OnLeftUp(self, evt): self.dragging = False def OnMotion(self, evt): if hasattr(evt, 'ButtonIsDown'): left_button_down = evt.ButtonIsDown(wx.MOUSE_BTN_LEFT) else: left_button_down = evt.leftIsDown if not evt.Dragging() or not left_button_down: return angle = self.GetDeltaAngle() self.renderer.rotate(self.rotation_vector, angle, rotate_mag=True) self.Refresh() def UpdateVisibleSections(self, visible): for i, v in enumerate(visible): self.renderer.set_section_visible(i, v) self.Refresh()
class GeodesicGrid(glrenderer.GLCanvas): def __init__(self, *k, **kw): pass def CreateRenderer(self): pass def SetVehicleWavefront(self, vehicle): pass def SetMag(self, x, y, z): pass def SetAttitude(self, roll, pitch, yaw, timestamp): pass def OnAttitudeTimer(self, evt): pass def CalcRotationVector(self, dx, dy): pass def GetDeltaAngle(self): pass def OnLeftDown(self, evt): pass def OnLeftUp(self, evt): pass def OnMotion(self, evt): pass def UpdateVisibleSections(self, visible): pass
13
0
11
2
9
0
2
0.04
1
3
1
0
12
11
12
15
140
30
106
44
93
4
101
44
88
5
2
1
25