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
7,300
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_speech.py
MAVProxy.modules.mavproxy_speech.SpeechCommandUnload
class SpeechCommandUnload(object): def __init__(self): pass
class SpeechCommandUnload(object): def __init__(self): 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
7,301
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_speech.py
MAVProxy.modules.mavproxy_speech.SpeechModule
class SpeechModule(mp_module.MPModule): def __init__(self, mpstate): super(SpeechModule, self).__init__(mpstate, "speech", "speech output") self.add_command('speech', self.cmd_speech, "text-to-speech", ['<say|list_voices>']) self.old_mpstate_say_function = self.mpstate.functions.say self.mpstate.functions.say = self.say try: self.settings.set('speech', 1) except AttributeError: self.settings.append(('speech', int, 1)) try: self.settings.set('speech_voice', '') except AttributeError: self.settings.append(('speech_voice', str, '')) self.backend = SpeechBackend(self.settings) self.settings_set_callback_installed = False self.settings_set_callback_delay = None def settings_callback(self, setting): '''handle changes in settings''' if setting.name == "speech_voice": self.backend.send(SpeechCommandSetVoice(setting.value)) def unload(self): '''unload module''' self.backend.send(SpeechCommandUnload()) self.settings.set('speech', 0) if self.mpstate.functions.say == self.mpstate.functions.say: self.mpstate.functions.say = self.old_mpstate_say_function def say(self, text, priority='important'): '''speak some text''' ''' http://cvs.freebsoft.org/doc/speechd/ssip.html see 4.3.1 for priorities''' self.console.writeln(text) if self.settings.speech: self.backend.send(SpeechCommandSay(text, priority)) def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' type = msg.get_type() if type == "STATUSTEXT": # say some statustext values speech_prefixes = [ "Tuning: ", "@" ] for s in speech_prefixes: if msg.text.startswith(s): self.say(msg.text[len(s):]) def cmd_speech(self, args): '''speech commands''' usage = "usage: speech <say>" if len(args) < 1: print(usage) return if args[0] == "say": if len(args) < 2: print("usage: speech say <text to say>") return self.say(" ".join(args[1::])) if args[0] == "list_voices": self.backend.send(SpeechCommandListVoices()) def idle_task(self): if not self.settings_set_callback_installed: now = time.time() if self.settings_set_callback_delay is None: self.settings_set_callback_delay_start = now if now - self.settings_set_callback_delay_start < 1: return self.settings_set_callback_delay = None try: self.settings.set_callback(self.settings_callback) self.settings_set_callback_installed = True except Exception as ex: print("Caught exception (%s)" % str(ex))
class SpeechModule(mp_module.MPModule): def __init__(self, mpstate): pass def settings_callback(self, setting): '''handle changes in settings''' pass def unload(self): '''unload module''' pass def say(self, text, priority='important'): '''speak some text''' pass def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' pass def cmd_speech(self, args): '''speech commands''' pass def idle_task(self): pass
8
5
10
0
9
1
3
0.11
1
10
5
0
7
5
7
45
77
9
61
19
53
7
61
18
53
5
2
3
23
7,302
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_swarm.py
MAVProxy.modules.mavproxy_swarm.SwarmFrame
class SwarmFrame(wx.Frame): ''' The main frame of the UI. Runs in a subprocess, so need a pipe to communicate with ''' def __init__(self, state, title, params, takeoffalt): self.state = state wx.Frame.__init__(self, None, title=title, size=( 1400, 500), style=wx.DEFAULT_FRAME_STYLE) self.panel = scrolled.ScrolledPanel(self, style=wx.FULL_REPAINT_ON_RESIZE) self.panel.SetBackgroundColour(wx.WHITE) # Icon self.SetIcon(icon.SimpleIcon("Swarm").get_ico()) # Params to show (array) self.parmsToShow = params self.takeoffalt = takeoffalt self.last_layout_send = time.time() # layout. Column per leader, with followers underneath self.sizer = wx.FlexGridSizer(1, 1, 0, 0) # add in the pipe from MAVProxy self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, lambda evt, panel=self.panel: self.on_timer(evt), self.timer) self.timer.Start(100) #Fires on window resize self.Bind(wx.EVT_SIZE, self.OnSize) # layout self.panel.SetSizer(self.sizer) self.panel.Layout() self.panel.SetupScrolling() self.Show(True) def OnSize(self, e): #This refresh shouldn't be necessary self.Refresh() #Pass event up the chain so window still resizes e.Skip() def on_timer(self, event): '''receive messages from MAVProxy and pass on to GUI''' state = self.state # update saved pos/size of GUI now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now state.child_pipe.send( (win_layout.get_wx_window_layout(self), 0, 0)) if state.close_event.wait(0.001): self.timer.Stop() self.Destroy() return while state.child_pipe.poll(): obj = state.child_pipe.recv() if obj[0] == 'updatelayout': self.updateLayout(obj[1]) elif obj[0] == 'onmavlinkpacket': self.onmavlinkpacket(obj[1]) elif obj[0] == 'updateHB': self.updateHB(obj[1]) elif isinstance(obj[0], win_layout.WinLayout): win_layout.set_wx_window_layout(self, obj[0]) elif obj[0] == 'changesetting' and obj[1][0] == 'takeoffalt': self.updatetakeoffalt(int(obj[1][1])) def updatetakeoffalt(self, alt): '''Update the takeoff altitude of the vehicles''' children = self.sizer.GetChildren() # update panel for child in children: widget = child.GetWindow() if isinstance(widget, VehiclePanel): widget.updatetakeoffalt(alt) def updateHB(self, vehHB): '''Update the GUI panels if we've lost link to vehicle Panel goes red if more than 4 sec since last HB''' children = self.sizer.GetChildren() # update panel for child in children: widget = child.GetWindow() if isinstance(widget, VehiclePanel): if (widget.sysid, widget.compid) in vehHB.keys(): # put to red if more than 4 sec, else no colour. Only change if required. if vehHB[(widget.sysid, widget.compid)] + 4 < time.time() and widget.GetBackgroundColour() != wx.RED: widget.SetBackgroundColour(wx.RED) elif vehHB[(widget.sysid, widget.compid)] + 4 > time.time() and widget.GetBackgroundColour() != wx.WHITE: widget.SetBackgroundColour(wx.WHITE) def updateLayout(self, layout): '''Update (recreate) the GUI layout, based on known vehicles''' leaders = [] # array of (sysid, compid, followid, vehtype) # create list of leaders, another vehicle has it's sysid as leader for veh in layout: for vehL in layout: if vehL[2] == veh[0] and veh not in leaders: leaders.append(veh) # create list of followers followers = {} # dict of key=leadersysid, (sysid, compid, vehtype) maxfollowers = 0 for veh in layout: # don't include leaders in the follower list if veh[2] != 0: if veh[2] not in followers.keys(): followers[veh[2]] = [(veh[0], veh[1], veh[3])] else: followers[veh[2]].append((veh[0], veh[1], veh[3])) if len(followers[veh[2]]) > maxfollowers: maxfollowers = len(followers[veh[2]]) # sort followers by sysid increasing for fwr in followers.keys(): followers[fwr].sort(key=lambda tup: tup[0]) # Any unassigned vehicles: Leader with 0 followers OR leader not present # OR vehicles not present in either list (leftovers) unassignedVeh = [] # (sysid, compid, vehtype) # Leader with no followers for index, veh in enumerate(leaders): if veh[0] not in followers.keys(): del leaders[index] unassignedVeh.append((veh[0], veh[1], veh[3])) # Not present in either list allfollowersflat = [] for fl in followers.items(): for vv in fl[1]: allfollowersflat.append(vv[0]) for veh in layout: if (veh not in leaders) and veh[0] not in allfollowersflat: unassignedVeh.append((veh[0], veh[1], veh[3])) # Leader not present for leader in followers.copy().keys(): if leader not in [i[0] for i in leaders]: for veh in followers[leader]: unassignedVeh.append(veh) del followers[leader] # followers.remove(leader) self.sizer.Clear(True) colsVeh = max(maxfollowers, len(unassignedVeh)) self.sizer = wx.FlexGridSizer((len(leaders)*2) + 1, colsVeh+1+1, 5, 0) # start populating the grid # for each row: for leader in leaders: panelLeader = VehiclePanel( self.state, self.panel, leader[0], leader[1], leader[3], True, followers[leader[0]], self.takeoffalt) self.sizer.Add(panelLeader) # add vertical line line = wx.StaticLine(self.panel, style=wx.LI_VERTICAL) self.sizer.Add(line, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) for follower in range(colsVeh): if leader[0] in followers.keys() and len(followers[leader[0]]) > follower: panelFollower = VehiclePanel(self.state, self.panel, followers[leader[0]][follower][0], followers[ leader[0]][follower][1], followers[leader[0]][follower][2], False, None, self.takeoffalt) else: panelFollower = wx.StaticText(self.panel, label="N/A") self.sizer.Add(panelFollower, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) # add horizontal line, column by column for follower in range(colsVeh+1+1): line = wx.StaticLine(self.panel, style=wx.LI_HORIZONTAL) self.sizer.Add(line, proportion=0, flag=wx.EXPAND | wx.ALL, border=0) # add "unassigned" row panelUnassigned = UnassignedPanel(self.state, self.panel) self.sizer.Add(panelUnassigned, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) line = wx.StaticLine(self.panel, style=wx.LI_VERTICAL) self.sizer.Add(line, proportion=0, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) for veh in unassignedVeh: panelunassigned = VehiclePanel( self.state, self.panel, veh[0], veh[1], veh[2], False, None, self.takeoffalt) self.sizer.Add(panelunassigned) self.panel.SetSizer(self.sizer) self.panel.Layout() self.panel.SetupScrolling() def onmavlinkpacket(self, msg): ''' on new mavlink packet, update relevant GUI elements''' children = self.sizer.GetChildren() sysid = msg.get_srcSystem() compid = msg.get_srcComponent() mtype = msg.get_type() for child in children: widget = child.GetWindow() # update arm and mode status on leader if isinstance(widget, VehiclePanel) and widget.sysid == sysid and widget.compid == compid: if mtype == 'HEARTBEAT': mode_map = mavutil.mode_mapping_bynumber(msg.type) isArmed = True if msg.base_mode & mavutil.mavlink.MAV_MODE_FLAG_SAFETY_ARMED == 128 else False widget.updateData(isArmed, mode_map[msg.custom_mode]) sysStatus = msg.system_status if sysStatus == mavutil.mavlink.MAV_STATE_BOOT: widget.updateStatus("Booting") elif sysStatus == mavutil.mavlink.MAV_STATE_CALIBRATING: widget.updateStatus("Calibrating") elif sysStatus == mavutil.mavlink.MAV_STATE_STANDBY: widget.updateStatus("On Ground") elif sysStatus == mavutil.mavlink.MAV_STATE_ACTIVE: widget.updateStatus("Flying") elif sysStatus == mavutil.mavlink.MAV_STATE_CRITICAL: widget.updateStatus("FAILSAFE") elif sysStatus == mavutil.mavlink.MAV_STATE_EMERGENCY: widget.updateStatus("Emergency") elif sysStatus == mavutil.mavlink.MAV_STATE_POWEROFF: widget.updateStatus("Poweroff") elif sysStatus == mavutil.mavlink.MAV_STATE_FLIGHT_TERMINATION: widget.updateStatus("Terminated") elif mtype == 'VFR_HUD': widget.updatethralt(msg.throttle, msg.alt) elif mtype == 'GLOBAL_POSITION_INT': widget.updaterelalt(msg.relative_alt * 1.0e-3) elif mtype == "SYS_STATUS": preArmGood = ((msg.onboard_control_sensors_health & mavutil.mavlink.MAV_SYS_STATUS_PREARM_CHECK) == mavutil.mavlink.MAV_SYS_STATUS_PREARM_CHECK) widget.updateprearm(preArmGood) widget.updatevoltage(float(msg.voltage_battery)/1000) elif mtype == "STATUSTEXT" and msg.severity <= mavutil.mavlink.MAV_SEVERITY_WARNING: # Only pass on warning messages or more severe widget.addstatustext(msg.text) elif mtype == 'PARAM_VALUE' and msg.param_id in self.parmsToShow: widget.updateOffset(msg.param_id, int(msg.param_value))
class SwarmFrame(wx.Frame): ''' The main frame of the UI. Runs in a subprocess, so need a pipe to communicate with ''' def __init__(self, state, title, params, takeoffalt): pass def OnSize(self, e): pass def on_timer(self, event): '''receive messages from MAVProxy and pass on to GUI''' pass def updatetakeoffalt(self, alt): '''Update the takeoff altitude of the vehicles''' pass def updateHB(self, vehHB): '''Update the GUI panels if we've lost link to vehicle Panel goes red if more than 4 sec since last HB''' pass def updateLayout(self, layout): '''Update (recreate) the GUI layout, based on known vehicles''' pass def onmavlinkpacket(self, msg): ''' on new mavlink packet, update relevant GUI elements''' pass
8
6
34
4
25
5
9
0.23
1
8
4
0
7
7
7
7
246
34
175
53
167
41
144
53
136
23
1
4
61
7,303
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_swarm.py
MAVProxy.modules.mavproxy_swarm.SwarmUI
class SwarmUI(): ''' Swarm User Interface ''' def __init__(self, parmsToShow, title='MAVProxy: Swarm Control', takeoffalt=10): self.title = title self.parmsToShow = parmsToShow self.takeoffalt = takeoffalt 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() app = wx.App(False) app.frame = SwarmFrame( self, title=self.title, params=self.parmsToShow, takeoffalt=self.takeoffalt) app.frame.Show() app.MainLoop() def changesetting(self, setting, val): '''Change a setting''' if self.child.is_alive(): self.parent_pipe.send(('changesetting', (setting, val))) 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 updateLayout(self, newLayout): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(('updatelayout', newLayout)) def updateHB(self, vehHB): '''update HB status of vehicles''' if self.child.is_alive(): self.parent_pipe.send(('updateHB', vehHB)) def onmavlinkpacket(self, pkt): '''set a status value''' if self.child.is_alive(): self.parent_pipe.send(('onmavlinkpacket', pkt))
class SwarmUI(): ''' Swarm User Interface ''' def __init__(self, parmsToShow, title='MAVProxy: Swarm Control', takeoffalt=10): pass def child_task(self): '''child process - this holds all the GUI elements''' pass def changesetting(self, setting, val): '''Change a setting''' pass def close(self): '''close the UI''' pass def is_alive(self): '''check if child is still going''' pass def updateLayout(self, newLayout): '''set a status value''' pass def updateHB(self, vehHB): '''update HB status of vehicles''' pass def onmavlinkpacket(self, pkt): '''set a status value''' pass
9
8
5
0
4
1
2
0.29
0
1
1
0
8
7
8
8
54
9
35
16
26
10
34
16
25
2
0
1
13
7,304
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_swarm.py
MAVProxy.modules.mavproxy_swarm.UnassignedPanel
class UnassignedPanel(wx.Panel): ''' A wx.Panel to hold a single unassigned vehicle ''' def __init__(self, state, parent): wx.Panel.__init__(self, parent) # , style=wx.BORDER_SIMPLE) self.state = state self.sizer = wx.BoxSizer(wx.VERTICAL) self.titleText = wx.StaticText( self, label="Unassigned Vehicles -->\n\nTools:") self.sizer.Add(self.titleText, flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5) self.getParamsButton = wx.Button( self, label="Get offsets", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.getParams, self.getParamsButton) self.resetButton = wx.Button( self, label="Reset layout", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.reset, self.resetButton) self.sizer.Add(self.getParamsButton) self.sizer.Add(self.resetButton) # Do the sizer layout self.SetSizer(self.sizer) def getParams(self, event): '''get offset params again''' self.state.child_pipe.send(("getparams", None, None)) def reset(self, event): '''arm/disarm the vehicle''' self.state.child_pipe.send(("resetLayout", None, None))
class UnassignedPanel(wx.Panel): ''' A wx.Panel to hold a single unassigned vehicle ''' def __init__(self, state, parent): pass def getParams(self, event): '''get offset params again''' pass def reset(self, event): '''arm/disarm the vehicle''' pass
4
3
10
2
7
1
1
0.32
1
0
0
0
3
5
3
3
35
7
22
9
18
7
18
9
14
1
1
0
3
7,305
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_swarm.py
MAVProxy.modules.mavproxy_swarm.VehiclePanel
class VehiclePanel(wx.Panel): ''' A wx.panel to hold a single vehicle (leader or follower) ''' def __init__(self, state, parent, sysid, compid, vehtype, isLeader, listFollowers, takeoffalt): wx.Panel.__init__(self, parent) self.state = state self.sysid = sysid self.compid = compid self.listFollowers = listFollowers self.isLeader = isLeader self.vehtype = vehtype self.takeoffalt = takeoffalt self.inLinkLoss = False # XYZ offsets. Filled are we get params self.offsetValues = [None, None, None] self.sizer = wx.BoxSizer(wx.VERTICAL) # Status boxes if self.isLeader: self.title = wx.StaticText(self, label="Leader {0}:{1} {2}".format( sysid, compid, get_vehicle_name(vehtype))) self.offsets = wx.StaticText(self, label="Offset: N/A") else: self.title = wx.StaticText(self, label="Veh {0}:{1} {2}".format( sysid, compid, get_vehicle_name(vehtype))) self.offsets = wx.StaticText(self, label="Offset: xxxxxx") self.armmode = wx.StaticText(self, label="armed/mode N/A ") self.thrAlt = wx.StaticText( self, label="Alt: {0}m Thr: {1}%".format(0, 0)) self.altRel = wx.StaticText(self, label="Rel Alt: {0}m".format(0)) self.battery = wx.StaticText(self, label="Battery: {0}V".format(0)) self.status = wx.StaticText(self, label="Status: N/A") self.prearm = wx.StaticText(self, label="Prearm: N/A") self.statusText = wx.TextCtrl( self, style=wx.TE_READONLY | wx.TE_MULTILINE, size=wx.Size(140, 100)) # Command buttons self.doArm = wx.Button(self, label="XXX", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.arm, self.doArm) if self.isLeader: self.armSizer = wx.BoxSizer(wx.HORIZONTAL) self.doArmAll = wx.Button(self, label="ALL", size=wx.Size(70, 50)) self.Bind(wx.EVT_BUTTON, self.armAll, self.doArmAll) self.doGuided = wx.Button( self, label="Mode GUIDED", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.guided, self.doGuided) if self.isLeader: self.guidedSizer = wx.BoxSizer(wx.HORIZONTAL) self.doGuidedAll = wx.Button( self, label="ALL", size=wx.Size(70, 50)) self.Bind(wx.EVT_BUTTON, self.guidedAll, self.doGuidedAll) if vehtype != mavutil.mavlink.MAV_TYPE_GROUND_ROVER: self.doGuidedTakeoff = wx.Button( self, label="GUIDED T/O {0}m".format(self.takeoffalt), size=wx.Size(130, 50)) self.Bind(wx.EVT_BUTTON, self.guidedTakeoff, self.doGuidedTakeoff) if self.isLeader: self.takeoffSizer = wx.BoxSizer(wx.HORIZONTAL) self.doGuidedTakeoffAll = wx.Button( self, label="ALL".format(self.takeoffalt), size=wx.Size(70, 50)) self.Bind(wx.EVT_BUTTON, self.guidedTakeoffAll, self.doGuidedTakeoffAll) self.doRTL = wx.Button(self, label="Mode RTL", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.rtl, self.doRTL) if self.isLeader: self.rtlSizer = wx.BoxSizer(wx.HORIZONTAL) self.doRTLAll = wx.Button(self, label="ALL", size=wx.Size(70, 50)) self.Bind(wx.EVT_BUTTON, self.rtlAll, self.doRTLAll) self.doKill = wx.Button(self, label="KILL", size=wx.Size(100, 50)) self.killTimer = None self.Bind(wx.EVT_BUTTON, self.kill, self.doKill) if self.isLeader: self.killSizer = wx.BoxSizer(wx.HORIZONTAL) self.doKillAll = wx.Button(self, label="ALL", size=wx.Size(70, 50)) self.killAllTimer = None self.Bind(wx.EVT_BUTTON, self.killall, self.doKillAll) if self.isLeader: self.doFollowAll = wx.Button( self, label="All Follow Leader", size=wx.Size(130, 50)) self.Bind(wx.EVT_BUTTON, self.followAll, self.doFollowAll) self.doAUTO = wx.Button( self, label="Mode AUTO", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.auto, self.doAUTO) else: self.doFollow = wx.Button( self, label="Mode Follow", size=wx.Size(100, 50)) self.Bind(wx.EVT_BUTTON, self.follow, self.doFollow) # Do the sizer layout self.doSizer() # get offset params. Needs to be after GUI elements are created time.sleep(0.05) self.state.child_pipe.send(("getoffsets", self.sysid, self.compid)) def doSizer(self): '''Sort out all the sizers and layout''' self.sizer.Add(self.title) self.sizer.Add(self.armmode) self.sizer.Add(self.thrAlt) self.sizer.Add(self.altRel) self.sizer.Add(self.battery) self.sizer.Add(self.status) self.sizer.Add(self.prearm) self.sizer.Add(self.offsets) self.sizer.Add(self.statusText) if self.isLeader: self.armSizer.Add(self.doArm) self.armSizer.Add(self.doArmAll) self.sizer.Add(self.armSizer) else: self.sizer.Add(self.doArm) if self.vehtype != mavutil.mavlink.MAV_TYPE_GROUND_ROVER: if self.isLeader: self.takeoffSizer.Add(self.doGuidedTakeoff) self.takeoffSizer.Add(self.doGuidedTakeoffAll) self.sizer.Add(self.takeoffSizer) else: self.sizer.Add(self.doGuidedTakeoff) if self.isLeader: self.guidedSizer.Add(self.doGuided) self.guidedSizer.Add(self.doGuidedAll) self.sizer.Add(self.guidedSizer) else: self.sizer.Add(self.doGuided) if self.isLeader: self.rtlSizer.Add(self.doRTL) self.rtlSizer.Add(self.doRTLAll) self.sizer.Add(self.rtlSizer) else: self.sizer.Add(self.doRTL) if self.isLeader: self.killSizer.Add(self.doKill) self.killSizer.Add(self.doKillAll) self.sizer.Add(self.killSizer) else: self.sizer.Add(self.doKill) if self.isLeader: self.sizer.Add(self.doFollowAll) self.sizer.Add(self.doAUTO) else: self.sizer.Add(self.doFollow) self.SetSizer(self.sizer) def updatetakeoffalt(self, alt): '''update takeoff altitude''' self.takeoffalt = alt if self.vehtype != mavutil.mavlink.MAV_TYPE_GROUND_ROVER: self.doGuidedTakeoff.SetLabel( "GUIDED T/O {0}m".format(self.takeoffalt)) if self.isLeader: self.doGuidedTakeoffAll.SetLabel("ALL".format(self.takeoffalt)) def updateData(self, armed, mode): '''update the arming/mode status. Only change if required''' if armed and (self.doArm.GetLabel() in ["ARM", "XXX"] or str(mode) not in self.armmode.GetLabel()): self.armmode.SetForegroundColour((0, 200, 0)) self.armmode.SetLabel("Armed" + "/" + str(mode)) self.doArm.SetLabel("DISARM") elif not armed and (self.doArm.GetLabel() in ["DISARM", "XXX"] or str(mode) not in self.armmode.GetLabel()): self.armmode.SetForegroundColour((200, 0, 0)) self.armmode.SetLabel("Disarmed" + "/" + str(mode)) self.doArm.SetLabel("ARM") def updatethralt(self, throttle, alt): '''update throttle and altitude status''' self.thrAlt.SetLabel("Alt: {0}m Thr: {1}%".format(int(alt), throttle)) def updaterelalt(self, relalt): '''update relative altitude''' self.altRel.SetLabel("Rel Alt: {0}m".format(int(relalt))) def updateStatus(self, status): '''update status''' self.status.SetLabel("Status: {0}".format(status)) if status in ["FAILSAFE", "Emergency", "Terminated"]: self.status.SetForegroundColour((200, 0, 0)) elif status == "Flying": self.status.SetForegroundColour((0, 200, 0)) else: self.status.SetForegroundColour((120, 120, 0)) def updateprearm(self, preArmGood): '''Update pre-arm status''' self.prearm.SetLabel("Prearm: {0}".format( "OK" if preArmGood else "BAD")) if preArmGood: self.prearm.SetForegroundColour((0, 200, 0)) else: self.prearm.SetForegroundColour((200, 0, 0)) def updatevoltage(self, voltage): '''update battery voltage''' self.battery.SetLabel("Battery: {0:.1f}V".format(voltage)) def arm(self, event): '''arm/disarm the vehicle''' self.state.child_pipe.send( ("arm" if self.doArm.GetLabel() == "ARM" else "disarm", self.sysid, self.compid)) def armAll(self, event): '''Arm leader and all followers''' self.state.child_pipe.send(("arm", self.sysid, self.compid)) if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send(("arm", sysidFollow, compidFollow)) def guided(self, event): '''switch to mode guided''' self.state.child_pipe.send(("GUIDED", self.sysid, self.compid)) def guidedAll(self, event): '''mode guided for leader and all followers''' self.state.child_pipe.send(("GUIDED", self.sysid, self.compid)) if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send( ("GUIDED", sysidFollow, compidFollow)) def addstatustext(self, text): '''have recieved statustext, update relevant control''' self.statusText.AppendText('\n' + text) def guidedTakeoff(self, event): '''switch to guided mode, wait 0.1 sec then nav_takeoff to TAKEOFFALT''' self.state.child_pipe.send(("GUIDED", self.sysid, self.compid)) time.sleep(0.1) self.state.child_pipe.send(("takeoff", self.sysid, self.compid)) def guidedTakeoffAll(self, event): '''switch to guided mode, wait 0.1 sec then nav_takeoff to TAKEOFFALT for all vehicles''' self.state.child_pipe.send(("GUIDED", self.sysid, self.compid)) time.sleep(0.1) self.state.child_pipe.send(("takeoff", self.sysid, self.compid)) if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send( ("GUIDED", sysidFollow, compidFollow)) time.sleep(0.1) self.state.child_pipe.send( ("takeoff", sysidFollow, compidFollow)) def rtl(self, event): '''switch to mode RTL''' self.state.child_pipe.send(("RTL", self.sysid, self.compid)) def rtlAll(self, event): '''RTL leader and all followers''' self.state.child_pipe.send(("RTL", self.sysid, self.compid)) if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send(("RTL", sysidFollow, compidFollow)) def killTimeout(self, event): '''Kill action timeout''' self.doKill.SetLabel("KILL") self.killTimer = None def killAllTimeout(self, event): '''Kill all action timeout''' self.doKillAll.SetLabel("ALL") self.killAllTimer = None def kill(self, event): '''disarm force (kill) the drone''' if self.doKill.GetLabel() == "KILL": self.doKill.SetLabel("KILL Sure?") # start a 1 sec timer self.killTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.killTimeout, self.killTimer) self.killTimer.Start(1000) else: self.state.child_pipe.send(("kill", self.sysid, self.compid)) def killall(self, event): '''disarm force (kill) the whole swarm''' if self.doKillAll.GetLabel() == "ALL": self.doKillAll.SetLabel("ALL Sure?") # start a 1 sec timer self.killAllTimer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.killAllTimeout, self.killAllTimer) self.killAllTimer.Start(1000) else: self.state.child_pipe.send(("kill", self.sysid, self.compid)) if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send( ("kill", sysidFollow, compidFollow)) def follow(self, event): '''switch to mode follow''' self.state.child_pipe.send(("FOLLOW", self.sysid, self.compid)) def followAll(self, event): '''Mode FOLLOW for all followers''' if len(self.listFollowers) > 0: for (sysidFollow, compidFollow, vehtype) in self.listFollowers: self.state.child_pipe.send( ("FOLLOW", sysidFollow, compidFollow)) def auto(self, event): '''switch to mode AUTO''' self.state.child_pipe.send(("AUTO", self.sysid, self.compid)) def updateOffset(self, param, value): '''get offset param''' if self.isLeader: return if param == 'FOLL_OFS_X': self.offsetValues[0] = value elif param == 'FOLL_OFS_Y': self.offsetValues[1] = value elif param == 'FOLL_OFS_Z': self.offsetValues[2] = value else: return # refresh static text if self.offsetValues[0] != None and self.offsetValues[1] != None and self.offsetValues[2] != None: self.offsets.SetLabel("Offset: {0}m,{1}m,{2}m".format( self.offsetValues[0], self.offsetValues[1], self.offsetValues[2]))
class VehiclePanel(wx.Panel): ''' A wx.panel to hold a single vehicle (leader or follower) ''' def __init__(self, state, parent, sysid, compid, vehtype, isLeader, listFollowers, takeoffalt): pass def doSizer(self): '''Sort out all the sizers and layout''' pass def updatetakeoffalt(self, alt): '''update takeoff altitude''' pass def updateData(self, armed, mode): '''update the arming/mode status. Only change if required''' pass def updatethralt(self, throttle, alt): '''update throttle and altitude status''' pass def updaterelalt(self, relalt): '''update relative altitude''' pass def updateStatus(self, status): '''update status''' pass def updateprearm(self, preArmGood): '''Update pre-arm status''' pass def updatevoltage(self, voltage): '''update battery voltage''' pass def arm(self, event): '''arm/disarm the vehicle''' pass def armAll(self, event): '''Arm leader and all followers''' pass def guided(self, event): '''switch to mode guided''' pass def guidedAll(self, event): '''mode guided for leader and all followers''' pass def addstatustext(self, text): '''have recieved statustext, update relevant control''' pass def guidedTakeoff(self, event): '''switch to guided mode, wait 0.1 sec then nav_takeoff to TAKEOFFALT''' pass def guidedTakeoffAll(self, event): '''switch to guided mode, wait 0.1 sec then nav_takeoff to TAKEOFFALT for all vehicles''' pass def rtl(self, event): '''switch to mode RTL''' pass def rtlAll(self, event): '''RTL leader and all followers''' pass def killTimeout(self, event): '''Kill action timeout''' pass def killAllTimeout(self, event): '''Kill all action timeout''' pass def killTimeout(self, event): '''disarm force (kill) the drone''' pass def killall(self, event): '''disarm force (kill) the whole swarm''' pass def follow(self, event): '''switch to mode follow''' pass def followAll(self, event): '''Mode FOLLOW for all followers''' pass def auto(self, event): '''switch to mode AUTO''' pass def updateOffset(self, param, value): '''get offset param''' pass
27
26
12
1
10
1
3
0.14
1
2
0
0
26
39
26
26
340
49
255
72
228
36
217
72
190
9
1
3
69
7,306
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_swarm.py
MAVProxy.modules.mavproxy_swarm.swarm
class swarm(mp_module.MPModule): ''' The MAVProxy module that manages the GUI ''' def __init__(self, mpstate): '''Initialise module''' super(swarm, self).__init__(mpstate, "swarm", "swarm module", multi_vehicle=True) # array of tuples for (SYSID, COMPID, FOLL_SYSID, veh_type) of all detected vehicles self.vehicleListing = [] self.add_command('swarm', self.cmd_swarm, "swarm control", ["<status>", "set (SWARMSETTING)"]) self.swarm_settings = mp_settings.MPSettings( [("takeoffalt", int, 10)]) # meters self.add_completion_function('(SWARMSETTING)', self.swarm_settings.completion) # Which params to show on the GUI per vehicle self.parmsToShow = ["FOLL_OFS_X", "FOLL_OFS_Y", "FOLL_OFS_Z"] # time of last HB for each vehicle. Key is tuple of sysid,compid. Value is time of last HB self.vehicleLastHB = {} self.needHBupdate_timer = mavutil.periodic_event(1) # Periodic event to update the GUI self.needGUIupdate = False self.needGUIupdate_timer = mavutil.periodic_event(1) # Periodic event to send param (offset) requests (5 Hz) self.requestParams_timer = mavutil.periodic_event(5) # Periodic event re-get params (0.1 Hz) self.RerequestParams_timer = mavutil.periodic_event(0.1) # List of any vehicles we still need to get params for self.vehParamsToGet = [] # All vehicle positions. Dict. Key is sysid, value is tuple of (lat,lon,alt) self.allVehPos = {} self.validVehicles = frozenset([mavutil.mavlink.MAV_TYPE_FIXED_WING, mavutil.mavlink.MAV_TYPE_VTOL_DUOROTOR, mavutil.mavlink.MAV_TYPE_VTOL_QUADROTOR, mavutil.mavlink.MAV_TYPE_VTOL_TILTROTOR, mavutil.mavlink.MAV_TYPE_GROUND_ROVER, mavutil.mavlink.MAV_TYPE_SURFACE_BOAT, mavutil.mavlink.MAV_TYPE_SUBMARINE, mavutil.mavlink.MAV_TYPE_QUADROTOR, mavutil.mavlink.MAV_TYPE_COAXIAL, mavutil.mavlink.MAV_TYPE_HEXAROTOR, mavutil.mavlink.MAV_TYPE_OCTOROTOR, mavutil.mavlink.MAV_TYPE_TRICOPTER, mavutil.mavlink.MAV_TYPE_HELICOPTER, mavutil.mavlink.MAV_TYPE_DODECAROTOR, mavutil.mavlink.MAV_TYPE_AIRSHIP]) # The GUI self.gui = SwarmUI( self.parmsToShow, takeoffalt=self.swarm_settings.get('takeoffalt')) def cmd_swarm(self, args): '''swarm command parser''' usage = "usage: swarm <set>" if len(args) == 0: print(usage) elif args[0] == "set": self.swarm_settings.command(args[1:]) if len(args) == 3: self.gui.changesetting(args[1], args[2]) else: print(usage) def set_layout(self, layout): '''set window layout''' self.gui.parent_pipe.send([layout]) def idle_task(self): '''run on idle''' # send updated HB stats to GUI every 1 sec if self.needHBupdate_timer.trigger(): self.gui.updateHB(self.vehicleLastHB) # do we need to update the GUI? if self.needGUIupdate_timer.trigger() and self.needGUIupdate: self.gui.updateLayout(self.vehicleListing) self.needGUIupdate = False # do we need to get any vehicle follow sysid params? # only send param requests 1 per 0.1sec, to avoid link flooding if self.requestParams_timer.trigger() and len(self.vehParamsToGet) > 0: (sysid, compid) = self.vehParamsToGet.pop(0) self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.param_request_read_send( sysid, compid, parmString("FOLL_SYSID"), -1)) if self.RerequestParams_timer.trigger(): # If any in vehicleListing are missing their FOLL_SYSID, re-request for veh in self.vehicleListing: if veh[2] == 0: self.vehParamsToGet.append(((veh[0], veh[1]))) # execute any commands from GUI via parent_pipe if self.gui.parent_pipe.poll(): (cmd, sysid, compid) = self.gui.parent_pipe.recv() if isinstance(cmd, win_layout.WinLayout): win_layout.set_layout(cmd, self.set_layout) if cmd == "arm": self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.command_long_send( # self.master.mav.command_long_send( sysid, # target_system compid, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 1, # param1 (1 to indicate arm) 0, # param2 (all other params meaningless) 0, # param3 0, # param4 0, # param5 0, # param6 0)) # param7 elif cmd == "disarm": self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.command_long_send( sysid, # target_system compid, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 0, # param1 (1 to indicate arm) 0, # param2 (all other params meaningless) 0, # param3 0, # param4 0, # param5 0, # param6 0)) # param7 elif cmd == "takeoff": self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.command_long_send( sysid, # target_system compid, # target_component mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, # command 0, # confirmation 0, # param1 0, # param2 0, # param3 0, # param4 0, # param5 0, # param6 self.swarm_settings.takeoffalt)) # param7 elif cmd in ["FOLLOW", "RTL", "AUTO", "GUIDED"]: mode_mapping = self.master.mode_mapping() self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.command_long_send(sysid, compid, mavutil.mavlink.MAV_CMD_DO_SET_MODE, 0, mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED, mode_mapping[cmd], 0, 0, 0, 0, 0)) elif cmd == "kill": self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.command_long_send( sysid, # target_system compid, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, # command 0, # confirmation 0, # param1 (0 to indicate disarm) 21196, # param2 (indicates force disarm) 0, # param3 0, # param4 0, # param5 0, # param6 0)) # param7 elif cmd == 'getoffsets': # time.sleep(0.1) for parm in self.parmsToShow: self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.param_request_read_send( sysid, compid, parmString(parm), -1)) elif cmd == 'resetLayout': self.vehicleListing = [] self.vehicleLastHB = {} self.needGUIupdate = True # self.gui.updateLayout(self.vehicleListing) elif cmd == 'getparams': for (sysid, compid, foll_sysid, veh_type) in self.vehicleListing: # time.sleep(0.1) for parm in self.parmsToShow: self.mpstate.foreach_mav(sysid, compid, lambda mav: mav.param_request_read_send( sysid, compid, parmString(parm), -1)) def mavlink_packet(self, m): '''handle incoming mavlink packets''' mtype = m.get_type() sysid = m.get_srcSystem() compid = m.get_srcComponent() # add to GUI if vehicle not seen before if mtype == 'HEARTBEAT' and m.type in self.validVehicles and not (sysid in [sysidList[0] for sysidList in self.vehicleListing] and compid in [compidList[1] for compidList in self.vehicleListing]): self.vehicleListing.append((sysid, compid, 0, m.type)) # figure out leader for vehicle - check FOLL_SYSID self.vehParamsToGet.append((sysid, compid)) self.needGUIupdate = True self.vehicleLastHB[(sysid, compid)] = time.time() # Only send these packets on if the vehicle is already in the list elif (sysid, compid) in self.vehicleLastHB.keys(): # update time vehicle was last seen if mtype == 'HEARTBEAT': self.vehicleLastHB[(sysid, compid)] = time.time() # updated leader information from vehicle elif mtype == 'PARAM_VALUE' and m.param_id == "FOLL_SYSID": for i in range(0, len(self.vehicleListing)): # only update if the leader ID has changed (avoids unessariliy refreshing the UI) if self.vehicleListing[i][0] == sysid and self.vehicleListing[i][1] == compid and self.vehicleListing[i][2] != int(m.param_value): self.vehicleListing[i] = (self.vehicleListing[i][0], self.vehicleListing[i][1], int( m.param_value), self.vehicleListing[i][3]) # get GUI to update layout self.needGUIupdate = True break # pass to gui elements. Only send relevant packets, otherwise will slow the GUI if mtype in ['HEARTBEAT', 'VFR_HUD', 'GLOBAL_POSITION_INT', "SYS_STATUS", "STATUSTEXT", 'PARAM_VALUE']: self.gui.onmavlinkpacket(m)
class swarm(mp_module.MPModule): ''' The MAVProxy module that manages the GUI ''' def __init__(self, mpstate): '''Initialise module''' pass def cmd_swarm(self, args): '''swarm command parser''' pass def set_layout(self, layout): '''set window layout''' pass def idle_task(self): '''run on idle''' pass def mavlink_packet(self, m): '''handle incoming mavlink packets''' pass
6
6
43
4
33
15
7
0.46
1
7
3
0
5
13
5
43
224
23
166
30
160
77
78
30
72
20
2
4
34
7,307
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_rc.py
MAVProxy.modules.mavproxy_rc.RCModule
class RCModule(mp_module.MPModule): def __init__(self, mpstate): super(RCModule, self).__init__(mpstate, "rc", "rc command handling", public = True) self.count = 18 self.override = [ 0 ] * self.count self.last_override = [ 0 ] * self.count self.override_counter = 0 x = "|".join(str(x) for x in range(1, (self.count+1))) self.add_command('rc', self.cmd_rc, "RC input control", ['<%s|all>' % x]) self.add_command('switch', self.cmd_switch, "flight mode switch control", ['<0|1|2|3|4|5|6>']) self.rc_settings = mp_settings.MPSettings( [('override_hz', float, 10.0)]) if self.sitl_output: self.rc_settings.override_hz = 20.0 self.add_completion_function('(RCSETTING)', self.rc_settings.completion) self.override_period = mavutil.periodic_event(self.rc_settings.override_hz) self.servoout_gui = None self.rcin_gui = None self.init_gui_menus() def init_gui_menus(self): '''initialise menus for console''' self.menu_added_console = False self.menu = None if not mp_util.has_wxpython: return self.menu = MPMenuSubMenu( "Tools", items=self.gui_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 def unload(self): if self.servoout_gui: self.servoout_gui.close() if self.rcin_gui: self.rcin_gui.close() 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) super(RCModule, self).unload() def idle_task(self): self.override_period.frequency = self.rc_settings.override_hz if self.override_period.trigger(): if (self.override != [ 0 ] * self.count or self.override != self.last_override or self.override_counter > 0): self.last_override = self.override[:] self.send_rc_override() if self.override_counter > 0: self.override_counter -= 1 self.idle_task_add_menu_items() # Check if the user has closed any GUI windows if self.servoout_gui and self.servoout_gui.close_event.wait(0.001): self.servoout_gui = None if self.rcin_gui and self.rcin_gui.close_event.wait(0.001): self.rcin_gui = None def mavlink_packet(self, m): '''handle mavlink packets''' if m.get_type() == 'RC_CHANNELS' and self.rcin_gui: self.rcin_gui.processPacket(m) elif m.get_type() == 'SERVO_OUTPUT_RAW' and self.servoout_gui: self.servoout_gui.processPacket(m) def send_rc_override(self): '''send RC override packet''' if self.sitl_output: chan16 = self.override[:16] buf = struct.pack('<HHHHHHHHHHHHHHHH', *chan16) self.sitl_output.write(buf) else: chan18 = self.override[:18] self.master.mav.rc_channels_override_send(self.target_system, self.target_component, *chan18) def cmd_switch(self, args): '''handle RC switch changes''' mapping = [ 0, 1165, 1295, 1425, 1555, 1685, 1815 ] if len(args) != 1: print("Usage: switch <pwmvalue>") return value = int(args[0]) if value < 0 or value > 6: print("Invalid switch value. Use 1-6 for flight modes, '0' to disable") return if self.vehicle_type == 'copter': default_channel = 5 else: default_channel = 8 if self.vehicle_type == 'rover': flite_mode_ch_parm = int(self.get_mav_param("MODE_CH", default_channel)) else: flite_mode_ch_parm = int(self.get_mav_param("FLTMODE_CH", default_channel)) self.override[flite_mode_ch_parm - 1] = mapping[value] self.override_counter = 10 self.send_rc_override() if value == 0: print("Disabled RC switch override") else: print("Set RC switch override to %u (PWM=%u channel=%u)" % ( value, mapping[value], flite_mode_ch_parm)) def set_override(self, newchannels): '''this is a public method for use by drone API or other scripting''' self.override = newchannels self.override_counter = 10 self.send_rc_override() def set_override_chan(self, channel, value): '''this is a public method for use by drone API or other scripting''' self.override[channel] = value self.override_counter = 10 self.send_rc_override() def get_override_chan(self, channel): '''this is a public method for use by drone API or other scripting''' return self.override[channel] def cmd_rc_status(self): print("") for i in range(self.count): value = "%u" % self.override[i] if value == "65535": value += " (ignored)" elif value == "0": value += " (no override)" print("%2d: %s" % (i+1, value)) def cmd_rc(self, args): '''handle RC value override''' if len(args) > 0 and args[0] == 'set': self.rc_settings.command(args[1:]) return if len(args) == 1 and args[0] == 'clear': channels = self.override for i in range(self.count): channels[i] = 0 self.set_override(channels) return if len(args) == 1 and args[0] == "status": self.cmd_rc_status() return if len(args) == 1 and args[0] == "guiin": if not mp_util.has_wxpython: print("No wxpython detected. Cannot show GUI") elif sys.version_info >= (3, 10) and sys.modules['wx'].__version__ < '4.2.1': print("wxpython needs to be >=4.2.1 on Python >=3.10. Cannot show GUI") elif not self.rcin_gui: from MAVProxy.modules.lib import wxrc self.rcin_gui = wxrc.RCStatus(panelType=wxrc.PanelType.RC_IN) return if len(args) == 1 and args[0] == "guiout": if not mp_util.has_wxpython: print("No wxpython detected. Cannot show GUI") elif sys.version_info >= (3, 10) and sys.modules['wx'].__version__ < '4.2.1': print("wxpython needs to be >=4.2.1 on Python >=3.10. Cannot show GUI") elif not self.servoout_gui: from MAVProxy.modules.lib import wxrc self.servoout_gui = wxrc.RCStatus(panelType=wxrc.PanelType.SERVO_OUT) return if len(args) != 2: print("Usage: rc <set|channel|all|clear|status|guiin|guiout> <pwmvalue>") return value = int(args[1]) if value > 65535 or value < -1: raise ValueError("PWM value must be a positive integer between 0 and 65535") if value == -1: value = 65535 channels = self.override if args[0] == 'all': for i in range(self.count): channels[i] = value else: channel = int(args[0]) if channel < 1 or channel > self.count: print("Channel must be between 1 and %u or 'all'" % self.count) return channels[channel - 1] = value self.set_override(channels) def gui_menu_items(self): return [ MPMenuItem('RC Inputs', 'RC Inputs', '# rc guiin'), MPMenuItem('Servo Outputs', 'Servo Outputs', '# rc guiout'), ]
class RCModule(mp_module.MPModule): def __init__(self, mpstate): pass def init_gui_menus(self): '''initialise menus for console''' pass def idle_task_add_menu_items(self): '''check for load of other modules, add our items as required''' pass def unload(self): pass def unload_remove_menu_items(self): '''remove out menu items from other modules''' pass def idle_task_add_menu_items(self): pass def mavlink_packet(self, m): '''handle mavlink packets''' pass def send_rc_override(self): '''send RC override packet''' pass def cmd_switch(self, args): '''handle RC switch changes''' pass def set_override(self, newchannels): '''this is a public method for use by drone API or other scripting''' pass def set_override_chan(self, channel, value): '''this is a public method for use by drone API or other scripting''' pass def get_override_chan(self, channel): '''this is a public method for use by drone API or other scripting''' pass def cmd_rc_status(self): pass def cmd_rc_status(self): '''handle RC value override''' pass def gui_menu_items(self): pass
16
10
13
0
12
1
4
0.08
1
11
5
0
15
10
15
53
214
21
180
42
162
15
155
42
137
19
2
3
58
7,308
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/mission_editor.py
MAVProxy.modules.mavproxy_misseditor.mission_editor.MissionEditorMain
class MissionEditorMain(object): def __init__(self, mpstate, elemodel): self.num_wps_expected = 0 #helps me to know if all my waypoints I'm expecting have arrived self.wps_received = {} self.event_queue = multiproc.Queue() self.event_queue_lock = multiproc.Lock() self.gui_event_queue = multiproc.Queue() self.gui_event_queue_lock = multiproc.Lock() self.object_queue = multiproc.Queue() self.close_window = multiproc.Semaphore() self.close_window.acquire() self.child = multiproc.Process(target=self.child_task,args=(self.event_queue,self.event_queue_lock,self.gui_event_queue,self.gui_event_queue_lock,self.close_window, elemodel)) self.child.start() self.event_thread = MissionEditorEventThread(self, self.event_queue, self.event_queue_lock) self.event_thread.start() self.mpstate = mpstate self.mpstate.miss_editor = self self.last_unload_check_time = time.time() self.unload_check_interval = 0.1 # seconds self.time_to_quit = False self.mavlink_message_queue = multiproc.Queue() self.mavlink_message_queue_handler = threading.Thread(target=self.mavlink_message_queue_handler) self.mavlink_message_queue_handler.start() self.needs_unloading = False self.last_wp_change = time.time() def mavlink_message_queue_handler(self): while not self.time_to_quit: while True: if self.time_to_quit: return if not self.mavlink_message_queue.empty(): break time.sleep(0.1) m = self.mavlink_message_queue.get() #MAKE SURE YOU RELEASE THIS LOCK BEFORE LEAVING THIS METHOD!!! #No "return" statement should be put in this method! self.gui_event_queue_lock.acquire() try: self.process_mavlink_packet(m) except Exception as e: print("Caught exception (%s)" % str(e)) import traceback traceback.print_stack() self.gui_event_queue_lock.release() def unload(self): '''unload module''' self.mpstate.miss_editor.close() self.mpstate.miss_editor = None def get_wps_from_module(self): '''get WP list from wp module''' self.event_queue_lock.acquire() self.event_queue.put(self.mpstate.module('wp').wploader) self.event_queue_lock.release() def idle_task(self): now = time.time() if self.last_unload_check_time + self.unload_check_interval < now: self.last_unload_check_time = now if not self.child.is_alive(): self.close() return last_wp_change = self.mpstate.module('wp').loading_waypoint_lasttime if last_wp_change > self.last_wp_change: self.last_wp_change = last_wp_change self.get_wps_from_module() def mavlink_packet(self, m): if (getattr(m, 'mission_type', None) is not None and m.mission_type != mavutil.mavlink.MAV_MISSION_TYPE_MISSION): return mtype = m.get_type() if mtype in ['MISSION_COUNT', 'MISSION_ITEM', 'MISSION_ITEM_INT']: if mtype == 'MISSION_ITEM_INT': m = self.mpstate.module('wp').wp_from_mission_item_int(m) self.mavlink_message_queue.put(m) def process_mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() # if you add processing for an mtype here, remember to add it # to mavlink_packet, above if (getattr(m, 'mission_type', None) is not None and m.mission_type != mavutil.mavlink.MAV_MISSION_TYPE_MISSION): return if mtype in ['MISSION_COUNT']: if (self.num_wps_expected == 0): #I haven't asked for WPs, or these messages are duplicates #of msgs I've already received. self.mpstate.console.error("No waypoint load started (from Editor).") #I only clear the mission in the Editor if this was a read event elif (self.num_wps_expected == -1): self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_CLEAR_MISS_TABLE)) self.num_wps_expected = m.count self.wps_received = {} if m.count > 1: self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_ADD_MISS_TABLE_ROWS,num_rows=m.count-1)) #write has been sent by the mission editor: elif (self.num_wps_expected > 1): if (m.count != self.num_wps_expected): self.mpstate.console.error("wpedit: mission is stale") #since this is a write operation from the Editor there #should be no need to update number of table rows elif mtype in ['MISSION_ITEM']: #still expecting wps? if (len(self.wps_received) < self.num_wps_expected): #if we haven't already received this wp, write it to the GUI: if (m.seq not in self.wps_received.keys()): self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_MISS_ITEM, num=m.seq,command=m.command,param1=m.param1, param2=m.param2,param3=m.param3,param4=m.param4, lat=m.x,lon=m.y,alt=m.z,frame=m.frame)) self.wps_received[m.seq] = True if len(self.wps_received) == self.num_wps_expected: # if we have received everything then reset # our state to indicate we're not currently # expecting waypoints. That way if we receive # a count we don't expect we don't spew errors self.num_wps_expected = -1 def child_task(self, q, l, gq, gl, cw_sem, elemodel): '''child process - this holds GUI elements''' mp_util.child_close_fds() from MAVProxy.modules.lib import wx_processguard from ..lib.wx_loader import wx from MAVProxy.modules.mavproxy_misseditor import missionEditorFrame self.app = wx.App(False) self.app.frame = missionEditorFrame.MissionEditorFrame(self,parent=None,id=wx.ID_ANY, elemodel=elemodel) self.app.frame.set_event_queue(q) self.app.frame.set_event_queue_lock(l) self.app.frame.set_gui_event_queue(gq) self.app.frame.set_gui_event_queue_lock(gl) self.app.frame.set_close_window_semaphore(cw_sem) self.app.SetExitOnFrameDelete(True) self.app.frame.Show() # start a thread to monitor the "close window" semaphore: 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() watcher_thread = CloseWindowSemaphoreWatcher(self, cw_sem) watcher_thread.start() self.app.MainLoop() # tell the watcher it is OK to quit: cw_sem.release() watcher_thread.join() def close(self): '''close the Mission Editor window''' self.time_to_quit = True self.close_window.release() if self.child.is_alive(): self.child.join(1) self.child.terminate() self.mavlink_message_queue_handler.time_to_quit = True self.mavlink_message_queue_handler.join() self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_TIME_TO_QUIT)); self.event_queue_lock.release() self.needs_unloading = True def read_waypoints(self): self.module('wp').cmd_wp(['list']) def update_map_click_position(self, new_click_pos): self.gui_event_queue_lock.acquire() self.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_LAST_MAP_CLICK_POS,click_pos=new_click_pos)) self.gui_event_queue_lock.release() def set_layout(self, layout): self.object_queue.put(layout)
class MissionEditorMain(object): def __init__(self, mpstate, elemodel): pass def mavlink_message_queue_handler(self): pass def unload(self): '''unload module''' pass def get_wps_from_module(self): '''get WP list from wp module''' pass def idle_task(self): pass def mavlink_packet(self, m): pass def process_mavlink_packet(self, m): '''handle an incoming mavlink packet''' pass def child_task(self, q, l, gq, gl, cw_sem, elemodel): '''child process - this holds GUI elements''' pass class CloseWindowSemaphoreWatcher(threading.Thread): def __init__(self, mpstate, elemodel): pass def run(self): pass def close(self): '''close the Mission Editor window''' pass def read_waypoints(self): pass def update_map_click_position(self, new_click_pos): pass def set_layout(self, layout): pass
16
5
14
2
11
2
3
0.17
1
6
3
0
12
18
12
12
209
39
147
47
127
25
135
46
115
12
1
4
37
7,309
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_ntrip.py
MAVProxy.modules.mavproxy_ntrip.NtripModule
class NtripModule(mp_module.MPModule): def __init__(self, mpstate): super(NtripModule, self).__init__(mpstate, "ntrip", "ntrip", public=False) self.ntrip_settings = mp_settings.MPSettings( [('caster', str, None), ('port', int, 2101), ('username', str, 'IBS'), ('password', str, 'IBS'), ('mountpoint', str, None), ('logfile', str, None), ('sendalllinks', bool, False), ('frag_drop_pct', float, 0), ('sendmul', int, 1)]) self.add_command('ntrip', self.cmd_ntrip, 'NTRIP control', ["<status>", "<start>", "<stop>", "set (NTRIPSETTING)"]) self.add_completion_function('(NTRIPSETTING)', self.ntrip_settings.completion) self.pos = None self.pkt_count = 0 self.last_pkt = None self.last_restart = None self.last_rate = None self.rate_total = 0 self.ntrip = None self.start_pending = False self.rate = 0 self.logfile = None self.id_counts = {} self.last_by_id = {} def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' if msg.get_type() in ['GPS_RAW_INT', 'GPS2_RAW']: if msg.fix_type >= 3: self.pos = (msg.lat*1.0e-7, msg.lon*1.0e-7, msg.alt*1.0e-3) def log_rtcm(self, data): '''optionally log rtcm data''' if self.ntrip_settings.logfile is None: return if self.logfile is None: self.logfile = open(self.ntrip_settings.logfile, 'wb') if self.logfile is not None: self.logfile.write(data) def idle_task(self): '''called on idle''' if self.start_pending and self.ntrip is None and self.pos is not None: self.cmd_start() if self.ntrip is None: return data = self.ntrip.read() if data is None: now = time.time() if (self.last_pkt is not None and now - self.last_pkt > 15 and (self.last_restart is None or now - self.last_restart > 30)): print("NTRIP restart") self.ntrip = None self.start_pending = True self.last_restart = now return if time.time() - self.ntrip.dt_last_gga_sent > 2: self.ntrip.setPosition(self.pos[0], self.pos[1]) self.ntrip.send_gga() self.log_rtcm(data) rtcm_id = self.ntrip.get_ID() if not rtcm_id in self.id_counts: self.id_counts[rtcm_id] = 0 self.last_by_id[rtcm_id] = data[:] self.id_counts[rtcm_id] += 1 blen = len(data) if blen > 4*180: # can't send this with GPS_RTCM_DATA return total_len = blen self.rate_total += blen * self.ntrip_settings.sendmul if blen > 180: flags = 1 # fragmented else: flags = 0 # add in the sequence number flags |= (self.pkt_count & 0x1F) << 3 fragment = 0 while blen > 0: send_data = bytearray(data[:180]) frag_len = len(send_data) data = data[frag_len:] if frag_len < 180: send_data.extend(bytearray([0]*(180-frag_len))) if self.ntrip_settings.sendalllinks: links = self.mpstate.mav_master else: links = [self.master] for link in links: for d in range(self.ntrip_settings.sendmul): if random.random() * 100 < self.ntrip_settings.frag_drop_pct: continue link.mav.gps_rtcm_data_send(flags | (fragment<<1), frag_len, send_data) fragment += 1 blen -= frag_len self.pkt_count += 1 now = time.time() if now - self.last_rate > 1: dt = now - self.last_rate rate_now = self.rate_total / float(dt) self.rate = 0.9 * self.rate + 0.1 * rate_now self.last_rate = now self.rate_total = 0 self.last_pkt = now def cmd_ntrip(self, args): '''ntrip command handling''' if len(args) <= 0: print("Usage: ntrip <start|stop|status|set>") return if args[0] == "start": self.cmd_start() if args[0] == "stop": self.ntrip = None self.start_pending = False elif args[0] == "status": self.ntrip_status() elif args[0] == "set": self.ntrip_settings.command(args[1:]) def ntrip_status(self): '''show ntrip status''' now = time.time() if self.ntrip is None: print("ntrip: Not started") return elif self.last_pkt is None: print("ntrip: no data") return frame_size = 0 for id in sorted(self.id_counts.keys()): print(" %4u: %u (len %u)" % (id, self.id_counts[id], len(self.last_by_id[id]))) frame_size += len(self.last_by_id[id]) print("ntrip: %u packets, %.1f bytes/sec last %.1fs ago framesize %u" % (self.pkt_count, self.rate, now - self.last_pkt, frame_size)) def cmd_start(self): '''start ntrip link''' if self.ntrip_settings.caster is None: print("Require caster") return if self.ntrip_settings.mountpoint is None: print("Require mountpoint") return if self.pos is None: print("Start delayed pending position") self.start_pending = True return user = self.ntrip_settings.username + ":" + self.ntrip_settings.password self.ntrip = ntrip.NtripClient(user=user, port=self.ntrip_settings.port, caster=self.ntrip_settings.caster, mountpoint=self.ntrip_settings.mountpoint, lat=self.pos[0], lon=self.pos[1], height=self.pos[2]) print("NTRIP started") self.start_pending = False self.last_rate = time.time() self.rate_total = 0
class NtripModule(mp_module.MPModule): def __init__(self, mpstate): pass def mavlink_packet(self, msg): '''handle an incoming mavlink packet''' pass def log_rtcm(self, data): '''optionally log rtcm data''' pass def idle_task(self): '''called on idle''' pass def cmd_ntrip(self, args): '''ntrip command handling''' pass def ntrip_status(self): '''show ntrip status''' pass def cmd_start(self): '''start ntrip link''' pass
8
6
24
1
22
1
5
0.06
1
8
1
0
7
13
7
45
174
12
154
39
146
9
127
39
119
16
2
4
38
7,310
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/missionEditorFrame.py
MAVProxy.modules.mavproxy_misseditor.missionEditorFrame.MissionEditorFrame
class MissionEditorFrame(wx.Frame): def __init__(self, state, elemodel='SRTM3', *args, **kwds): # begin wxGlade: MissionEditorFrame.__init__ self.state = state kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.label_sync_state = wx.StaticText(self, wx.ID_ANY, "UNSYNCED \n", style=wx.ALIGN_CENTRE) self.label_wp_radius = wx.StaticText(self, wx.ID_ANY, "WP Radius") self.text_ctrl_wp_radius = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB) self.label_loiter_rad = wx.StaticText(self, wx.ID_ANY, "Loiter Radius") self.text_ctrl_loiter_radius = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB) self.checkbox_loiter_dir = wx.CheckBox(self, wx.ID_ANY, "CW") # The AGL checkbox is not yet implemented. # self.checkbox_agl = wx.CheckBox(self, wx.ID_ANY, "AGL") self.label_default_alt = wx.StaticText(self, wx.ID_ANY, "Default Alt") self.text_ctrl_wp_default_alt = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_PROCESS_ENTER | wx.TE_PROCESS_TAB) self.label_home_location = wx.StaticText(self, wx.ID_ANY, "Home Location") self.label_home_lat = wx.StaticText(self, wx.ID_ANY, "Lat") self.label_home_lat_value = wx.StaticText(self, wx.ID_ANY, "0.0") self.label_home_lon = wx.StaticText(self, wx.ID_ANY, "Lon") self.label_home_lon_value = wx.StaticText(self, wx.ID_ANY, "0.0") self.label_home_alt = wx.StaticText(self, wx.ID_ANY, "Alt (abs)") self.label_home_alt_value = wx.StaticText(self, wx.ID_ANY, "0.0") self.button_read_wps = wx.Button(self, wx.ID_ANY, "Read WPs") self.button_write_wps = wx.Button(self, wx.ID_ANY, "Write WPs") self.button_load_wp_file = wx.Button(self, wx.ID_ANY, "Load WP File") self.button_save_wp_file = wx.Button(self, wx.ID_ANY, "Save WP File") self.grid_mission = wx.grid.Grid(self, wx.ID_ANY, size=(1, 1)) self.button_add_wp = wx.Button(self, wx.ID_ANY, "Add Below") self.button_split = wx.Button(self, wx.ID_ANY, "Split") self.__set_properties() self.__do_layout() self.ElevationModel = mp_elevation.ElevationModel(database=elemodel) self.Bind(wx.EVT_TEXT_ENTER, self.on_wp_radius_enter, self.text_ctrl_wp_radius) self.Bind(wx.EVT_TEXT, self.on_wp_radius_changed, self.text_ctrl_wp_radius) self.Bind(wx.EVT_TEXT_ENTER, self.on_loiter_rad_enter, self.text_ctrl_loiter_radius) self.Bind(wx.EVT_TEXT, self.on_loiter_rad_change, self.text_ctrl_loiter_radius) self.Bind(wx.EVT_CHECKBOX, self.on_loiter_dir_cb_change, self.checkbox_loiter_dir) self.Bind(wx.EVT_TEXT_ENTER, self.on_wp_default_alt_enter, self.text_ctrl_wp_default_alt) self.Bind(wx.EVT_TEXT, self.on_wp_default_alt_change, self.text_ctrl_wp_default_alt) self.Bind(wx.EVT_BUTTON, self.read_wp_pushed, self.button_read_wps) self.Bind(wx.EVT_BUTTON, self.write_wp_pushed, self.button_write_wps) self.Bind(wx.EVT_BUTTON, self.load_wp_file_pushed, self.button_load_wp_file) self.Bind(wx.EVT_BUTTON, self.save_wp_file_pushed, self.button_save_wp_file) self.Bind(wx.grid.EVT_GRID_CMD_CELL_CHANGED, self.on_mission_grid_cell_changed, self.grid_mission) self.Bind(wx.grid.EVT_GRID_CMD_CELL_LEFT_CLICK, self.on_mission_grid_cell_left_click, self.grid_mission) self.Bind(wx.grid.EVT_GRID_CMD_SELECT_CELL, self.on_mission_grid_cell_select, self.grid_mission) self.Bind(wx.EVT_BUTTON, self.add_wp_below_pushed, self.button_add_wp) self.Bind(wx.EVT_BUTTON, self.split_pushed, self.button_split) # end wxGlade #use a timer to facilitate event an event handlers for events #passed from another process. self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.time_to_process_gui_events, self.timer) self.timer.Start(200) self.last_layout_send = time.time() self.Bind(wx.EVT_IDLE, self.on_idle) delete_br = button_renderer.ButtonRenderer("Delete",70,20) up_br = button_renderer.ButtonRenderer("+",20,20) down_br = button_renderer.ButtonRenderer("-",1,1) self.del_attr = wx.grid.GridCellAttr() self.del_attr.SetReadOnly(True) self.del_attr.SetRenderer(delete_br) self.up_attr = wx.grid.GridCellAttr() self.up_attr.SetReadOnly(True) self.up_attr.SetRenderer(up_br) self.down_attr = wx.grid.GridCellAttr() self.down_attr.SetReadOnly(True) self.down_attr.SetRenderer(down_br) self.read_only_attr = wx.grid.GridCellAttr() self.read_only_attr.SetReadOnly(True) self.grid_mission.SetColAttr(ME_DELETE_COL, self.del_attr) self.grid_mission.SetColAttr(ME_UP_COL, self.up_attr) self.grid_mission.SetColAttr(ME_DOWN_COL, self.down_attr) self.grid_mission.SetColAttr(ME_DIST_COL, self.read_only_attr) self.grid_mission.SetColAttr(ME_ANGLE_COL, self.read_only_attr) self.grid_mission.SetRowLabelSize(50) #remember what mission we opened/saved last self.last_mission_file_path = "" #remember last map click position self.last_map_click_pos = None def __set_properties(self): # begin wxGlade: MissionEditorFrame.__set_properties self.SetTitle("Mission Editor") self.SetSize((820, 480)) self.label_sync_state.SetForegroundColour(wx.Colour(255, 0, 0)) self.label_sync_state.SetFont(wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.NORMAL, 0, "Droid Sans")) self.text_ctrl_wp_radius.SetMinSize((50, 27)) self.text_ctrl_loiter_radius.SetMinSize((50, 27)) self.text_ctrl_wp_default_alt.SetMinSize((70, 27)) self.label_home_lat_value.SetMinSize((100, 17)) self.label_home_lat_value.SetForegroundColour(wx.Colour(0, 127, 255)) self.label_home_lon_value.SetMinSize((100, 17)) self.label_home_lon_value.SetForegroundColour(wx.Colour(0, 127, 255)) self.label_home_alt_value.SetForegroundColour(wx.Colour(0, 127, 255)) self.grid_mission.CreateGrid(0, 14) self.grid_mission.SetRowLabelSize(20) self.grid_mission.SetColLabelSize(20) self.grid_mission.SetColLabelValue(0, "Command") self.grid_mission.SetColSize(0, 150) self.grid_mission.SetColLabelValue(1, "P1") self.grid_mission.SetColLabelValue(2, "P2") self.grid_mission.SetColLabelValue(3, "P3") self.grid_mission.SetColLabelValue(4, "P4") self.grid_mission.SetColLabelValue(5, "Lat") self.grid_mission.SetColLabelValue(6, "Lon") self.grid_mission.SetColLabelValue(7, "Alt") self.grid_mission.SetColLabelValue(8, "Frame") self.grid_mission.SetColLabelValue(9, "Delete") self.grid_mission.SetColLabelValue(10, "Up") self.grid_mission.SetColLabelValue(11, "Down") self.grid_mission.SetDefaultColSize(-1) self.grid_mission.SetColLabelValue(12, "Distance") self.grid_mission.SetColLabelValue(13, "Grad (deg)") # end wxGlade def __do_layout(self): # begin wxGlade: MissionEditorFrame.__do_layout sizer_3 = wx.BoxSizer(wx.VERTICAL) sizer_16 = wx.BoxSizer(wx.HORIZONTAL) sizer_4 = wx.BoxSizer(wx.HORIZONTAL) sizer_12 = wx.BoxSizer(wx.VERTICAL) sizer_14 = wx.BoxSizer(wx.HORIZONTAL) sizer_13 = wx.BoxSizer(wx.HORIZONTAL) sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_11 = wx.BoxSizer(wx.HORIZONTAL) sizer_10 = wx.BoxSizer(wx.HORIZONTAL) sizer_2 = wx.BoxSizer(wx.HORIZONTAL) sizer_9 = wx.BoxSizer(wx.VERTICAL) sizer_5 = wx.BoxSizer(wx.VERTICAL) sizer_15 = wx.BoxSizer(wx.HORIZONTAL) sizer_4.Add(self.label_sync_state, 0, wx.LEFT | wx.ALIGN_CENTER_VERTICAL, 10) sizer_4.Add((10, 0), 0, 0, 0) sizer_5.Add(self.label_wp_radius, 0, 0, 0) sizer_5.Add(self.text_ctrl_wp_radius, 0, 0, 0) sizer_5.Add(self.label_loiter_rad, 0, 0, 0) sizer_15.Add(self.text_ctrl_loiter_radius, 0, 0, 0) sizer_15.Add(self.checkbox_loiter_dir, 0, 0, 0) sizer_5.Add(sizer_15, 1, wx.EXPAND, 0) sizer_4.Add(sizer_5, 0, wx.EXPAND, 0) sizer_4.Add((20, 20), 0, 0, 0) sizer_9.Add(self.label_default_alt, 0, 0, 0) sizer_9.Add(self.text_ctrl_wp_default_alt, 0, 0, 0) sizer_4.Add(sizer_9, 0, wx.EXPAND, 0) sizer_4.Add((20, 20), 0, 0, 0) sizer_1.Add(self.label_home_location, 0, 0, 0) sizer_2.Add(self.label_home_lat, 0, 0, 0) sizer_2.Add((40, 0), 0, 0, 0) sizer_2.Add(self.label_home_lat_value, 0, 0, 0) sizer_1.Add(sizer_2, 1, wx.EXPAND, 0) sizer_10.Add(self.label_home_lon, 0, 0, 0) sizer_10.Add((36, 0), 0, 0, 0) sizer_10.Add(self.label_home_lon_value, 0, 0, 0) sizer_1.Add(sizer_10, 1, wx.EXPAND, 0) sizer_11.Add(self.label_home_alt, 0, 0, 0) sizer_11.Add((11, 0), 0, 0, 0) sizer_11.Add(self.label_home_alt_value, 0, 0, 0) sizer_1.Add(sizer_11, 1, wx.EXPAND, 0) sizer_4.Add(sizer_1, 0, wx.EXPAND, 0) sizer_13.Add(self.button_read_wps, 0, 0, 0) sizer_13.Add((20, 20), 0, 0, 0) sizer_13.Add(self.button_write_wps, 0, 0, 0) sizer_12.Add(sizer_13, 1, wx.EXPAND, 0) sizer_12.Add((20, 20), 0, 0, 0) sizer_14.Add(self.button_load_wp_file, 0, 0, 0) sizer_14.Add((20, 20), 0, 0, 0) sizer_14.Add(self.button_save_wp_file, 0, 0, 0) sizer_12.Add(sizer_14, 1, wx.EXPAND, 0) sizer_4.Add(sizer_12, 0, wx.EXPAND, 0) sizer_3.Add(sizer_4, 0, wx.EXPAND, 0) sizer_3.Add(self.grid_mission, 1, wx.EXPAND, 0) sizer_16.Add(self.button_add_wp, 0, 0, 0) sizer_16.Add(self.button_split, 0, 0, 0) sizer_3.Add(sizer_16, 0, wx.EXPAND, 0) self.SetSizer(sizer_3) self.Layout() # end wxGlade def set_event_queue(self, q): self.event_queue = q def set_event_queue_lock(self, l): self.event_queue_lock = l def set_gui_event_queue(self, q): self.gui_event_queue = q def set_gui_event_queue_lock(self, l): self.gui_event_queue_lock = l def set_close_window_semaphore(self, sem): self.close_window_semaphore = sem def time_to_process_gui_events(self, evt): event_processed = False queue_access_start_time = time.time() self.gui_event_queue_lock.acquire() while (not self.gui_event_queue.empty()) and (time.time() < queue_access_start_time) < 0.6: event_processed = True event = self.gui_event_queue.get() try: self.process_gui_event(event) except Exception as e: print("Caught exception (%s)" % str(e)) self.gui_event_queue_lock.release() if (event_processed == True): #redraw window to apply changes self.Refresh() self.Update() def process_gui_event(self, event): if event.get_type() == me_event.MEGE_CLEAR_MISS_TABLE: self.grid_mission.ClearGrid() if (self.grid_mission.GetNumberRows() > 0): self.grid_mission.DeleteRows(0, self.grid_mission.GetNumberRows()) self.grid_mission.SetDefaultColSize(50, True) self.grid_mission.SetColSize(ME_COMMAND_COL, 150) self.grid_mission.SetColSize(ME_LAT_COL, 100) self.grid_mission.SetColSize(ME_LON_COL, 100) self.grid_mission.SetColSize(ME_ALT_COL, 75) self.grid_mission.SetColSize(ME_DIST_COL, 1) self.grid_mission.SetColSize(ME_ANGLE_COL, 1) self.grid_mission.ForceRefresh() elif event.get_type() == me_event.MEGE_ADD_MISS_TABLE_ROWS: num_new_rows = event.get_arg("num_rows") if (num_new_rows < 1): return old_num_rows = self.grid_mission.GetNumberRows() self.grid_mission.AppendRows(num_new_rows) self.prep_new_rows(old_num_rows, num_new_rows) self.grid_mission.ForceRefresh() elif event.get_type() == me_event.MEGE_SET_MISS_ITEM: row = event.get_arg("num") - 1 command = event.get_arg("command") if row == -1: #1st mission item is special: it's the immutable home position self.label_home_lat_value.SetLabel( str(event.get_arg("lat"))) self.label_home_lon_value.SetLabel( str(event.get_arg("lon"))) self.label_home_alt_value.SetLabel( str(event.get_arg("alt"))) else: #not the first mission item if command in me_defines.miss_cmds: self.grid_mission.SetCellValue(row, ME_COMMAND_COL, me_defines.miss_cmds[command]) else: self.grid_mission.SetCellValue(row, ME_COMMAND_COL, str(command)) self.grid_mission.SetCellValue(row, ME_P1_COL, str(event.get_arg("param1"))) self.grid_mission.SetCellValue(row, ME_P2_COL, str(event.get_arg("param2"))) self.grid_mission.SetCellValue(row, ME_P3_COL, str(event.get_arg("param3"))) self.grid_mission.SetCellValue(row, ME_P4_COL, str(event.get_arg("param4"))) self.grid_mission.SetCellValue(row, ME_LAT_COL, str(event.get_arg("lat"))) self.grid_mission.SetCellValue(row, ME_LON_COL, str(event.get_arg("lon"))) self.grid_mission.SetCellValue(row, ME_ALT_COL, "%.2f" % event.get_arg("alt")) self.set_grad_dist() frame_num = event.get_arg("frame") if frame_num in me_defines.frame_enum: self.grid_mission.SetCellValue(row, ME_FRAME_COL, me_defines.frame_enum[frame_num]) else: self.grid_mission.SetCellValue(row, ME_FRAME_COL, "Und") elif event.get_type() == me_event.MEGE_SET_WP_RAD: self.text_ctrl_wp_radius.SetValue(str(event.get_arg("wp_rad"))) self.text_ctrl_wp_radius.SetForegroundColour(wx.Colour(0, 0, 0)) elif event.get_type() == me_event.MEGE_SET_LOIT_RAD: loiter_radius = event.get_arg("loit_rad") self.text_ctrl_loiter_radius.SetValue( str(math.fabs(loiter_radius))) self.text_ctrl_loiter_radius.SetForegroundColour(wx.Colour(0, 0, 0)) if (loiter_radius < 0.0): self.checkbox_loiter_dir.SetValue(False) else: self.checkbox_loiter_dir.SetValue(True) elif event.get_type() == me_event.MEGE_SET_WP_DEFAULT_ALT: self.text_ctrl_wp_default_alt.SetValue(str( event.get_arg("def_wp_alt"))) self.text_ctrl_wp_default_alt.SetForegroundColour(wx.Colour(0, 0, 0)) elif event.get_type() == me_event.MEGE_SET_LAST_MAP_CLICK_POS: self.last_map_click_pos = event.get_arg("click_pos") def prep_new_row(self, row_num): command_choices = sorted(list(me_defines.miss_cmds.values())) cell_ed = DropdownCellEditor(command_choices) self.grid_mission.SetCellEditor(row_num, ME_COMMAND_COL, cell_ed) cell_ed.IncRef() self.grid_mission.SetCellValue(row_num, ME_COMMAND_COL, "NAV_WAYPOINT") for i in range(1, 7): self.grid_mission.SetCellValue(row_num, i, "0.0") for i in range(12, 14): self.grid_mission.SetCellValue(row_num, i, "0.0") #set altitude to default: self.grid_mission.SetCellValue(row_num, ME_ALT_COL, self.text_ctrl_wp_default_alt.GetValue()) #populate frm cell editor and set to default value frame_cell_ed = wx.grid.GridCellChoiceEditor(list(me_defines.frame_enum.values())) self.grid_mission.SetCellEditor(row_num, ME_FRAME_COL, frame_cell_ed) # default to previous rows frame if row_num > 0: frame = self.grid_mission.GetCellValue(row_num-1, ME_FRAME_COL) if frame not in ["Rel", "AGL"]: frame = "Rel" else: frame = "Rel" self.grid_mission.SetCellValue(row_num, ME_FRAME_COL, frame) #this makes newest row always have the cursor in it, #making the "Add Below" button work like I want: self.grid_mission.SetGridCursor(row_num, ME_COMMAND_COL) def prep_new_rows(self, start_row, num_rows): num_remaining = num_rows current_row = start_row while num_remaining > 0: self.prep_new_row(current_row) current_row = current_row + 1 num_remaining = num_remaining - 1 def set_modified_state(self, modified): if (modified): self.set_grad_dist() self.label_sync_state.SetLabel("MODIFIED") self.label_sync_state.SetForegroundColour(wx.Colour(255, 0, 0)) else: self.label_sync_state.SetLabel("SYNCED") self.label_sync_state.SetForegroundColour(wx.Colour(12, 152, 26)) def read_wp_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_READ_WPS)) #sneak in some queries about a few other items as well: self.event_queue.put(MissionEditorEvent(me_event.MEE_GET_WP_RAD)) self.event_queue.put(MissionEditorEvent(me_event.MEE_GET_LOIT_RAD)) self.event_queue.put(MissionEditorEvent(me_event.MEE_GET_WP_DEFAULT_ALT)) self.event_queue_lock.release() event.Skip() #TODO: the read actually has to succeed before I can say this: self.set_modified_state(False) def write_wp_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_WRITE_WPS,count= self.grid_mission.GetNumberRows()+1)) #home point first: lat = float(self.label_home_lat_value.GetLabel()) lon = float(self.label_home_lon_value.GetLabel()) alt = float(self.label_home_alt_value.GetLabel()) self.event_queue.put(MissionEditorEvent(me_event.MEE_WRITE_WP_NUM, num=0,cmd_id=16,p1=0.0,p2=0.0,p3=0.0,p4=0.0, lat=lat,lon=lon,alt=alt,frame=0)) for i in range(0, self.grid_mission.GetNumberRows()): cmd_id = me_defines.cmd_reverse_lookup(self.grid_mission.GetCellValue(i,0)) #don't lock up the misseditor on missing input! #anything missing will just be zero try: p1 = float(self.grid_mission.GetCellValue(i,ME_P1_COL)) except: p1 = 0.0 try: p2 = float(self.grid_mission.GetCellValue(i,ME_P2_COL)) except: p2 = 0.0 try: p3 = float(self.grid_mission.GetCellValue(i,ME_P3_COL)) except: p3 = 0.0 try: p4 = float(self.grid_mission.GetCellValue(i,ME_P4_COL)) except: p4 = 0.0 try: lat = float(self.grid_mission.GetCellValue(i,ME_LAT_COL)) except: lat = 0.0 try: lon = float(self.grid_mission.GetCellValue(i,ME_LON_COL)) except: lon = 0.0 try: alt = float(self.grid_mission.GetCellValue(i,ME_ALT_COL)) except: alt = 0.0 try: frame = float(me_defines.frame_enum_rev[self.grid_mission.GetCellValue(i,ME_FRAME_COL)]) except: frame = 0.0 self.event_queue.put(MissionEditorEvent(me_event.MEE_WRITE_WP_NUM, num=i+1,cmd_id=cmd_id,p1=p1,p2=p2,p3=p3,p4=p4, lat=lat,lon=lon,alt=alt,frame=frame)) self.event_queue_lock.release() self.set_modified_state(False) event.Skip() def load_wp_file_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> fd = wx.FileDialog(self, "Open Mission File", os.getcwd(), "", "MissionFiles(*.txt.*.wp,*.waypoints)|*.txt;*.wp;*.waypoints", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if (fd.ShowModal() == wx.ID_CANCEL): return #user changed their mind... self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_LOAD_WP_FILE, path=fd.GetPath())) self.event_queue_lock.release() self.last_mission_file_path = fd.GetPath() event.Skip() def add_wp_below_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> row_selected = self.grid_mission.GetGridCursorRow() if (row_selected < 0): row_selected = self.grid_mission.GetNumberRows()-1 self.grid_mission.InsertRows(row_selected+1) self.prep_new_row(row_selected+1) #set lat/lon based on last map click position: if self.last_map_click_pos is not None: self.grid_mission.SetCellValue(row_selected + 1, ME_LAT_COL, str(self.last_map_click_pos[0])) self.grid_mission.SetCellValue(row_selected + 1, ME_LON_COL, str(self.last_map_click_pos[1])) #highlight new row self.grid_mission.SelectRow(row_selected+1) self.set_modified_state(True) self.fix_jumps(row_selected+1, 1) event.Skip() def split_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> row_selected = self.grid_mission.GetGridCursorRow() if (row_selected < 2): print("Invalid row selected") event.Skip() return if self.grid_mission.GetCellValue(row_selected, ME_COMMAND_COL) != "NAV_WAYPOINT": print("Bad command (need NAV_WAYPOINT)") event.Skip() return if self.grid_mission.GetCellValue(row_selected-1, ME_COMMAND_COL) != "NAV_WAYPOINT": print("Bad previous command (need NAV_WAYPOINT)") event.Skip() return if (self.grid_mission.GetCellValue(row_selected, ME_FRAME_COL) != self.grid_mission.GetCellValue(row_selected-1, ME_FRAME_COL)): print("Items differ in frame") event.Skip() return lat = (float(self.grid_mission.GetCellValue(row_selected, ME_LAT_COL)) + float(self.grid_mission.GetCellValue(row_selected-1, ME_LAT_COL)))/2 lng = (float(self.grid_mission.GetCellValue(row_selected, ME_LON_COL)) + float(self.grid_mission.GetCellValue(row_selected-1, ME_LON_COL)))/2 alt = (float(self.grid_mission.GetCellValue(row_selected, ME_ALT_COL)) + float(self.grid_mission.GetCellValue(row_selected-1, ME_ALT_COL)))/2 self.grid_mission.InsertRows(row_selected) self.prep_new_row(row_selected) self.grid_mission.SetCellValue(row_selected, ME_LAT_COL, str(lat)) self.grid_mission.SetCellValue(row_selected, ME_LON_COL, str(lng)) self.grid_mission.SetCellValue(row_selected, ME_ALT_COL, str(alt)) #highlight new row self.grid_mission.SelectRow(row_selected) self.set_modified_state(True) self.fix_jumps(row_selected, 1) event.Skip() def save_wp_file_pushed(self, event): # wxGlade: MissionEditorFrame.<event_handler> fd = wx.FileDialog(self, "Save Mission File", os.getcwd(), os.path.basename(self.last_mission_file_path), "MissionFiles(*.txt.*.wp,*.waypoints)|*.txt;*.wp;*.waypoints", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if (fd.ShowModal() == wx.ID_CANCEL): return #user change their mind... #ask mp_misseditor module to save file self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_SAVE_WP_FILE, path=fd.GetPath())) self.event_queue_lock.release() self.last_mission_file_path = fd.GetPath() event.Skip() def on_mission_grid_cell_select(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.grid_mission.SetColLabelValue(ME_P1_COL, "P1") self.grid_mission.SetColLabelValue(ME_P2_COL, "P2") self.grid_mission.SetColLabelValue(ME_P3_COL, "P3") self.grid_mission.SetColLabelValue(ME_P4_COL, "P4") self.grid_mission.SetColLabelValue(ME_LAT_COL, "Lat") self.grid_mission.SetColLabelValue(ME_LON_COL, "Lon") self.grid_mission.SetColLabelValue(ME_ALT_COL, "Alt") self.grid_mission.SetColLabelValue(ME_DIST_COL, "Distance") self.grid_mission.SetColLabelValue(ME_ANGLE_COL, "Grad (deg)") if event.GetRow() == self.grid_mission.GetNumberRows(): # this event fires when last row is deleted; ignore # attempt to set a cell in that deleted row as selected. return command = self.grid_mission.GetCellValue(event.GetRow(), ME_COMMAND_COL) col_labels = me_defines.get_column_labels(command) for col in col_labels.keys(): self.grid_mission.SetColLabelValue(col, col_labels[col]) event.Skip() def on_mission_grid_cell_left_click(self, event): # wxGlade: MissionEditorFrame.<event_handler> #delete column? if (event.GetCol() == ME_DELETE_COL): row = event.GetRow() dlg = wx.MessageDialog(self, 'Sure you want to delete item ' + str(row+1) + '?', 'Really Delete?', wx.YES_NO | wx.ICON_EXCLAMATION) result = dlg.ShowModal() if (result == wx.ID_YES): #delete this row self.grid_mission.DeleteRows(row) self.set_modified_state(True) self.fix_jumps(row, -1) #up column? elif (event.GetCol() == ME_UP_COL): row = event.GetRow() if (row == 0): #can't go any higher return #insert a copy of this row above the previous row, then delete this row self.grid_mission.InsertRows(row-1) self.prep_new_row(row-1) for i in range(0, self.grid_mission.GetNumberCols()): self.grid_mission.SetCellValue(row-1, i, self.grid_mission.GetCellValue(row+1,i)) self.grid_mission.DeleteRows(row+1) #move the cursor to where the row moved and highlight the row self.grid_mission.SetGridCursor(row-1,ME_UP_COL) self.grid_mission.SelectRow(row-1) self.set_modified_state(True) #Return so we don't skip the event so the cursor will go where expected return #down column? elif (event.GetCol() == ME_DOWN_COL): row = event.GetRow() if (row == self.grid_mission.GetNumberRows() - 1): #can't go lower return #insert a copy of this row 2 rows down, then delete this row self.grid_mission.InsertRows(row+2) self.prep_new_row(row+2) for i in range(0, self.grid_mission.GetNumberCols()): self.grid_mission.SetCellValue(row+2, i, self.grid_mission.GetCellValue(row, i)) self.grid_mission.DeleteRows(row) #move the cursor to where the row moved and highlight the row self.grid_mission.SetGridCursor(row+1,ME_DOWN_COL) self.grid_mission.SelectRow(row+1) self.set_modified_state(True) #Return so we don't skip the event so the cursor will go where expected return event.Skip() def on_mission_grid_cell_changed(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.set_modified_state(True) event.Skip() def on_wp_radius_changed(self, event): # wxGlade: MissionEditorFrame.<event_handler> #change text red self.text_ctrl_wp_radius.SetForegroundColour(wx.Colour(255, 0, 0)) event.Skip() def on_wp_radius_enter(self, event): # wxGlade: MissionEditorFrame.<event_handler> try: wp_radius = float(self.text_ctrl_wp_radius.GetValue()) except Exception as e: print(str(e)) return #text back to black self.text_ctrl_wp_radius.SetForegroundColour(wx.Colour(0, 0, 0)) self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_SET_WP_RAD, rad=wp_radius)) self.event_queue_lock.release() event.Skip() def send_loiter_rad_msg(self): try: loit_radius = float(self.text_ctrl_loiter_radius.GetValue()) except Exception as e: print(str(e)) return if (not self.checkbox_loiter_dir.IsChecked()): loit_radius = loit_radius * -1.0 #text back to black self.text_ctrl_loiter_radius.SetForegroundColour(wx.Colour(0, 0, 0)) self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_SET_LOIT_RAD, rad=loit_radius)) self.event_queue_lock.release() def on_loiter_rad_enter(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.send_loiter_rad_msg() event.Skip() def on_loiter_rad_change(self, event): # wxGlade: MissionEditorFrame.<event_handler> #change text red self.text_ctrl_loiter_radius.SetForegroundColour(wx.Colour(255, 0, 0)) event.Skip() def on_loiter_dir_cb_change(self, event): # wxGlade: MissionEditorFrame.<event_handler> self.send_loiter_rad_msg() event.Skip() def on_wp_default_alt_enter(self, event): # wxGlade: MissionEditorFrame.<event_handler> try: def_alt = float(self.text_ctrl_wp_default_alt.GetValue()) except Exception as e: print(str(e)) return #text back to black self.text_ctrl_wp_default_alt.SetForegroundColour(wx.Colour(0, 0, 0)) self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_SET_WP_DEFAULT_ALT, alt=def_alt)) self.event_queue_lock.release() event.Skip() def on_wp_default_alt_change(self, event): # wxGlade: MissionEditorFrame.<event_handler> #change text red self.text_ctrl_wp_default_alt.SetForegroundColour(wx.Colour(255, 0, 0)) event.Skip() def fix_jumps(self, row_selected, delta): '''fix up jumps when we add/remove rows''' numrows = self.grid_mission.GetNumberRows() for row in range(numrows): command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL) if command in ["DO_JUMP", "DO_CONDITION_JUMP"]: p1 = int(float(self.grid_mission.GetCellValue(row, ME_P1_COL))) if p1 > row_selected and p1+delta>0: self.grid_mission.SetCellValue(row, ME_P1_COL, str(float(p1+delta))) def has_location_cmd(self, cmd_id): '''return True if a WP command has a location''' if isinstance(cmd_id, str): cmd_id = eval(f"mavutil.mavlink.MAV_CMD_{cmd_id}") 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 has_location(self, lat, lon, cmd_id): '''return True if a WP command has a location''' if lat == 0 and lon == 0: return False return self.has_location_cmd(cmd_id) def set_grad_dist(self): '''fix up distance and gradient when changing cell values''' home_def_alt = float(self.label_home_alt_value.GetLabel()) numrows = self.grid_mission.GetNumberRows() for row in range(1,numrows): command = self.grid_mission.GetCellValue(row, ME_COMMAND_COL) command_prev = self.grid_mission.GetCellValue(row - 1, ME_COMMAND_COL) lat = float(self.grid_mission.GetCellValue(row, ME_LAT_COL)) lon = float(self.grid_mission.GetCellValue(row, ME_LON_COL)) if not self.has_location(lat, lon, command): dist = 0.0 grad = 0.0 else : if "NAV" in command: row_prev = row - 1 while not self.has_location_cmd(command_prev) and (row_prev > 0): command_prev = self.grid_mission.GetCellValue(row_prev - 1, ME_COMMAND_COL) row_prev = row_prev - 1 prev_lat = float(self.grid_mission.GetCellValue(row_prev, ME_LAT_COL)) prev_lon = float(self.grid_mission.GetCellValue(row_prev, ME_LON_COL)) prev_alt = float(self.grid_mission.GetCellValue(row_prev, ME_ALT_COL)) if (self.grid_mission.GetCellValue(row_prev, ME_FRAME_COL) == "Rel"): prev_alt = prev_alt + home_def_alt elif (self.grid_mission.GetCellValue(row_prev, ME_FRAME_COL) == "AGL"): prev_alt = self.ElevationModel.GetElevation(prev_lat, prev_lon) + prev_alt while not self.has_location(prev_lat,prev_lon,command_prev) and (row_prev > 0): prev_lat = float(self.grid_mission.GetCellValue(row_prev - 1, ME_LAT_COL)) prev_lon = float(self.grid_mission.GetCellValue(row_prev - 1, ME_LON_COL)) command_prev = self.grid_mission.GetCellValue(row_prev - 1, ME_COMMAND_COL) row_prev = row_prev - 1 dist = mp_util.gps_distance(lat, lon, prev_lat, prev_lon) curr_alt = float(self.grid_mission.GetCellValue(row, ME_ALT_COL)) if (self.grid_mission.GetCellValue(row, ME_FRAME_COL) == "Rel"): curr_alt = curr_alt + home_def_alt elif(self.grid_mission.GetCellValue(row, ME_FRAME_COL) == "AGL"): curr_alt = curr_alt + self.ElevationModel.GetElevation(lat, lon) grad = math.atan2(curr_alt - prev_alt, dist) *180 / math.pi else: grad = 0.0 dist = 0.0 dist = format(dist, '.1f') grad = format(grad, '.1f') self.grid_mission.SetCellValue(row, ME_DIST_COL, str(dist)) self.grid_mission.SetCellValue(row, ME_ANGLE_COL, str(grad)) def on_idle(self, event): now = time.time() if now - self.last_layout_send > 1: self.last_layout_send = now self.event_queue.put(win_layout.get_wx_window_layout(self)) obj = None while not self.state.object_queue.empty(): obj = self.state.object_queue.get() if isinstance(obj, win_layout.WinLayout): win_layout.set_wx_window_layout(self, obj)
class MissionEditorFrame(wx.Frame): def __init__(self, state, elemodel='SRTM3', *args, **kwds): pass def __set_properties(self): pass def __do_layout(self): pass def set_event_queue(self, q): pass def set_event_queue_lock(self, l): pass def set_gui_event_queue(self, q): pass def set_gui_event_queue_lock(self, l): pass def set_close_window_semaphore(self, sem): pass def time_to_process_gui_events(self, evt): pass def process_gui_event(self, event): pass def prep_new_row(self, row_num): pass def prep_new_rows(self, start_row, num_rows): pass def set_modified_state(self, modified): pass def read_wp_pushed(self, event): pass def write_wp_pushed(self, event): pass def load_wp_file_pushed(self, event): pass def add_wp_below_pushed(self, event): pass def split_pushed(self, event): pass def save_wp_file_pushed(self, event): pass def on_mission_grid_cell_select(self, event): pass def on_mission_grid_cell_left_click(self, event): pass def on_mission_grid_cell_changed(self, event): pass def on_wp_radius_changed(self, event): pass def on_wp_radius_enter(self, event): pass def send_loiter_rad_msg(self): pass def on_loiter_rad_enter(self, event): pass def on_loiter_rad_change(self, event): pass def on_loiter_dir_cb_change(self, event): pass def on_wp_default_alt_enter(self, event): pass def on_wp_default_alt_change(self, event): pass def fix_jumps(self, row_selected, delta): '''fix up jumps when we add/remove rows''' pass def has_location_cmd(self, cmd_id): '''return True if a WP command has a location''' pass def has_location_cmd(self, cmd_id): '''return True if a WP command has a location''' pass def set_grad_dist(self): '''fix up distance and gradient when changing cell values''' pass def on_idle(self, event): pass
36
4
21
2
18
2
3
0.12
1
10
4
0
35
37
35
35
780
111
617
157
581
73
561
153
525
14
1
4
106
7,311
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipInfoImage
class SlipInfoImage(SlipInformation): '''an image to display in the info box''' def __init__(self, key, img): SlipInformation.__init__(self, key) self.imgstr = img.tostring() (self.width, self.height) = image_shape(img) self.imgpanel = None def img(self): '''return a wx image''' import wx with warnings.catch_warnings(): warnings.simplefilter('ignore') img = wx.EmptyImage(self.width, self.height) img.SetData(self.imgstr) return img def draw(self, parent, box): '''redraw the image''' import wx from MAVProxy.modules.lib import mp_widgets if self.imgpanel is None: self.imgpanel = mp_widgets.ImagePanel(parent, self.img()) box.Add(self.imgpanel, flag=wx.LEFT, border=0) box.Layout() def update(self, newinfo): '''update the image''' self.imgstr = newinfo.imgstr self.width = newinfo.width self.height = newinfo.height if self.imgpanel is not None: self.imgpanel.set_image(self.img())
class SlipInfoImage(SlipInformation): '''an image to display in the info box''' def __init__(self, key, img): pass def img(self): '''return a wx image''' pass def draw(self, parent, box): '''redraw the image''' pass def update(self, newinfo): '''update the image''' pass
5
4
7
0
6
1
2
0.15
1
2
1
0
4
4
4
7
33
3
26
12
18
4
26
12
18
2
1
1
6
7,312
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipInfoText
class SlipInfoText(SlipInformation): '''text to display in the info box''' def __init__(self, key, text): SlipInformation.__init__(self, key) self.text = text self.textctrl = None def _resize(self): '''calculate and set text size, handling multi-line''' lines = self.text.split('\n') xsize, ysize = 0, 0 for line in lines: size = self.textctrl.GetTextExtent(line) xsize = max(xsize, size[0]) ysize = ysize + size[1] xsize = int(xsize*1.2) self.textctrl.SetSize((xsize, ysize)) self.textctrl.SetMinSize((xsize, ysize)) def draw(self, parent, box): '''redraw the text''' import wx if self.textctrl is None: self.textctrl = wx.TextCtrl(parent, style=wx.TE_MULTILINE|wx.TE_READONLY) self.textctrl.WriteText(self.text) self._resize() box.Add(self.textctrl, flag=wx.LEFT, border=0) box.Layout() def update(self, newinfo): '''update the image''' self.text = newinfo.text if self.textctrl is not None: self.textctrl.Clear() self.textctrl.WriteText(self.text) self._resize()
class SlipInfoText(SlipInformation): '''text to display in the info box''' def __init__(self, key, text): pass def _resize(self): '''calculate and set text size, handling multi-line''' pass def draw(self, parent, box): '''redraw the text''' pass def update(self, newinfo): '''update the image''' pass
5
4
8
0
7
1
2
0.14
1
1
0
0
4
2
4
7
37
4
29
12
23
4
29
12
23
2
1
1
7
7,313
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipInformation
class SlipInformation: '''an object to display in the information box''' def __init__(self, key): self.key = key def draw(self, parent, box): '''default draw method''' pass def update(self, newinfo): '''update the information''' pass
class SlipInformation: '''an object to display in the information box''' def __init__(self, key): pass def draw(self, parent, box): '''default draw method''' pass def update(self, newinfo): '''update the information''' pass
4
3
3
0
2
1
1
0.43
0
0
0
2
3
1
3
3
12
2
7
5
3
3
7
5
3
1
0
0
3
7,314
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipKeyEvent
class SlipKeyEvent(SlipEvent): '''a key event sent to the parent''' def __init__(self, latlon, event, selected): SlipEvent.__init__(self, latlon, event, selected)
class SlipKeyEvent(SlipEvent): '''a key event sent to the parent''' def __init__(self, latlon, event, selected): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
2
4
0
3
2
1
1
3
2
1
1
1
0
1
7,315
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipLabel
class SlipLabel(SlipObject): '''a text label to display on the map''' def __init__(self, key, point, label, layer, colour, size=0.5): SlipObject.__init__(self, key, layer) self.point = point self.colour = colour self.label = label self.size = size def draw_label(self, img, pixmapper): pix1 = pixmapper(self.point) cv2.putText(img, self.label, pix1, cv2.FONT_HERSHEY_SIMPLEX, self.size, self.colour) def draw(self, img, pixmapper, bounds): if self.hidden: return self.draw_label(img, pixmapper) def bounds(self): '''return bounding box''' if self.hidden: return None return (self.point[0], self.point[1], 0, 0)
class SlipLabel(SlipObject): '''a text label to display on the map''' def __init__(self, key, point, label, layer, colour, size=0.5): pass def draw_label(self, img, pixmapper): pass def draw_label(self, img, pixmapper): pass def bounds(self): '''return bounding box''' pass
5
2
5
0
4
0
2
0.11
1
0
0
0
4
4
4
13
23
3
18
10
13
2
18
10
13
2
1
1
6
7,316
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipMenuEvent
class SlipMenuEvent(SlipEvent): '''a menu event sent to the parent''' def __init__(self, latlon, event, selected, menuitem): SlipEvent.__init__(self, latlon, event, selected) self.menuitem = menuitem
class SlipMenuEvent(SlipEvent): '''a menu event sent to the parent''' def __init__(self, latlon, event, selected, menuitem): pass
2
1
3
0
3
0
1
0.25
1
0
0
0
1
1
1
2
5
0
4
3
2
1
4
3
2
1
1
0
1
7,317
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipMouseEvent
class SlipMouseEvent(SlipEvent): '''a mouse event sent to the parent''' def __init__(self, latlon, event, selected): SlipEvent.__init__(self, latlon, event, selected)
class SlipMouseEvent(SlipEvent): '''a mouse event sent to the parent''' def __init__(self, latlon, event, selected): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
2
4
0
3
2
1
1
3
2
1
1
1
0
1
7,318
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/mission_editor.py
MAVProxy.modules.mavproxy_misseditor.mission_editor.MissionEditorEventThread
class MissionEditorEventThread(threading.Thread): def __init__(self, mp_misseditor, q, l): threading.Thread.__init__(self) self.mp_misseditor = mp_misseditor self.event_queue = q self.event_queue_lock = l self.time_to_quit = False def module(self, name): '''access another module''' return self.mp_misseditor.mpstate.module(name) def master(self): '''access master mavlink connection''' return self.mp_misseditor.mpstate.master() def run(self): while not self.time_to_quit: queue_access_start_time = time.time() self.event_queue_lock.acquire() request_read_after_processing_queue = False while (not self.event_queue.empty()) and (time.time() - queue_access_start_time) < 0.6: event = self.event_queue.get() if isinstance(event, win_layout.WinLayout): win_layout.set_layout(event, self.mp_misseditor.set_layout) elif isinstance(event, mavwp.MAVWPLoader): self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_CLEAR_MISS_TABLE)) self.mp_misseditor.gui_event_queue_lock.release() if event.count() > 0: self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_ADD_MISS_TABLE_ROWS,num_rows=event.count()-1)) self.mp_misseditor.gui_event_queue_lock.release() for m in event.wpoints: self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_MISS_ITEM, num=m.seq,command=m.command,param1=m.param1, param2=m.param2,param3=m.param3,param4=m.param4, lat=m.x,lon=m.y,alt=m.z,frame=m.frame)) self.mp_misseditor.gui_event_queue_lock.release() else: event_type = event.get_type() if event_type == me_event.MEE_READ_WPS: self.module('wp').cmd_wp(['list']) #list the rally points while I'm add it: #TODO: DON'T KNOW WHY THIS DOESN'T WORK #self.module('rally').cmd_rally(['list']) #means I'm doing a read & don't know how many wps to expect: self.mp_misseditor.num_wps_expected = -1 self.wps_received = {} elif event_type == me_event.MEE_TIME_TO_QUIT: self.time_to_quit = True elif event_type == me_event.MEE_GET_WP_RAD: wp_radius = self.module('param').mav_param.get('WP_RADIUS') if (wp_radius is None): continue self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_WP_RAD,wp_rad=wp_radius)) self.mp_misseditor.gui_event_queue_lock.release() elif event_type == me_event.MEE_SET_WP_RAD: self.mp_misseditor.param_set('WP_RADIUS',event.get_arg("rad")) elif event_type == me_event.MEE_GET_LOIT_RAD: loiter_radius = self.module('param').mav_param.get('WP_LOITER_RAD') if (loiter_radius is None): continue self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_LOIT_RAD,loit_rad=loiter_radius)) self.mp_misseditor.gui_event_queue_lock.release() elif event_type == me_event.MEE_SET_LOIT_RAD: loit_rad = event.get_arg("rad") if (loit_rad is None): continue self.mp_misseditor.param_set('WP_LOITER_RAD', loit_rad) #need to redraw rally points # Don't understand why this rally refresh isn't lagging... # likely same reason why "timeout setting WP_LOITER_RAD" #comes back: #TODO: fix timeout issue self.module('rally').set_last_change(time.time()) elif event_type == me_event.MEE_GET_WP_DEFAULT_ALT: self.mp_misseditor.gui_event_queue_lock.acquire() self.mp_misseditor.gui_event_queue.put(MissionEditorEvent( me_event.MEGE_SET_WP_DEFAULT_ALT,def_wp_alt=self.mp_misseditor.mpstate.settings.wpalt)) self.mp_misseditor.gui_event_queue_lock.release() elif event_type == me_event.MEE_SET_WP_DEFAULT_ALT: self.mp_misseditor.mpstate.settings.command(["wpalt",event.get_arg("alt")]) elif event_type == me_event.MEE_WRITE_WPS: self.module('wp').wploader.clear() self.module('wp').wploader.expected_count = event.get_arg("count") self.master().waypoint_count_send(event.get_arg("count")) self.mp_misseditor.num_wps_expected = event.get_arg("count") self.mp_misseditor.wps_received = {} elif event_type == me_event.MEE_WRITE_WP_NUM: w = mavutil.mavlink.MAVLink_mission_item_message( self.mp_misseditor.mpstate.settings.target_system, self.mp_misseditor.mpstate.settings.target_component, event.get_arg("num"), int(event.get_arg("frame")), event.get_arg("cmd_id"), 0, 1, event.get_arg("p1"), event.get_arg("p2"), event.get_arg("p3"), event.get_arg("p4"), event.get_arg("lat"), event.get_arg("lon"), event.get_arg("alt")) self.module('wp').wploader.add(w) wsend = self.module('wp').wploader.wp(w.seq) if self.mp_misseditor.mpstate.settings.wp_use_mission_int: wsend = self.module('wp').wp_to_mission_item_int(w) self.master().mav.send(wsend) #tell the wp module to expect some waypoints self.module('wp').loading_waypoints = True elif event_type == me_event.MEE_LOAD_WP_FILE: self.module('wp').cmd_wp(['load',event.get_arg("path")]) elif event_type == me_event.MEE_SAVE_WP_FILE: self.module('wp').cmd_wp(['save',event.get_arg("path")]) self.event_queue_lock.release() #if event processing operations require a mission referesh in GUI #(e.g., after a load or a verified-completed write): if (request_read_after_processing_queue): self.event_queue_lock.acquire() self.event_queue.put(MissionEditorEvent(me_event.MEE_READ_WPS)) self.event_queue_lock.release() #periodically re-request WPs that were never received: #DON'T NEED TO! -- wp module already doing this time.sleep(0.2)
class MissionEditorEventThread(threading.Thread): def __init__(self, mp_misseditor, q, l): pass def module(self, name): '''access another module''' pass def master(self): '''access master mavlink connection''' pass def run(self): pass
5
2
37
5
28
4
7
0.14
1
2
1
0
4
5
4
29
151
24
111
20
106
16
79
20
74
24
1
5
27
7,319
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipObject
class SlipObject: '''an object to display on the map''' def __init__(self, key, layer, popup_menu=None): self.key = key self.layer = str(layer) self.latlon = None self.popup_menu = popup_menu self.hidden = False self._timestamp_range = None def clip(self, px, py, w, h, img): '''clip an area for display on the map''' sx = 0 sy = 0 if px < 0: sx = -px w += px px = 0 if py < 0: sy = -py h += py py = 0 (width, height) = image_shape(img) if px+w > width: w = width - px if py+h > height: h = height - py return (px, py, sx, sy, w, h) def draw(self, img, pixmapper, bounds): '''default draw method''' pass def update_position(self, newpos): '''update object position''' if getattr(self, 'trail', None) is not None: self.trail.update_position(newpos) self.latlon = newpos.latlon if hasattr(self, 'rotation'): self.rotation = newpos.rotation def clicked(self, px, py): '''check if a click on px,py should be considered a click on the object. Return None if definitely not a click, otherwise return the distance of the click, smaller being nearer ''' return None def selection_info(self): '''extra selection information sent when object is selected''' return None def bounds(self): '''return bounding box or None''' return None def set_hidden(self, hidden): '''set hidden attribute''' self.hidden = hidden def set_time_range(self, trange): '''set timestamp range for display''' self._timestamp_range = trange
class SlipObject: '''an object to display on the map''' def __init__(self, key, layer, popup_menu=None): pass def clip(self, px, py, w, h, img): '''clip an area for display on the map''' pass def draw(self, img, pixmapper, bounds): '''default draw method''' pass def update_position(self, newpos): '''update object position''' pass def clicked(self, px, py): '''check if a click on px,py should be considered a click on the object. Return None if definitely not a click, otherwise return the distance of the click, smaller being nearer ''' pass def selection_info(self): '''extra selection information sent when object is selected''' pass def bounds(self): '''return bounding box or None''' pass def set_hidden(self, hidden): '''set hidden attribute''' pass def set_time_range(self, trange): '''set timestamp range for display''' pass
10
9
6
0
5
1
2
0.28
0
1
0
8
9
7
9
9
64
9
43
20
33
12
43
20
33
5
0
1
15
7,320
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipFlightModeLegend
class SlipFlightModeLegend(SlipObject): '''a legend to display in the map area''' def __init__(self, key, tuples, layer=1): SlipObject.__init__(self, key, layer) self.tuples = tuples self._img = None self.top_margin = 5 self.bottom_margin = 5 self.left_margin = 5 self.right_margin = 5 self.swatch_min_width = 5 self.swatch_min_height = 5 self.swatch_text_gap = 2 self.row_gap = 2 self.border_width = 1 self.border_colour = (255,0,0) self.text_colour = (0,0,0) self.font_scale = 0.5 def draw_legend(self): font = cv2.FONT_HERSHEY_SIMPLEX fontscale = self.font_scale width = 0 height = self.top_margin + self.bottom_margin row_height_max = self.swatch_min_height for (mode, colour) in self.tuples: if mode is None: mode = "Unknown" ((tw,th),tb) = cv2.getTextSize(mode, font, fontscale, 1) width = max(width, tw) row_height_max = max(row_height_max, th) row_count = len(self.tuples) height = self.top_margin + row_count*row_height_max + (row_count-1)*self.row_gap + self.bottom_margin swatch_height = max(self.swatch_min_height, row_height_max) swatch_width = max(self.swatch_min_width, swatch_height) width += self.left_margin + self.right_margin width += swatch_width + self.swatch_text_gap img = np.zeros((height,width,3),np.uint8) img[:] = (255,255,255) cv2.rectangle(img, (0, 0), (width-1, height-1), self.border_colour, self.border_width) y = self.top_margin for (mode, colour) in self.tuples: if mode is None: mode = "Unknown" x = self.left_margin cv2.rectangle(img, (x, y), (x+swatch_width-1, y+swatch_height-1), colour, -1) x += swatch_width x += self.swatch_text_gap cv2.putText(img, mode, (x, y+row_height_max), font, fontscale, self.text_colour) y += row_height_max + self.row_gap return img def draw(self, img, pixmapper, bounds): '''draw legend on the image''' if self._img is None: self._img = self.draw_legend() w = self._img.shape[1] h = self._img.shape[0] px = 5 py = 5 img[py:py+h,px:px+w] = self._img
class SlipFlightModeLegend(SlipObject): '''a legend to display in the map area''' def __init__(self, key, tuples, layer=1): pass def draw_legend(self): pass def draw_legend(self): '''draw legend on the image''' pass
4
2
20
1
19
0
3
0.03
1
0
0
0
3
14
3
12
64
4
58
35
54
2
57
35
53
5
1
2
8
7,321
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipFollow
class SlipFollow: '''enable/disable follow''' def __init__(self, enable): self.enable = enable
class SlipFollow: '''enable/disable follow''' def __init__(self, enable): 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
7,322
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipFollowObject
class SlipFollowObject: '''enable/disable follow for an object''' def __init__(self, key, enable): self.key = key self.enable = enable
class SlipFollowObject: '''enable/disable follow for an object''' def __init__(self, key, enable): pass
2
1
3
0
3
0
1
0.25
0
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
7,323
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipObjectSelection
class SlipObjectSelection: '''description of a object under the cursor during an event''' def __init__(self, objkey, distance, layer, extra_info=None): self.distance = distance self.objkey = objkey self.layer = str(layer) self.extra_info = extra_info
class SlipObjectSelection: '''description of a object under the cursor during an event''' def __init__(self, objkey, distance, layer, extra_info=None): pass
2
1
5
0
5
0
1
0.17
0
1
0
0
1
4
1
1
7
0
6
6
4
1
6
6
4
1
0
0
1
7,324
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipGrid
class SlipGrid(SlipObject): '''a map grid''' def __init__(self, key, layer, colour, linewidth): SlipObject.__init__(self, key, layer, ) self.colour = colour self.linewidth = linewidth def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pt1 = mp_util.constrain_latlon(pt1) pt2 = mp_util.constrain_latlon(pt2) pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: return cv2.line(img, pix1, pix2, colour, linewidth) def draw(self, img, pixmapper, bounds): '''draw a polygon on the image''' if self.hidden: return (lat,lon,w,h) = bounds # note that w and h are in degrees spacing = 1000 lat2 = mp_util.constrain(lat+h*0.5,-85,85) lon2 = mp_util.wrap_180(lon+w) dist = mp_util.gps_distance(lat2,lon,lat2,lon2) while True: count = int(dist / spacing) if count < 2: spacing /= 10.0 elif count > 50: spacing *= 10.0 else: break count += 10 start = mp_util.latlon_round((lat,lon), spacing) for i in range(count): # draw vertical lines of constant longitude pos1 = mp_util.gps_newpos(start[0], start[1], 90, i*spacing) pos3 = (pos1[0]+h*2, pos1[1]) self.draw_line(img, pixmapper, pos1, pos3, self.colour, self.linewidth) # draw horizontal lines of constant latitude pos1 = mp_util.gps_newpos(start[0], start[1], 0, i*spacing) pos3 = (pos1[0], pos1[1]+w*2) self.draw_line(img, pixmapper, pos1, pos3, self.colour, self.linewidth)
class SlipGrid(SlipObject): '''a map grid''' def __init__(self, key, layer, colour, linewidth): pass def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pass def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a polygon on the image''' pass
4
3
16
1
13
2
3
0.15
1
2
0
0
3
2
3
12
52
6
40
20
36
6
38
20
34
6
1
2
9
7,325
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipHideObject
class SlipHideObject: '''hide an object by key''' def __init__(self, key, hide): self.key = key self.hide = hide
class SlipHideObject: '''hide an object by key''' def __init__(self, key, hide): pass
2
1
3
0
3
0
1
0.25
0
0
0
0
1
2
1
1
5
0
4
4
2
1
4
4
2
1
0
0
1
7,326
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipPolygon
class SlipPolygon(SlipObject): '''a polygon to display on the map''' def __init__(self, key, points, layer, colour, linewidth, arrow = False, popup_menu=None, showlines=True): SlipObject.__init__(self, key, layer, popup_menu=popup_menu) self.points = points self.colour = colour self.linewidth = linewidth self.arrow = arrow self._bounds = mp_util.polygon_bounds(self.points) self._pix_points = [] self._selected_vertex = None self._has_timestamps = False self._showlines = showlines def set_colour(self, colour): self.colour = colour def bounds(self): '''return bounding box''' if self.hidden: return None return self._bounds def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pt1 = mp_util.constrain_latlon(pt1) pt2 = mp_util.constrain_latlon(pt2) pix1 = pixmapper(pt1) pix2 = pixmapper(pt2) (width, height) = image_shape(img) (ret, pix1, pix2) = cv2.clipLine((0, 0, width, height), pix1, pix2) if ret is False: if len(self._pix_points) == 0: self._pix_points.append(None) self._pix_points.append(None) return if self._showlines: cv2.line(img, pix1, pix2, colour, linewidth) cv2.circle(img, pix2, linewidth*2, colour) if len(self._pix_points) == 0: self._pix_points.append(pix1) self._pix_points.append(pix2) if self.arrow: xdiff = pix2[0]-pix1[0] ydiff = pix2[1]-pix1[1] if (xdiff*xdiff + ydiff*ydiff) > 400: # the segment is longer than 20 pix SlipArrow(self.key, self.layer, (int(pix1[0]+xdiff/2.0), int(pix1[1]+ydiff/2.0)), self.colour, self.linewidth, math.atan2(ydiff, xdiff)+math.pi/2.0).draw(img) def draw(self, img, pixmapper, bounds): '''draw a polygon on the image''' if self.hidden: return self._has_timestamps = len(self.points) > 0 and len(self.points[0]) > 3 self._pix_points = [] for i in range(len(self.points)-1): if len(self.points[i]) > 2: colour = self.points[i][2] else: colour = self.colour if len(self.points[i]) > 3: timestamp = self.points[i][3] if self._timestamp_range is not None: if timestamp < self._timestamp_range[0] or timestamp > self._timestamp_range[1]: continue self.draw_line(img, pixmapper, self.points[i], self.points[i+1], colour, self.linewidth) def clicked(self, px, py): '''see if the polygon has been clicked on. Consider it clicked if the pixel is within 6 of the point ''' if self.hidden: return None num_points = len(self._pix_points) if num_points <= 0: return None for idx in range(num_points): # the odd ordering here is to that the home point, which is index 0, is checked last # as home cannot be moved i = (idx+1) % num_points if self._pix_points[i] is None: continue (pixx,pixy) = self._pix_points[i] if abs(px - pixx) < 6 and abs(py - pixy) < 6: self._selected_vertex = i return math.sqrt((px - pixx)**2 + (py - pixy)**2) return None def selection_info(self): '''extra selection information sent when object is selected''' return self._selected_vertex
class SlipPolygon(SlipObject): '''a polygon to display on the map''' def __init__(self, key, points, layer, colour, linewidth, arrow = False, popup_menu=None, showlines=True): pass def set_colour(self, colour): pass def bounds(self): '''return bounding box''' pass def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a line on the image''' pass def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth): '''draw a polygon on the image''' pass def clicked(self, px, py): '''see if the polygon has been clicked on. Consider it clicked if the pixel is within 6 of the point ''' pass def selection_info(self): '''extra selection information sent when object is selected''' pass
8
6
12
0
11
1
4
0.14
1
3
1
1
7
9
7
16
92
6
76
30
68
11
73
30
65
7
1
4
25
7,327
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipEvent
class SlipEvent: '''an event sent to the parent. latlon = (lat,lon) of mouse on map event = wx event objkeys = list of SlipObjectSelection selections ''' def __init__(self, latlon, event, selected): self.latlon = latlon self.event = mp_util.object_container(event) self.selected = selected
class SlipEvent: '''an event sent to the parent. latlon = (lat,lon) of mouse on map event = wx event objkeys = list of SlipObjectSelection selections ''' def __init__(self, latlon, event, selected): pass
2
1
4
0
4
0
1
1
0
1
1
3
1
3
1
1
11
1
5
5
3
5
5
5
3
1
0
0
1
7,328
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipPosition
class SlipPosition: '''an position object to move an existing object on the map''' def __init__(self, key, latlon, layer='', rotation=0, label=None, colour=None): self.key = key self.layer = str(layer) self.latlon = latlon self.rotation = rotation self.label = label self.colour = colour
class SlipPosition: '''an position object to move an existing object on the map''' def __init__(self, key, latlon, layer='', rotation=0, label=None, colour=None): pass
2
1
7
0
7
0
1
0.13
0
1
0
0
1
6
1
1
9
0
8
8
6
1
8
8
6
1
0
0
1
7,329
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipIcon
class SlipIcon(SlipThumbnail): '''a icon to display on the map''' def __init__(self, key, latlon, img, layer=1, rotation=0, follow=False, trail=None, popup_menu=None, label=None, colour=(255,255,255)): SlipThumbnail.__init__(self, key, latlon, layer, img, popup_menu=popup_menu) self.rotation = rotation self.follow = follow self.trail = trail self.label = label self.colour = colour # label colour def img(self): '''return a cv image for the icon''' SlipThumbnail.img(self) if self.rotation: # rotate the image mat = cv2.getRotationMatrix2D((self.height//2, self.width//2), -self.rotation, 1.0) self._rotated = cv2.warpAffine(self._img, mat, (self.height, self.width)) else: self._rotated = self._img return self._rotated def draw(self, img, pixmapper, bounds): '''draw the icon on the image''' if self.hidden: return if self.trail is not None: self.trail.draw(img, pixmapper, bounds) icon = self.img() (px,py) = pixmapper(self.latlon) # find top left (w, h) = image_shape(icon) px -= w//2 py -= h//2 (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img) img[py:py + h, px:px + w] = cv2.add(img[py:py+h, px:px+w], icon[sy:sy+h, sx:sx+w]) if self.label is not None: cv2.putText(img, self.label, (px,py), cv2.FONT_HERSHEY_SIMPLEX, 1.0, self.colour) # remember where we placed it for clicked() self.posx = px+w//2 self.posy = py+h//2
class SlipIcon(SlipThumbnail): '''a icon to display on the map''' def __init__(self, key, latlon, img, layer=1, rotation=0, follow=False, trail=None, popup_menu=None, label=None, colour=(255,255,255)): pass def img(self): '''return a cv image for the icon''' pass def draw(self, img, pixmapper, bounds): '''draw the icon on the image''' pass
4
3
15
3
11
2
2
0.21
1
0
0
0
3
8
3
17
50
11
33
18
28
7
31
17
27
4
2
1
7
7,330
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipThumbnail
class SlipThumbnail(SlipObject): '''a thumbnail to display on the map''' def __init__(self, key, latlon, layer, img, border_colour=None, border_width=0, popup_menu=None): SlipObject.__init__(self, key, layer, popup_menu=popup_menu) self.latlon = latlon self._img = None if isinstance(img, str): img = mp_tile.mp_icon(img) if not hasattr(img, 'shape'): img = np.asarray(img[:,:]) self.original_img = img (self.width, self.height) = image_shape(img) self.border_width = border_width self.border_colour = border_colour self.posx = -1 self.posy = -1 def bounds(self): '''return bounding box''' if self.hidden: return None return (self.latlon[0], self.latlon[1], 0, 0) def img(self): '''return a cv image for the thumbnail''' if self._img is not None: return self._img self._img = cv2.cvtColor(self.original_img, cv2.COLOR_BGR2RGB) if self.border_width and self.border_colour is not None: cv2.rectangle(self._img, (0, 0), (self.width-1, self.height-1), self.border_colour, self.border_width) return self._img def draw(self, img, pixmapper, bounds): '''draw the thumbnail on the image''' if self.hidden: return thumb = self.img() (px,py) = pixmapper(self.latlon) # find top left (w, h) = image_shape(thumb) px -= w//2 py -= h//2 (px, py, sx, sy, w, h) = self.clip(px, py, w, h, img) thumb_roi = thumb[sy:sy+h, sx:sx+w] img[py:py+h, px:px+w] = thumb_roi # remember where we placed it for clicked() self.posx = px+w//2 self.posy = py+h//2 def clicked(self, px, py): '''see if the image has been clicked on''' if self.hidden: return None if (abs(px - self.posx) > self.width/2 or abs(py - self.posy) > self.height/2): return None return math.sqrt((px-self.posx)**2 + (py-self.posy)**2)
class SlipThumbnail(SlipObject): '''a thumbnail to display on the map''' def __init__(self, key, latlon, layer, img, border_colour=None, border_width=0, popup_menu=None): pass def bounds(self): '''return bounding box''' pass def img(self): '''return a cv image for the thumbnail''' pass def draw(self, img, pixmapper, bounds): '''draw the thumbnail on the image''' pass def clicked(self, px, py): '''see if the image has been clicked on''' pass
6
5
12
1
10
1
3
0.14
1
1
0
1
5
9
5
14
64
8
49
21
41
7
45
19
39
3
1
1
13
7,331
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/missionEditorFrame.py
MAVProxy.modules.mavproxy_misseditor.missionEditorFrame.ListCtrlComboPopup
class ListCtrlComboPopup(wx.ComboPopup): def __init__(self): wx.ComboPopup.__init__(self) self.lc = None def AddItem(self, txt): self.lc.InsertItem(self.lc.GetItemCount(), txt) def OnMotion(self, evt): item, flags = self.lc.HitTest(evt.GetPosition()) if item >= 0: self.lc.Select(item) self.curitem = item def OnLeftDown(self, evt): self.value = self.curitem self.Dismiss() # This is called immediately after construction finishes. You can # use self.GetCombo if needed to get to the ComboCtrl instance. def Init(self): self.value = -1 self.curitem = -1 # Create the popup child control. Return true for success. def Create(self, parent): self.lc = wx.ListCtrl(parent, style=wx.LC_SINGLE_SEL | wx.SIMPLE_BORDER | wx.LC_REPORT | wx.LC_NO_HEADER) self.lc.InsertColumn(0, '') self.lc.Bind(wx.EVT_MOTION, self.OnMotion) self.lc.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown) return True # Return the widget that is to be used for the popup def GetControl(self): return self.lc # Called just prior to displaying the popup, you can use it to # 'select' the current item. def SetStringValue(self, val): idx = self.lc.FindItem(-1, val) if idx != wx.NOT_FOUND: self.lc.Select(idx) def FindString(self, val): idx = self.lc.FindItem(-1, val) if idx == wx.NOT_FOUND: idx = 0 return idx # Return a string representation of the current item. def GetStringValue(self): if self.value >= 0: return self.lc.GetItemText(self.value) return "" # Called immediately after the popup is shown def OnPopup(self): self.lc.SetColumnWidth(0, wx.LIST_AUTOSIZE) wx.ComboPopup.OnPopup(self) # Called when popup is dismissed def OnDismiss(self): wx.ComboPopup.OnDismiss(self) # This is called to custom paint in the combo control itself # (ie. not the popup). Default implementation draws value as # string. def PaintComboControl(self, dc, rect): wx.ComboPopup.PaintComboControl(self, dc, rect) # Receives key events from the parent ComboCtrl. Events not # handled should be skipped, as usual. def OnComboKeyEvent(self, event): wx.ComboPopup.OnComboKeyEvent(self, event) # Implement if you need to support special action when user # double-clicks on the parent wxComboCtrl. def OnComboDoubleClick(self): wx.ComboPopup.OnComboDoubleClick(self) # Return final size of popup. Called on every popup, just prior to OnPopup. # minWidth = preferred minimum width for window # prefHeight = preferred height. Only applies if > 0, # maxHeight = max height for window, as limited by screen size # and should only be rounded down, if necessary. def GetAdjustedSize(self, minWidth, prefHeight, maxHeight): return wx.ComboPopup.GetAdjustedSize(self, minWidth, prefHeight, maxHeight) # Return true if you want delay the call to Create until the popup # is shown for the first time. It is more efficient, but note that # it is often more convenient to have the control created # immediately. # Default returns false. def LazyCreate(self): return wx.ComboPopup.LazyCreate(self)
class ListCtrlComboPopup(wx.ComboPopup): def __init__(self): pass def AddItem(self, txt): pass def OnMotion(self, evt): pass def OnLeftDown(self, evt): pass def Init(self): pass def Create(self, parent): pass def GetControl(self): pass def SetStringValue(self, val): pass def FindString(self, val): pass def GetStringValue(self): pass def OnPopup(self): pass def OnDismiss(self): pass def PaintComboControl(self, dc, rect): pass def OnComboKeyEvent(self, event): pass def OnComboDoubleClick(self): pass def GetAdjustedSize(self, minWidth, prefHeight, maxHeight): pass def LazyCreate(self): pass
18
0
3
0
3
0
1
0.49
1
0
0
0
17
3
17
17
96
17
53
24
35
26
53
24
35
2
1
1
21
7,332
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/missionEditorFrame.py
MAVProxy.modules.mavproxy_misseditor.missionEditorFrame.DropdownCellEditor
class DropdownCellEditor(grid.GridCellEditor): def __init__(self, choices): super().__init__() self.choices = choices def Create(self, parent, id, evtHandler): self.control = wx.ComboCtrl(parent, id, "", style=wx.CB_READONLY) self.popupCtrl = ListCtrlComboPopup() self.control.SetPopupControl(self.popupCtrl) for choice in self.choices: self.popupCtrl.AddItem(choice) self.SetControl(self.control) def Clone(self): return DropdownCellEditor(self.choices) def BeginEdit(self, row, col, grid): self.startValue = grid.GetTable().GetValue(row, col) self.control.SetValue(self.startValue) def EndEdit(self, row, col, grid, oldval): self.endValue = self.popupCtrl.GetStringValue() if self.endValue != oldval and self.endValue != "": return self.endValue else: return None def ApplyEdit(self, row, col, grid): self.control.SetValue(self.endValue) grid.GetTable().SetValue(row, col, self.endValue) def Reset(self): self.control.SetValue(self.startValue)
class DropdownCellEditor(grid.GridCellEditor): def __init__(self, choices): pass def Create(self, parent, id, evtHandler): pass def Clone(self): pass def BeginEdit(self, row, col, grid): pass def EndEdit(self, row, col, grid, oldval): pass def ApplyEdit(self, row, col, grid): pass def Reset(self): pass
8
0
4
0
4
0
1
0
1
2
1
0
7
5
7
7
33
6
27
14
19
0
26
14
18
2
1
1
9
7,333
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/me_event.py
MAVProxy.modules.mavproxy_misseditor.me_event.MissionEditorEvent
class MissionEditorEvent: def __init__(self, type, **kwargs): self.type = type self.arg_dict = kwargs if not self.type in [MEE_READ_WPS, MEE_WRITE_WPS, MEGE_CLEAR_MISS_TABLE, MEGE_ADD_MISS_TABLE_ROWS, MEGE_SET_MISS_ITEM, MEE_TIME_TO_QUIT, MEE_GET_WP_RAD, MEE_GET_LOIT_RAD, MEGE_SET_WP_RAD, MEGE_SET_LOIT_RAD, MEE_GET_WP_DEFAULT_ALT, MEGE_SET_WP_DEFAULT_ALT, MEE_WRITE_WP_NUM, MEE_LOAD_WP_FILE, MEE_SAVE_WP_FILE, MEE_SET_WP_RAD, MEE_SET_LOIT_RAD, MEE_SET_WP_DEFAULT_ALT]: raise TypeError("Unrecongized MissionEditorEvent type:" + str(self.type)) def get_type(self): return self.type def get_arg(self, key): if not key in self.arg_dict: print("No key %s in %s" % (key, str(self.type))) return None return self.arg_dict[key]
class MissionEditorEvent: def __init__(self, type, **kwargs): pass def get_type(self): pass def get_arg(self, key): pass
4
0
6
0
6
0
2
0
0
2
0
0
3
2
3
3
21
3
18
6
14
0
13
6
9
2
0
1
5
7,334
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/button_renderer.py
MAVProxy.modules.mavproxy_misseditor.button_renderer.ButtonRenderer
class ButtonRenderer(wx.grid.PyGridCellRenderer): def __init__(self,label,width=75,height=25): self.label = label self.width = width self.height = height wx.grid.PyGridCellRenderer.__init__(self) def Clone(self): return copy.copy(self) def GetBestSize(self, grid, dc, row, col): return wx.Size(self.width,self.height) def Draw(self, grid, attr, dc, rect, row, col, isSelected): dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNFACE))) dc.DrawRectangle( rect.GetX(), rect.GetY(), rect.GetWidth(), rect.GetHeight()) #draw a shaded rectangle to emulate a button #(taken from src/generic/renderg.cpp) strength = 1 pen1 = wx.Pen(wx.WHITE, strength) dc.SetPen(pen1) dc.DrawLine(rect.GetLeft()+strength-1, rect.GetTop()+strength-1, rect.GetLeft()+strength-1, rect.GetBottom()-strength+1) dc.DrawLine(rect.GetLeft()+strength-1, rect.GetTop()+strength-1, rect.GetRight()-strength, rect.GetTop()+strength-1) pen2 = wx.Pen(wx.BLACK, strength) dc.SetPen(pen2) dc.DrawLine(rect.GetRight()-strength, rect.GetTop(), rect.GetRight()-strength, rect.GetBottom()); dc.DrawLine(rect.GetLeft(), rect.GetBottom(), rect.GetRight() - strength, rect.GetBottom()); ''' #another drawing routine #(taken from src/generic/renderg.cpp) #Could port this later for animating the button when clicking const wxCoord x = rect.x, y = rect.y, w = rect.width, h = rect.height; dc.SetBrush(*wxTRANSPARENT_BRUSH); wxPen pen(*wxBLACK, 1); dc.SetPen(pen); dc.DrawLine( x+w, y, x+w, y+h ); // right (outer) dc.DrawRectangle( x, y+h, w+1, 1 ); // bottom (outer) pen.SetColour(wxColour(wxT("DARK GREY"))); dc.SetPen(pen); dc.DrawLine( x+w-1, y, x+w-1, y+h ); // right (inner) dc.DrawRectangle( x+1, y+h-1, w-2, 1 ); // bottom (inner) pen.SetColour(*wxWHITE); dc.SetPen(pen); dc.DrawRectangle( x, y, w, 1 ); // top (outer) dc.DrawRectangle( x, y, 1, h ); // left (outer) dc.DrawLine( x, y+h-1, x+1, y+h-1 ); dc.DrawLine( x+w-1, y, x+w-1, y+1 ); ''' # draw the button-label dc.SetBackgroundMode(wx.TRANSPARENT ) dc.SetTextForeground(attr.GetTextColour() ) dc.SetFont( attr.GetFont() ) #dc.DrawLabel( wxT("Delete"), rect, dc.DrawLabel( self.label, rect, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL)
class ButtonRenderer(wx.grid.PyGridCellRenderer): def __init__(self,label,width=75,height=25): pass def Clone(self): pass def GetBestSize(self, grid, dc, row, col): pass def Draw(self, grid, attr, dc, rect, row, col, isSelected): pass
5
0
17
2
8
7
1
0.88
1
0
0
0
4
3
4
4
72
12
32
11
27
28
26
11
21
1
1
0
4
7,335
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misseditor/__init__.py
MAVProxy.modules.mavproxy_misseditor.MissionEditorModule
class MissionEditorModule(mp_module.MPModule): ''' A Mission Editor for use with MAVProxy ''' def __init__(self, mpstate): super(MissionEditorModule, self).__init__(mpstate, "misseditor", "mission editor", public = True) # to work around an issue on MacOS this module is a thin wrapper around a separate MissionEditorMain object from MAVProxy.modules.mavproxy_misseditor import mission_editor self.me_main = mission_editor.MissionEditorMain(mpstate, self.module('terrain').ElevationModel.database) def unload(self): '''unload module''' self.me_main.unload() def idle_task(self): self.me_main.idle_task() if self.me_main.needs_unloading: self.needs_unloading = True def mavlink_packet(self, m): self.me_main.mavlink_packet(m) def click_updated(self): self.me_main.update_map_click_position(self.mpstate.click_location)
class MissionEditorModule(mp_module.MPModule): ''' A Mission Editor for use with MAVProxy ''' def __init__(self, mpstate): pass def unload(self): '''unload module''' pass def idle_task(self): pass def mavlink_packet(self, m): pass def click_updated(self): pass
6
2
3
0
3
0
1
0.33
1
2
1
0
5
2
5
43
25
5
15
9
8
5
15
9
8
2
2
1
6
7,336
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misc.py
MAVProxy.modules.mavproxy_misc.RepeatCommand
class RepeatCommand(object): '''repeated command object''' def __init__(self, period, cmd): self.period = period self.cmd = cmd self.event = mavutil.periodic_event(1.0/period) def __str__(self): return "Every %.1f seconds: %s" % (self.period, self.cmd)
class RepeatCommand(object): '''repeated command object''' def __init__(self, period, cmd): pass def __str__(self): pass
3
1
3
0
3
0
1
0.14
1
0
0
0
2
3
2
2
9
1
7
6
4
1
7
6
4
1
1
0
2
7,337
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipRemoveObject
class SlipRemoveObject: '''remove an object by key''' def __init__(self, key): self.key = key
class SlipRemoveObject: '''remove an object by key''' def __init__(self, key): 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
7,338
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_messagerate.py
MAVProxy.modules.mavproxy_messagerate.messagerate
class messagerate(mp_module.MPModule): def __init__(self, mpstate): """Initialise module""" super(messagerate, self).__init__(mpstate, "messagerate", "") self.counts = {} self.buckets = [] self.max_buckets = 5 self.last_calc = time.time() self.add_command('messagerate', self.cmd_messagerate, "messagerate module", ['status', 'reset', 'set', 'get']) def usage(self): '''show help on command line options''' return "Usage: messagerate <status | reset | set(msg)(rate) | get(msg)>" def cmd_messagerate(self, args): '''control behaviour of the module''' if len(args) == 0: print(self.usage()) elif args[0] == "status": print(self.status()) elif args[0] == "reset": self.reset() elif args[0] == "get": if len(args) != 2: print(self.usage()) return message_name = args[1] mavlink_map = mavutil.mavlink.mavlink_map for msg_id in mavlink_map.keys(): msg_type = mavlink_map[msg_id] mav_cmd_name = msg_type.msgname if hasattr(msg_type, "msgname") else msg_type.name if mav_cmd_name == message_name: self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_GET_MESSAGE_INTERVAL, 0, msg_id, 0, 0, 0, 0, 0, 0) return print("Unknown message ID:%s" % message_name) elif args[0] == "set": if len(args) < 3: print(self.usage()) return message_name = args[1] message_rate = float(args[2]) # Special handling for -1 and 0 which correspond to "stop sending" and "reset to default rate" message_rate = message_rate if message_rate <= 0 else 1E6/message_rate priority = 0 if len(args) > 3: priority = int(args[3]) mavlink_map = mavutil.mavlink.mavlink_map for msg_id in mavlink_map.keys(): msg_type = mavlink_map[msg_id] mav_cmd_name = msg_type.msgname if hasattr(msg_type, "msgname") else msg_type.name if mav_cmd_name == message_name: self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_SET_MESSAGE_INTERVAL, 0, msg_id, (int) (message_rate), priority, 0, 0, 0, 0) return print("Unknown message ID:%s" % message_name) else: print(self.usage()) def reset(self): '''reset rates''' self.counts = {} self.buckets = [] self.last_calc = time.time() def status(self): '''returns rates''' counts = {} for bucket in self.buckets: for x in bucket: if not x in counts: counts[x] = 0 counts[x] += bucket[x] ret = "" mtypes = counts.keys() mtypes = sorted(mtypes) for mtype in mtypes: ret += "%s: %0.1f/s\n" % (mtype, counts[mtype]/float(len(self.buckets))) return ret def idle_task(self): '''called rapidly by mavproxy''' now = time.time() time_delta = now - self.last_calc if time_delta > 1: self.last_calc = now self.buckets.append(self.counts) self.counts = {} if len(self.buckets) > self.max_buckets: self.buckets = self.buckets[-self.max_buckets:] def mavlink_packet(self, m): '''handle mavlink packets''' mtype = m.get_type() if mtype not in self.counts: self.counts[mtype] = 0 self.counts[mtype] += 1 mavlink_map = mavutil.mavlink.mavlink_map if mtype == 'MESSAGE_INTERVAL': if m.message_id in mavlink_map: msg_type = mavlink_map[m.message_id] mav_cmd_name = msg_type.msgname if hasattr(msg_type, "msgname") else msg_type.name print("Msg:%s rate:%0.2fHz" % (mav_cmd_name, (1E6/m.interval_us) ) ) else: print("Msg ID:%s rate:%0.2fHz" % (m.message_id, (1E6/m.interval_us) ) )
class messagerate(mp_module.MPModule): def __init__(self, mpstate): '''Initialise module''' pass def usage(self): '''show help on command line options''' pass def cmd_messagerate(self, args): '''control behaviour of the module''' pass def reset(self): '''reset rates''' pass def status(self): '''returns rates''' pass def idle_task(self): '''called rapidly by mavproxy''' pass def mavlink_packet(self, m): '''handle mavlink packets''' pass
8
7
16
1
15
1
5
0.08
1
3
0
0
7
4
7
45
122
11
103
31
95
8
83
31
75
16
2
3
32
7,339
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_message.py
MAVProxy.modules.mavproxy_message.message
class message(mp_module.MPModule): def __init__(self, mpstate): """Initialise module""" super(message, self).__init__(mpstate, "message", "") self.status_callcount = 0 self.boredom_interval = 10 # seconds self.last_bored = time.time() self.packets_mytarget = 0 self.packets_othertarget = 0 self.verbose = False self.message_settings = mp_settings.MPSettings( [('verbose', bool, False)]) self.add_command('message', self.cmd_message, "message module", []) def usage(self): '''show help on command line options''' return "Usage: message TYPE ARG..." def cmd_message(self, args): if len(args) == 0: print(self.usage()) else: packettype = args[0] methodname = packettype.lower() + "_send" transformed = [eval(x) for x in args[1:]] try: method = getattr(self.master.mav, methodname) except AttributeError: print("Unable to find %s" % methodname) return method(*transformed)
class message(mp_module.MPModule): def __init__(self, mpstate): '''Initialise module''' pass def usage(self): '''show help on command line options''' pass def cmd_message(self, args): pass
4
2
10
1
9
1
2
0.11
1
4
1
0
3
7
3
41
33
4
27
15
23
3
25
15
21
3
2
2
5
7,340
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_tile.py
MAVProxy.modules.mavproxy_map.mp_tile.TileServiceInfo
class TileServiceInfo: '''a lookup object for the URL templates''' def __init__(self, x, y, zoom): self.X = x self.Y = y self.Z = zoom quadcode = '' for i in range(zoom - 1, -1, -1): quadcode += str((((((y >> i) & 1) << 1) + ((x >> i) & 1)))) self.ZOOM = zoom self.QUAD = quadcode self.OAM_ZOOM = 17 - zoom self.GOOG_DIGIT = (x + y) & 3 self.MS_DIGITBR = (((y & 1) << 1) + (x & 1)) + 1 self.MS_DIGIT = (((y & 3) << 1) + (x & 1)) self.Y_DIGIT = (x + y + zoom) % 3 + 1 self.GALILEO = "Galileo"[0:(3 * x + y) & 7] self.ENI_Y = (1<<zoom)-1-y def __getitem__(self, a): return str(getattr(self, a))
class TileServiceInfo: '''a lookup object for the URL templates''' def __init__(self, x, y, zoom): pass def __getitem__(self, a): pass
3
1
9
0
9
0
2
0.05
0
2
0
0
2
12
2
2
21
1
19
17
16
1
19
17
16
2
0
1
3
7,341
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_misc.py
MAVProxy.modules.mavproxy_misc.MiscModule
class MiscModule(mp_module.MPModule): def __init__(self, mpstate): super(MiscModule, self).__init__(mpstate, "misc", "misc commands", public=True) self.add_command('alt', self.cmd_alt, "show altitude information") self.add_command('up', self.cmd_up, "adjust pitch trim by up to 5 degrees") self.add_command('reboot', self.cmd_reboot, "reboot autopilot") self.add_command('time', self.cmd_time, "show autopilot time") self.add_command('shell', self.cmd_shell, "run shell command") self.add_command('changealt', self.cmd_changealt, "change target altitude") self.add_command('changealt_abs', self.cmd_changealt_abs, "change target absolute altitude") self.add_command('land', self.cmd_land, "auto land") self.add_command('repeat', self.cmd_repeat, "repeat a command at regular intervals", ["<add|remove|clear>"]) self.add_command('version', self.cmd_version, "fetch autopilot version") self.add_command('capabilities', self.cmd_capabilities, "fetch autopilot capabilities") self.add_command('rcbind', self.cmd_rcbind, "bind RC receiver") self.add_command('led', self.cmd_led, "control board LED") self.add_command('oreoled', self.cmd_oreoled, "control OreoLEDs") self.add_command('playtune', self.cmd_playtune, "play tune remotely") self.add_command('devid', self.cmd_devid, "show device names from parameter IDs") self.add_command('gethome', self.cmd_gethome, "get HOME_POSITION") self.add_command('flashbootloader', self.cmd_flashbootloader, "flash bootloader (dangerous)") self.add_command('wipe_parameters', self.cmd_wipe_parameters, "wipe autopilot parameters") self.add_command('lockup_autopilot', self.cmd_lockup_autopilot, "lockup autopilot") self.add_command('corrupt_params', self.cmd_corrupt_param, "corrupt param storage") self.add_command('hardfault_autopilot', self.cmd_hardfault_autopilot, "hardfault autopilot") self.add_command('panic_autopilot', self.cmd_panic_autopilot, "panic autopilot") self.add_command('longloop_autopilot', self.cmd_longloop_autopilot, "cause long loop in autopilot") self.add_command('configerror_autopilot', self.cmd_config_error_autopilot, "ask autopilot to jump to its config error loop") # noqa:E501 self.add_command('internalerror_autopilot', self.cmd_internalerror_autopilot, "cause internal error in autopilot") self.add_command('dfu_boot', self.cmd_dfu_boot, "boot into DFU mode") self.add_command('deadlock', self.cmd_deadlock, "trigger deadlock") self.add_command('batreset', self.cmd_battery_reset, "reset battery remaining") self.add_command('setorigin', self.cmd_setorigin, "set global origin") self.add_command('magsetfield', self.cmd_magset_field, "set expected mag field by field") self.add_command('magresetofs', self.cmd_magreset_ofs, "reset offsets for all compasses") self.add_command('namedvaluefloat', self.cmd_namedvaluefloat, "send a NAMED_VALUE_FLOAT") self.add_command('scripting', self.cmd_scripting, "control onboard scripting", ["<stop|restart>"]) self.add_command('formatsdcard', self.cmd_formatsdcard, "format SD card") self.add_command('canforward', self.cmd_canforward, "enable CAN forwarding") self.add_command('gear', self.cmd_landing_gear, "landing gear control") self.repeats = [] def altitude_difference(self, pressure1, pressure2, ground_temp): '''calculate barometric altitude''' scaling = pressure2 / pressure1 temp = ground_temp + 273.15 return 153.8462 * temp * (1.0 - math.exp(0.190259 * math.log(scaling))) def qnh_estimate(self): '''estimate QNH pressure from GPS altitude and scaled pressure''' alt_gps = self.master.field('GPS_RAW_INT', 'alt', 0) * 0.001 pressure2 = self.master.field('SCALED_PRESSURE', 'press_abs', 0) ground_temp = self.get_mav_param('GND_TEMP', 21) temp = ground_temp + 273.15 pressure1 = pressure2 / math.exp(math.log(1.0 - (alt_gps / (153.8462 * temp))) / 0.190259) return pressure1 def cmd_alt(self, args): '''show altitude''' print("Altitude: %.1f" % self.status.altitude) qnh_pressure = self.get_mav_param('AFS_QNH_PRESSURE', None) if qnh_pressure is not None and qnh_pressure > 0: ground_temp = self.get_mav_param('GND_TEMP', 21) pressure = self.master.field('SCALED_PRESSURE', 'press_abs', 0) qnh_alt = self.altitude_difference(qnh_pressure, pressure, ground_temp) print("QNH Alt: %u meters %u feet for QNH pressure %.1f" % (qnh_alt, qnh_alt*3.2808, qnh_pressure)) print("QNH Estimate: %.1f millibars" % self.qnh_estimate()) def cmd_shell(self, args): '''shell command''' print(run_command(args, shell=False, timeout=3)) def cmd_up(self, args): '''adjust TRIM_PITCH_CD up by 5 degrees''' if len(args) == 0: adjust = 5.0 else: adjust = float(args[0]) old_trim = self.get_mav_param('TRIM_PITCH_CD', None) if old_trim is None: print("Existing trim value unknown!") return new_trim = int(old_trim + (adjust*100)) if math.fabs(new_trim - old_trim) > 1000: print("Adjustment by %d too large (from %d to %d)" % (adjust*100, old_trim, new_trim)) return print("Adjusting TRIM_PITCH_CD from %d to %d" % (old_trim, new_trim)) self.param_set('TRIM_PITCH_CD', new_trim) def cmd_reboot(self, args): '''reboot autopilot''' hold_in_bootloader = "bootloader" in args force = "force" in args # different path for force/not force to avoid dependency on # pymavlink's force-reboot support: if force: if hold_in_bootloader: param1 = 3 else: param1 = 1 param6 = 20190226 self.master.mav.command_long_send( self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, param1, 0, 0, 0, 0, param6, 0 ) return if len(args) > 0 and args[0] == 'bootloader': self.master.reboot_autopilot(True) else: self.master.reboot_autopilot() def cmd_wipe_parameters(self, args): self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_STORAGE, 0, 2, 0, 0, 0, 0, 0, 0) def cmd_dosomethingreallynastyto_autopilot(self, args, description, code): '''helper function for the following commands which do unpleasant things to the autopilot''' if len(args) > 0 and args[0] == 'IREALLYMEANIT': print("Sending %s command" % description) self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_PREFLIGHT_REBOOT_SHUTDOWN, 0, 42, 24, 71, code, 0, 0, 0) else: print("Invalid %s command" % description) def cmd_lockup_autopilot(self, args): '''lockup autopilot for watchdog testing''' self.cmd_dosomethingreallynastyto_autopilot(args, 'lockup', 93) def cmd_hardfault_autopilot(self, args): '''lockup autopilot for watchdog testing''' self.cmd_dosomethingreallynastyto_autopilot(args, 'hardfault', 94) def cmd_panic_autopilot(self, args): '''get ArduPilot to call AP_HAL::panic()''' self.cmd_dosomethingreallynastyto_autopilot(args, 'panic', 95) def cmd_corrupt_param(self, args): '''corrupt parameter storage for backup testing''' self.cmd_dosomethingreallynastyto_autopilot(args, 'corruption', 96) def cmd_longloop_autopilot(self, args): '''Ask the autopilot to create a long loop''' self.cmd_dosomethingreallynastyto_autopilot(args, 'long-loop', 97) def cmd_internalerror_autopilot(self, args): '''Ask the autopilot to create an internal error''' self.cmd_dosomethingreallynastyto_autopilot(args, 'internal-error', 98) def cmd_dfu_boot(self, args): '''boot into DFU bootloader without hold''' self.cmd_dosomethingreallynastyto_autopilot(args, 'DFU-boot-without-hold', 99) def cmd_config_error_autopilot(self, args): '''Ask the autopilot to jump into its config error loop''' self.cmd_dosomethingreallynastyto_autopilot(args, 'config-loop', 101) def cmd_deadlock(self, args): '''trigger a mutex deadlock''' self.cmd_dosomethingreallynastyto_autopilot(args, 'mutex-deadlock', 100) def cmd_battery_reset(self, args): '''reset battery remaining''' mask = -1 remaining_pct = 100 if len(args) > 0: mask = int(args[0]) if len(args) > 1: remaining_pct = int(args[1]) self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_BATTERY_RESET, 0, mask, remaining_pct, 0, 0, 0, 0, 0) def cmd_time(self, args): '''show autopilot time''' tusec = self.master.field('SYSTEM_TIME', 'time_unix_usec', 0) if tusec == 0: print("No SYSTEM_TIME time available") return print("%s (%s)\n" % (time.ctime(tusec * 1.0e-6), time.ctime())) def _cmd_changealt(self, alt, frame): self.master.mav.mission_item_send(self.settings.target_system, self.settings.target_component, 0, frame, mavutil.mavlink.MAV_CMD_NAV_WAYPOINT, 3, 1, 0, 0, 0, 0, 0, 0, alt) print("Sent change altitude command for %.1f meters" % alt) def cmd_changealt(self, args): '''change target altitude''' if len(args) < 1: print("usage: changealt <relaltitude>") return relalt = float(args[0]) self._cmd_changealt(relalt, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT) def cmd_changealt_abs(self, args): '''change target altitude''' if len(args) < 1: print("usage: changealt_abs <absaltitude>") return absalt = float(args[0]) self._cmd_changealt(absalt, mavutil.mavlink.MAV_FRAME_GLOBAL) def cmd_land(self, args): '''auto land commands''' if len(args) < 1: self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_DO_LAND_START, 0, 0, 0, 0, 0, 0, 0, 0) elif args[0] == 'abort': self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_DO_GO_AROUND, 0, 0, 0, 0, 0, 0, 0, 0) else: print("Usage: land [abort]") def request_message(self, message_id, p1=0): self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_REQUEST_MESSAGE, 0, # confirmation message_id, 0, 0, 0, 0, 0, 0) def cmd_version(self, args): '''show version''' self.request_message(mavutil.mavlink.MAVLINK_MSG_ID_AUTOPILOT_VERSION) def cmd_capabilities(self, args): '''show capabilities''' self.request_message(mavutil.mavlink.MAVLINK_MSG_ID_AUTOPILOT_VERSION) def cmd_rcbind(self, args): '''start RC bind''' if len(args) < 1: print("Usage: rcbind <dsmmode>") return self.master.mav.command_long_send(self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_START_RX_PAIR, 0, float(args[0]), 0, 0, 0, 0, 0, 0) def cmd_gethome(self, args): '''get home position''' self.master.mav.command_long_send(self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_GET_HOME_POSITION, 0, 0, 0, 0, 0, 0, 0, 0) def cmd_led(self, args): '''send LED pattern as override''' if len(args) < 3: print("Usage: led RED GREEN BLUE <RATE>") return pattern = [0] * 24 pattern[0] = int(args[0]) pattern[1] = int(args[1]) pattern[2] = int(args[2]) if len(args) == 4: plen = 4 pattern[3] = int(args[3]) else: plen = 3 self.master.mav.led_control_send(self.settings.target_system, self.settings.target_component, 0, 0, plen, pattern) def cmd_scripting(self, args): '''control onboard scripting''' if len(args) < 1: print("Usage: scripting <stop|restart>") return if args[0] == 'restart': cmd = mavutil.mavlink.SCRIPTING_CMD_STOP_AND_RESTART elif args[0] == 'stop': cmd = mavutil.mavlink.SCRIPTING_CMD_STOP else: print("Usage: scripting <stop|restart>") return # MAVProxy command to stop and re-start is: command_int 0 42701 0 0 3 0 0 0 0 0 0 self.master.mav.command_int_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, mavutil.mavlink.MAV_CMD_SCRIPTING, 0, 0, cmd, 0, 0, 0, 0, 0, 0) def cmd_formatsdcard(self, args): '''format SD card''' self.master.mav.command_int_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT_INT, mavutil.mavlink.MAV_CMD_STORAGE_FORMAT, 0, 0, 1, 1, 0, 0, 0, 0, 0) def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' if len(args) < 4: print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>") return lednum = int(args[0]) pattern = [0] * 24 pattern[0] = ord('R') pattern[1] = ord('G') pattern[2] = ord('B') pattern[3] = ord('0') pattern[4] = 0 pattern[5] = int(args[1]) pattern[6] = int(args[2]) pattern[7] = int(args[3]) self.master.mav.led_control_send(self.settings.target_system, self.settings.target_component, lednum, 255, 8, pattern) def cmd_flashbootloader(self, args): '''flash bootloader''' self.master.mav.command_long_send( self.settings.target_system, 0, mavutil.mavlink.MAV_CMD_FLASH_BOOTLOADER, 0, 0, 0, 0, 0, 290876, 0, 0 ) def cmd_playtune(self, args): '''send PLAY_TUNE message''' if len(args) < 1: print("Usage: playtune TUNE") return tune = args[0] str1 = tune[0:30] str2 = tune[30:] if sys.version_info.major >= 3 and not isinstance(str1, bytes): str1 = bytes(str1, "ascii") if sys.version_info.major >= 3 and not isinstance(str2, bytes): str2 = bytes(str2, "ascii") self.master.mav.play_tune_send(self.settings.target_system, self.settings.target_component, str1, str2) def cmd_repeat(self, args): '''repeat a command at regular intervals''' if len(args) == 0: if len(self.repeats) == 0: print("No repeats") return for i in range(len(self.repeats)): print("%u: %s" % (i, self.repeats[i])) return if args[0] == 'add': if len(args) < 3: print("Usage: repeat add PERIOD CMD") return self.repeats.append(RepeatCommand(float(args[1]), " ".join(args[2:]))) elif args[0] == 'remove': if len(args) < 2: print("Usage: repeat remove INDEX") return i = int(args[1]) if i < 0 or i >= len(self.repeats): print("Invalid index %d" % i) return self.repeats.pop(i) return elif args[0] == 'clean': self.repeats = [] else: print("Usage: repeat <add|remove|clean>") def cmd_devid(self, args): '''decode device IDs from parameters''' for p in self.mav_param.keys(): if p.startswith('COMPASS_DEV_ID') or p.startswith('COMPASS_PRIO') or ( p.startswith('COMPASS') and p.endswith('DEV_ID')): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('INS') and p.endswith('_ID'): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('GND_BARO') and p.endswith('_ID'): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('BARO') and p.endswith('_DEVID'): mp_util.decode_devid(self.mav_param[p], p) if p.startswith('ARSPD') and p.endswith('_DEVID'): mp_util.decode_devid(self.mav_param[p], p) def cmd_setorigin(self, args): '''set global origin''' if len(args) < 3: print("Usage: setorigin LAT(deg) LON(deg) ALT(m)") return lat = float(args[0]) lon = float(args[1]) alt = float(args[2]) print("Setting origin to: ", lat, lon, alt) self.master.mav.set_gps_global_origin_send( self.settings.target_system, int(lat*10000000), # lat int(lon*10000000), # lon int(alt*1000)) # param7 def cmd_magset_field(self, args): '''set compass offsets by field''' if len(args) < 3: print("Usage: magsetfield MagX MagY MagZ") return magX = int(args[0]) magY = int(args[1]) magZ = int(args[2]) field1x = self.master.field('RAW_IMU', 'xmag', 0) field1y = self.master.field('RAW_IMU', 'ymag', 0) field1z = self.master.field('RAW_IMU', 'zmag', 0) field2x = self.master.field('SCALED_IMU2', 'xmag', 0) field2y = self.master.field('SCALED_IMU2', 'ymag', 0) field2z = self.master.field('SCALED_IMU2', 'zmag', 0) field3x = self.master.field('SCALED_IMU3', 'xmag', 0) field3y = self.master.field('SCALED_IMU3', 'ymag', 0) field3z = self.master.field('SCALED_IMU3', 'zmag', 0) self.param_set('COMPASS_OFS_X', magX - (field1x - self.get_mav_param('COMPASS_OFS_X', 0))) self.param_set('COMPASS_OFS_Y', magY - (field1y - self.get_mav_param('COMPASS_OFS_Y', 0))) self.param_set('COMPASS_OFS_Z', magZ - (field1z - self.get_mav_param('COMPASS_OFS_Z', 0))) self.param_set('COMPASS_OFS2_X', magX - (field2x - self.get_mav_param('COMPASS_OFS2_X', 0))) self.param_set('COMPASS_OFS2_Y', magY - (field2y - self.get_mav_param('COMPASS_OFS2_Y', 0))) self.param_set('COMPASS_OFS2_Z', magZ - (field2z - self.get_mav_param('COMPASS_OFS2_Z', 0))) self.param_set('COMPASS_OFS3_X', magX - (field3x - self.get_mav_param('COMPASS_OFS3_X', 0))) self.param_set('COMPASS_OFS3_Y', magY - (field3y - self.get_mav_param('COMPASS_OFS3_Y', 0))) self.param_set('COMPASS_OFS3_Z', magZ - (field3z - self.get_mav_param('COMPASS_OFS3_Z', 0))) def cmd_magreset_ofs(self, args): '''set compass offsets to all zero''' self.param_set('COMPASS_OFS_X', 0) self.param_set('COMPASS_OFS_Y', 0) self.param_set('COMPASS_OFS_Z', 0) self.param_set('COMPASS_DIA_X', 1) self.param_set('COMPASS_DIA_Y', 1) self.param_set('COMPASS_DIA_Z', 1) self.param_set('COMPASS_ODI_X', 0) self.param_set('COMPASS_ODI_Y', 0) self.param_set('COMPASS_ODI_Z', 0) self.param_set('COMPASS_OFS2_X', 0) self.param_set('COMPASS_OFS2_Y', 0) self.param_set('COMPASS_OFS2_Z', 0) self.param_set('COMPASS_DIA2_X', 1) self.param_set('COMPASS_DIA2_Y', 1) self.param_set('COMPASS_DIA2_Z', 1) self.param_set('COMPASS_ODI2_X', 0) self.param_set('COMPASS_ODI2_Y', 0) self.param_set('COMPASS_ODI2_Z', 0) self.param_set('COMPASS_OFS3_X', 0) self.param_set('COMPASS_OFS3_Y', 0) self.param_set('COMPASS_OFS3_Z', 0) self.param_set('COMPASS_DIA3_X', 1) self.param_set('COMPASS_DIA3_Y', 1) self.param_set('COMPASS_DIA3_Z', 1) self.param_set('COMPASS_ODI3_X', 0) self.param_set('COMPASS_ODI3_Y', 0) self.param_set('COMPASS_ODI3_Z', 0) def cmd_namedvaluefloat(self, args): '''send a NAMED_VALUE_FLOAT''' if len(args) < 2: print("Usage: namedvaluefloat NAME value") return tnow_ms = int((time.time() - self.mpstate.start_time_s)*1000) name = args[0] value = float(args[1]) self.master.mav.named_value_float_send(tnow_ms, name.encode("utf-8"), value) def cmd_canforward(self, args): if len(args) < 1: print("Usage: canforward bus") return bus = int(args[0]) self.master.mav.command_long_send( self.settings.target_system, self.settings.target_component, mavutil.mavlink.MAV_CMD_CAN_FORWARD, 0, bus, 0, 0, 0, 0, 0, 0) def cmd_landing_gear(self, args): usage = '''Usage: gear <up|down> [ID] Alt: gear <extend|retract> [ID]''' if len(args) == 0 or args[0] not in ['up', 'down', 'extend', 'retract']: print(usage) return if args[0] in ['down', 'extend']: DesiredState = 0 elif args[0] in ['up', 'retract']: DesiredState = 1 else: print(usage) return if len(args) == 1: ID = -1 elif len(args) == 2: try: ID = int(args[1]) except ValueError: print(usage) return if ID < -1: print(usage) return else: print(usage) return self.master.mav.command_long_send( self.target_system, self.target_component, mavutil.mavlink.MAV_CMD_AIRFRAME_CONFIGURATION , 0, ID, DesiredState, 0, 0, 0, 0, 0, 0 ) def idle_task(self): '''called on idle''' for r in self.repeats: if r.event.trigger(): self.mpstate.functions.process_stdin(r.cmd, immediate=True)
class MiscModule(mp_module.MPModule): def __init__(self, mpstate): pass def altitude_difference(self, pressure1, pressure2, ground_temp): '''calculate barometric altitude''' pass def qnh_estimate(self): '''estimate QNH pressure from GPS altitude and scaled pressure''' pass def cmd_alt(self, args): '''show altitude''' pass def cmd_shell(self, args): '''shell command''' pass def cmd_up(self, args): '''adjust TRIM_PITCH_CD up by 5 degrees''' pass def cmd_reboot(self, args): '''reboot autopilot''' pass def cmd_wipe_parameters(self, args): pass def cmd_dosomethingreallynastyto_autopilot(self, args, description, code): '''helper function for the following commands which do unpleasant things to the autopilot''' pass def cmd_lockup_autopilot(self, args): '''lockup autopilot for watchdog testing''' pass def cmd_hardfault_autopilot(self, args): '''lockup autopilot for watchdog testing''' pass def cmd_panic_autopilot(self, args): '''get ArduPilot to call AP_HAL::panic()''' pass def cmd_corrupt_param(self, args): '''corrupt parameter storage for backup testing''' pass def cmd_longloop_autopilot(self, args): '''Ask the autopilot to create a long loop''' pass def cmd_internalerror_autopilot(self, args): '''Ask the autopilot to create an internal error''' pass def cmd_dfu_boot(self, args): '''boot into DFU bootloader without hold''' pass def cmd_config_error_autopilot(self, args): '''Ask the autopilot to jump into its config error loop''' pass def cmd_deadlock(self, args): '''trigger a mutex deadlock''' pass def cmd_battery_reset(self, args): '''reset battery remaining''' pass def cmd_time(self, args): '''show autopilot time''' pass def _cmd_changealt(self, alt, frame): pass def cmd_changealt(self, args): '''change target altitude''' pass def cmd_changealt_abs(self, args): '''change target altitude''' pass def cmd_land(self, args): '''auto land commands''' pass def request_message(self, message_id, p1=0): pass def cmd_version(self, args): '''show version''' pass def cmd_capabilities(self, args): '''show capabilities''' pass def cmd_rcbind(self, args): '''start RC bind''' pass def cmd_gethome(self, args): '''get home position''' pass def cmd_led(self, args): '''send LED pattern as override''' pass def cmd_scripting(self, args): '''control onboard scripting''' pass def cmd_formatsdcard(self, args): '''format SD card''' pass def cmd_oreoled(self, args): '''send LED pattern as override, using OreoLED conventions''' pass def cmd_flashbootloader(self, args): '''flash bootloader''' pass def cmd_playtune(self, args): '''send PLAY_TUNE message''' pass def cmd_repeat(self, args): '''repeat a command at regular intervals''' pass def cmd_devid(self, args): '''decode device IDs from parameters''' pass def cmd_setorigin(self, args): '''set global origin''' pass def cmd_magset_field(self, args): '''set compass offsets by field''' pass def cmd_magreset_ofs(self, args): '''set compass offsets to all zero''' pass def cmd_namedvaluefloat(self, args): '''send a NAMED_VALUE_FLOAT''' pass def cmd_canforward(self, args): pass def cmd_landing_gear(self, args): pass def idle_task(self): '''called on idle''' pass
45
38
12
0
11
1
2
0.1
1
7
1
0
44
1
44
82
582
62
478
102
433
47
355
102
310
10
2
2
97
7,342
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_tile.py
MAVProxy.modules.mavproxy_map.mp_tile.TileInfo
class TileInfo: '''description of a tile''' def __init__(self, tile, zoom, service, offset=(0,0)): self.tile = tile (self.x, self.y) = tile self.zoom = zoom self.service = service (self.offsetx, self.offsety) = offset self.refresh_time() def key(self): '''tile cache key''' return (self.tile, self.zoom, self.service) def refresh_time(self): '''reset the request time''' self.request_time = time.time() def coord(self, offset=(0,0)): '''return lat,lon within a tile given (offsetx,offsety)''' (tilex, tiley) = self.tile (offsetx, offsety) = offset world_tiles = 1<<self.zoom x = ( tilex + 1.0*offsetx/TILES_WIDTH ) / (world_tiles/2.) - 1 y = ( tiley + 1.0*offsety/TILES_HEIGHT) / (world_tiles/2.) - 1 lon = mp_util.wrap_180(x * 180.0) y = exp(-y*2*pi) e = (y-1)/(y+1) lat = 180.0/pi * asin(e) return (lat, lon) def size(self): '''return tile size as (width,height) in meters''' (lat1, lon1) = self.coord((0,0)) (lat2, lon2) = self.coord((TILES_WIDTH,0)) width = mp_util.gps_distance(lat1, lon1, lat2, lon2) (lat2, lon2) = self.coord((0,TILES_HEIGHT)) height = mp_util.gps_distance(lat1, lon1, lat2, lon2) return (width,height) def distance(self, lat, lon): '''distance of this tile from a given lat/lon''' (tlat, tlon) = self.coord((TILES_WIDTH/2,TILES_HEIGHT/2)) return mp_util.gps_distance(lat, lon, tlat, tlon) def path(self): '''return relative path of tile image''' (x, y) = self.tile return os.path.join('%u' % self.zoom, '%u' % y, '%u.img' % x) def url(self, service): '''return URL for a tile''' if service not in TILE_SERVICES: raise TileException('unknown tile service %s' % service) url = string.Template(TILE_SERVICES[service]) (x,y) = self.tile tile_info = TileServiceInfo(x, y, self.zoom) return url.substitute(tile_info)
class TileInfo: '''description of a tile''' def __init__(self, tile, zoom, service, offset=(0,0)): pass def key(self): '''tile cache key''' pass def refresh_time(self): '''reset the request time''' pass def coord(self, offset=(0,0)): '''return lat,lon within a tile given (offsetx,offsety)''' pass def size(self): '''return tile size as (width,height) in meters''' pass def distance(self, lat, lon): '''distance of this tile from a given lat/lon''' pass def path(self): '''return relative path of tile image''' pass def url(self, service): '''return URL for a tile''' pass
9
8
6
0
6
1
1
0.18
0
3
2
1
8
8
8
8
60
7
45
32
36
8
43
32
34
2
0
1
9
7,343
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_tile.py
MAVProxy.modules.mavproxy_map.mp_tile.TileException
class TileException(Exception): '''tile error class''' def __init__(self, msg): Exception.__init__(self, msg)
class TileException(Exception): '''tile error class''' def __init__(self, msg): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
11
4
0
3
2
1
1
3
2
1
1
3
0
1
7,344
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_tile.py
MAVProxy.modules.mavproxy_map.mp_tile.MPTile
class MPTile: '''map tile object''' def __init__(self, cache_path=None, download=True, cache_size=500, service="MicrosoftSat", tile_delay=0.3, debug=False, max_zoom=19, refresh_age=30*24*60*60): if cache_path is None: try: cache_path = os.path.join(os.environ['HOME'], '.tilecache') except Exception: if 'LOCALAPPDATA' in os.environ: cache_path = os.path.join(os.environ['LOCALAPPDATA'], '.tilecache') else: import tempfile cache_path = os.path.join(tempfile.gettempdir(), '.tilecache') if not os.path.exists(cache_path): mp_util.mkdir_p(cache_path) self.cache_path = cache_path self.max_zoom = max_zoom self.min_zoom = 4 self.download = download self.cache_size = cache_size self.tile_delay = tile_delay self.service = service self.debug = debug self.refresh_age = refresh_age if service not in TILE_SERVICES: raise TileException('unknown tile service %s' % service) # _download_pending is a dictionary of TileInfo objects self._download_pending = {} self._download_thread = None self._loading = mp_icon('loading.jpg') self._unavailable = mp_icon('unavailable.jpg') try: self._tile_cache = collections.OrderedDict() except AttributeError: # OrderedDicts in python 2.6 come from the ordereddict module # which is a 3rd party package, not in python2.6 distribution import ordereddict self._tile_cache = ordereddict.OrderedDict() def set_service(self, service): '''set tile service''' self.service = service def get_service(self): '''get tile service''' return self.service def get_service_list(self): '''return list of available services''' service_list = TILE_SERVICES.keys() return sorted(service_list) def set_download(self, download): '''set download enable''' self.download = download def coord_to_tile(self, lat, lon, zoom): '''convert lat/lon/zoom to a TileInfo''' world_tiles = 1<<zoom lon = mp_util.wrap_180(lon) x = world_tiles / 360.0 * (lon + 180.0) tiles_pre_radian = world_tiles / (2 * pi) e = sin(radians(lat)) e = mp_util.constrain(e, -1+1.0e-15, 1-1.0e-15) y = world_tiles/2 + 0.5*log((1+e)/(1-e)) * (-tiles_pre_radian) offsetx = int((x - int(x)) * TILES_WIDTH) offsety = int((y - int(y)) * TILES_HEIGHT) return TileInfo((int(x) % world_tiles, int(y) % world_tiles), zoom, self.service, offset=(offsetx, offsety)) def tile_to_path(self, tile): '''return full path to a tile''' return os.path.join(self.cache_path, self.service, tile.path()) def coord_to_tilepath(self, lat, lon, zoom): '''return the tile ID that covers a latitude/longitude at a specified zoom level ''' tile = self.coord_to_tile(lat, lon, zoom) return self.tile_to_path(tile) def tiles_pending(self): '''return number of tiles pending download''' return len(self._download_pending) def downloader(self): '''the download thread''' while self.tiles_pending() > 0: time.sleep(self.tile_delay) keys = sorted(self._download_pending.keys()) # work out which one to download next, choosing by request_time tile_info = self._download_pending[keys[0]] for key in keys: if self._download_pending[key].request_time > tile_info.request_time: tile_info = self._download_pending[key] url = tile_info.url(self.service) path = self.tile_to_path(tile_info) key = tile_info.key() try: if self.debug: print("Downloading %s [%u left]" % (url, len(keys))) req = url_request(url) req.add_header('User-Agent', 'MAVProxy') # try to re-use our cached data: try: mtime = os.path.getmtime(path) req.add_header('If-Modified-Since', time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(mtime))) except Exception: pass if url.find('google') != -1: req.add_header('Referer', 'https://maps.google.com/') resp = url_open(req) headers = resp.info() except url_error as e: try: if e.getcode() == 304: # cache hit; touch the file to reset its refresh time pathlib.Path(path).touch() self._download_pending.pop(key) continue except Exception as ex: pass #print('Error loading %s' % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("Failed %s: %s" % (url, str(e))) continue if 'content-type' not in headers or headers['content-type'].find('image') == -1: if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) if self.debug: print("non-image response %s" % url) continue else: img = resp.read() # see if its a blank/unavailable tile md5 = hashlib.md5(img).hexdigest() if md5 in BLANK_TILES: if self.debug: print("blank tile %s" % url) if not key in self._tile_cache: self._tile_cache[key] = self._unavailable self._download_pending.pop(key) continue mp_util.mkdir_p(os.path.dirname(path)) h = open(path+'.tmp','wb') h.write(img) h.close() try: os.unlink(path) except Exception: pass os.rename(path+'.tmp', path) self._download_pending.pop(key) self._download_thread = None def start_download_thread(self): '''start the downloader''' if self._download_thread: return t = threading.Thread(target=self.downloader) t.daemon = True self._download_thread = t t.start() def load_tile_lowres(self, tile): '''load a lower resolution tile from cache to fill in a map while waiting for a higher resolution tile''' if tile.zoom == self.min_zoom: return None # find the equivalent lower res tile (lat,lon) = tile.coord() width2 = TILES_WIDTH height2 = TILES_HEIGHT for zoom2 in range(tile.zoom-1, self.min_zoom-1, -1): width2 //= 2 height2 //= 2 if width2 == 0 or height2 == 0: break tile_info = self.coord_to_tile(lat, lon, zoom2) # see if its in the tile cache key = tile_info.key() if key in self._tile_cache: img = self._tile_cache[key] if np.array_equal(img, np.array(self._unavailable)): continue else: path = self.tile_to_path(tile_info) if not os.path.exists(path): continue img = cv2.imread(path) if img is None: continue #cv2.rectangle(img, (0,0), (TILES_WIDTH-1,TILES_WIDTH-1), (255,0,0), 1) # add it to the tile cache self._tile_cache[key] = img while len(self._tile_cache) > self.cache_size: self._tile_cache.popitem(0) # copy out the quadrant we want availx = min(TILES_WIDTH - tile_info.offsetx, width2) availy = min(TILES_HEIGHT - tile_info.offsety, height2) if availx != width2 or availy != height2: continue roi = img[tile_info.offsety:tile_info.offsety+height2, tile_info.offsetx:tile_info.offsetx+width2] # and scale it try: scaled = cv2.resize(roi, (TILES_HEIGHT,TILES_WIDTH)) except Exception as ex: return None #cv.Rectangle(scaled, (0,0), (255,255), (0,255,0), 1) return scaled return None def load_tile(self, tile): '''load a tile from cache or tile server''' # see if its in the tile cache key = tile.key() if key in self._tile_cache: img = self._tile_cache[key] if np.array_equal(img, self._unavailable): img = self.load_tile_lowres(tile) if img is None: img = self._unavailable return img path = self.tile_to_path(tile) if not os.path.exists(path): ret = None else: ret = cv2.imread(path) if ret is not None: #cv2.rectangle(ret, (0,0), (TILES_WIDTH-1,TILES_WIDTH-1), (255,0,0), 1) # if it is an old tile, then try to refresh if os.path.getmtime(path) + self.refresh_age < time.time(): try: self._download_pending[key].refresh_time() except Exception: self._download_pending[key] = tile self.start_download_thread() # add it to the tile cache self._tile_cache[key] = ret while len(self._tile_cache) > self.cache_size: self._tile_cache.popitem(0) return ret if not self.download: img = self.load_tile_lowres(tile) if img is None: img = self._unavailable return img try: self._download_pending[key].refresh_time() except Exception: self._download_pending[key] = tile self.start_download_thread() img = self.load_tile_lowres(tile) if img is None: img = self._loading return img def scaled_tile(self, tile): '''return a scaled tile''' width = int(TILES_WIDTH / tile.scale) height = int(TILES_HEIGHT / tile.scale) full_tile = self.load_tile(tile) scaled_tile = cv2.resize(full_tile, (height, width)) return scaled_tile def coord_from_area(self, x, y, lat, lon, width, ground_width): '''return (lat,lon) for a pixel in an area image x is pixel coord to the right from top,left y is pixel coord down from top left ''' scale1 = mp_util.constrain(cos(radians(lat)), 1.0e-15, 1) pixel_width = ground_width / float(width) pixel_width_equator = (ground_width / float(width)) / cos(radians(lat)) latr = radians(lat) y0 = abs(1.0/cos(latr) + tan(latr)) lat2 = 2 * atan(y0 * exp(-(y * pixel_width_equator) / mp_util.radius_of_earth)) - pi/2.0 lat2 = degrees(lat2) dx = pixel_width_equator * cos(radians(lat2)) * x (lat2,lon2) = mp_util.gps_offset(lat2, lon, dx, 0) return (lat2,lon2) def coord_to_pixel(self, lat, lon, width, ground_width, lat2, lon2): '''return pixel coordinate (px,py) for position (lat2,lon2) in an area image. Note that the results are relative to top,left and may be outside the image ground_width is with at lat,lon px is pixel coord to the right from top,left py is pixel coord down from top left ''' pixel_width_equator = (ground_width / float(width)) / cos(radians(lat)) latr = radians(lat) lat2r = radians(lat2) C = mp_util.radius_of_earth / pixel_width_equator y = C * (log(abs(1.0/cos(latr) + tan(latr))) - log(abs(1.0/cos(lat2r) + tan(lat2r)))) y = int(y+0.5) dx = mp_util.gps_distance(lat2, lon, lat2, lon2) if mp_util.gps_bearing(lat2, lon, lat2, lon2) > 180: dx = -dx x = int(0.5 + dx / (pixel_width_equator * cos(radians(lat2)))) return (x,y) def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None): '''return a list of TileInfoScaled objects needed for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. If unspecified, the zoom is automatically chosen to avoid having to grow the tiles ''' pixel_width = ground_width / float(width) ground_height = ground_width * (height/(float(width))) top_right = mp_util.gps_newpos(lat, lon, 90, ground_width) bottom_left = mp_util.gps_newpos(lat, lon, 180, ground_height) ground_width_bottom = ground_width * cos(radians(lat)) / max(1.0e-15,cos(radians(bottom_left[0]))) bottom_right = mp_util.gps_newpos(bottom_left[0], bottom_left[1], 90, ground_width_bottom) # choose a zoom level if not provided if zoom is None: zooms = range(self.min_zoom, self.max_zoom+1) else: zooms = [zoom] for zoom in zooms: tile_min = self.coord_to_tile(lat, lon, zoom) (twidth,theight) = tile_min.size() tile_pixel_width = twidth / float(TILES_WIDTH) scale = pixel_width / tile_pixel_width if scale >= 1.0: break scaled_tile_width = int(TILES_WIDTH / scale) scaled_tile_height = int(TILES_HEIGHT / scale) # work out the bottom right tile tile_max = self.coord_to_tile(bottom_right[0], bottom_right[1], zoom) ofsx = int(tile_min.offsetx / scale) ofsy = int(tile_min.offsety / scale) srcy = ofsy dsty = 0 ret = [] # place the tiles for y in range(tile_min.y, tile_max.y+1): srcx = ofsx dstx = 0 world_tiles = 1<<zoom lim_x = (tile_max.x+1) % world_tiles x = tile_min.x while x != lim_x: if dstx < width and dsty < height: ret.append(TileInfoScaled((x,y), zoom, scale, (srcx,srcy), (dstx,dsty), self.service)) dstx += scaled_tile_width-srcx srcx = 0 x = (x+1) % world_tiles dsty += scaled_tile_height-srcy srcy = 0 return ret def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True): '''return an RGB image for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. The zoom is automatically chosen to avoid having to grow the tiles''' img = np.zeros((height,width,3), np.uint8) tlist = self.area_to_tile_list(lat, lon, width, height, ground_width, zoom) # order the display by distance from the middle, so the download happens # close to the middle of the image first if ordered: (midlat, midlon) = self.coord_from_area(width/2, height/2, lat, lon, width, ground_width) tlist.sort(key=lambda d: d.distance(midlat, midlon), reverse=True) for t in tlist: scaled_tile = self.scaled_tile(t) w = width - t.dstx h = height - t.dsty if w > 0 and h > 0: scaled_tile_roi = scaled_tile[t.srcy:t.srcy+h, t.srcx:t.srcx+w] h = scaled_tile_roi.shape[0] w = scaled_tile_roi.shape[1] img[t.dsty:t.dsty+h, t.dstx:t.dstx+w] = scaled_tile_roi.copy() # return as an RGB image img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) return img
class MPTile: '''map tile object''' def __init__(self, cache_path=None, download=True, cache_size=500, service="MicrosoftSat", tile_delay=0.3, debug=False, max_zoom=19, refresh_age=30*24*60*60): pass def set_service(self, service): '''set tile service''' pass def get_service(self): '''get tile service''' pass def get_service_list(self): '''return list of available services''' pass def set_download(self, download): '''set download enable''' pass def coord_to_tile(self, lat, lon, zoom): '''convert lat/lon/zoom to a TileInfo''' pass def tile_to_path(self, tile): '''return full path to a tile''' pass def coord_to_tilepath(self, lat, lon, zoom): '''return the tile ID that covers a latitude/longitude at a specified zoom level ''' pass def tiles_pending(self): '''return number of tiles pending download''' pass def downloader(self): '''the download thread''' pass def start_download_thread(self): '''start the downloader''' pass def load_tile_lowres(self, tile): '''load a lower resolution tile from cache to fill in a map while waiting for a higher resolution tile''' pass def load_tile_lowres(self, tile): '''load a tile from cache or tile server''' pass def scaled_tile(self, tile): '''return a scaled tile''' pass def coord_from_area(self, x, y, lat, lon, width, ground_width): '''return (lat,lon) for a pixel in an area image x is pixel coord to the right from top,left y is pixel coord down from top left ''' pass def coord_to_pixel(self, lat, lon, width, ground_width, lat2, lon2): '''return pixel coordinate (px,py) for position (lat2,lon2) in an area image. Note that the results are relative to top,left and may be outside the image ground_width is with at lat,lon px is pixel coord to the right from top,left py is pixel coord down from top left ''' pass def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None): '''return a list of TileInfoScaled objects needed for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. If unspecified, the zoom is automatically chosen to avoid having to grow the tiles ''' pass def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordered=True): '''return an RGB image for an area of land, with ground_width in meters, and width/height in pixels. lat/lon is the top left corner. The zoom is automatically chosen to avoid having to grow the tiles''' pass
19
18
23
3
17
4
4
0.21
0
12
3
0
18
14
18
18
437
72
301
130
278
64
293
125
272
19
0
4
75
7,345
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.UnclosedSlipPolygon
class UnclosedSlipPolygon(SlipPolygon): '''a polygon to display on the map - but one with no return point or closing vertex''' def draw(self, img, pixmapper, bounds, colour=(0,0,0)): '''draw a polygon on the image''' if self.hidden: return self._pix_points = [] for i in range(len(self.points)): if len(self.points[i]) > 2: colour = self.points[i][2] else: colour = self.colour _from = self.points[i] if i+1 == len(self.points): _to = self.points[0] else: _to = self.points[i+1] self.draw_line( img, pixmapper, _from, _to, colour, self.linewidth)
class UnclosedSlipPolygon(SlipPolygon): '''a polygon to display on the map - but one with no return point or closing vertex''' def draw(self, img, pixmapper, bounds, colour=(0,0,0)): '''draw a polygon on the image''' pass
2
2
22
0
21
1
5
0.14
1
1
0
0
1
1
1
17
25
0
22
6
20
3
14
6
12
5
2
2
5
7,346
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipZoom
class SlipZoom: '''an object to change ground width''' def __init__(self, ground_width): self.ground_width = ground_width
class SlipZoom: '''an object to change ground width''' def __init__(self, ground_width): 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
7,347
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_tile.py
MAVProxy.modules.mavproxy_map.mp_tile.TileInfoScaled
class TileInfoScaled(TileInfo): '''information on a tile with scale information and placement''' def __init__(self, tile, zoom, scale, src, dst, service): TileInfo.__init__(self, tile, zoom, service) self.scale = scale (self.srcx, self.srcy) = src (self.dstx, self.dsty) = dst
class TileInfoScaled(TileInfo): '''information on a tile with scale information and placement''' def __init__(self, tile, zoom, scale, src, dst, service): pass
2
1
5
0
5
0
1
0.17
1
0
0
0
1
5
1
9
7
0
6
5
4
1
6
5
4
1
1
0
1
7,348
ArduPilot/MAVProxy
ArduPilot_MAVProxy/MAVProxy/modules/mavproxy_map/mp_slipmap_util.py
MAVProxy.modules.mavproxy_map.mp_slipmap_util.SlipTrail
class SlipTrail: '''trail information for a moving icon''' def __init__(self, timestep=0.2, colour=(255,255,0), count=60, points=[]): self.timestep = timestep self.colour = colour self.count = count self.points = points self.last_time = time.time() def update_position(self, newpos): '''update trail''' tnow = time.time() if tnow >= self.last_time + self.timestep: self.points.append(newpos.latlon) self.last_time = tnow while len(self.points) > self.count: self.points.pop(0) def draw(self, img, pixmapper, bounds): '''draw the trail''' for p in self.points: (px,py) = pixmapper(p) (width, height) = image_shape(img) if px >= 0 and py >= 0 and px < width and py < height: cv2.circle(img, (px,py), 1, self.colour)
class SlipTrail: '''trail information for a moving icon''' def __init__(self, timestep=0.2, colour=(255,255,0), count=60, points=[]): pass def update_position(self, newpos): '''update trail''' pass def draw(self, img, pixmapper, bounds): '''draw the trail''' pass
4
3
7
0
6
1
2
0.15
0
0
0
0
3
5
3
3
25
2
20
13
16
3
20
13
16
3
0
2
7
7,349
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/schema.py
swg2rst.swagger.schema.Schema
class Schema(AbstractTypeObject): """ Represents Swagger Schema Object """ schema_id = None schema_type = None #: definition or inline ref_path = None #: path for definition schemas nested_schemas = None all_of = None def __init__(self, obj, schema_type, **kwargs): assert schema_type in SchemaTypes.prefixes super(Schema, self).__init__(obj, **kwargs) self.nested_schemas = set() self.schema_type = schema_type self.description = obj.get('description', '').replace('"', '\'') self._type = obj.get('type', 'object') self.type_format = obj.get('format') self.schema_example = obj.get('example') self.read_only = obj.get('readOnly', False) self.external_docs = obj.get('externalDocs') if self._type in PRIMITIVE_TYPES: self.properties = [{ 'name': kwargs.get('name', ''), 'description': obj.get('description', ''), 'required': obj.get('required', False), 'type': self.type, 'type_format': self.type_format, 'type_properties': self.get_type_properties(obj, '')[2], }] if schema_type == SchemaTypes.DEFINITION: self.ref_path = '#/definitions/{}'.format(self.name) if self.is_array: self.item = dict(zip( ('type', 'type_format', 'type_properties'), self.get_type_properties(obj['items'], self.name) )) self.name += '_array' if self.item['type'] not in PRIMITIVE_TYPES: self.nested_schemas.add(self.item['type']) self._set_properties(obj) self._parse_all_of_property(obj) self._set_schema_id() def get_type_properties(self, property_obj, name, additional_prop=False): """ Extend parents 'Get internal properties of property'-method """ property_type, property_format, property_dict = \ super(Schema, self).get_type_properties(property_obj, name, additional_prop=additional_prop) _schema = self.storage.get(property_type) if _schema and ('additionalProperties' in property_obj): _property_type, _property_format, _property_dict = super(Schema, self).get_type_properties( property_obj['additionalProperties'], '{}-mapped'.format(name), additional_prop=True) if _property_type not in PRIMITIVE_TYPES: SchemaMapWrapper.wrap(self.storage.get(_property_type)) _schema.nested_schemas.add(_property_type) else: _schema.type_format = _property_type return property_type, property_format, property_dict def _set_schema_id(self): _id = self._get_id(self.ref_path or json.dumps(self.raw)) self.schema_id = '{}_{}'.format( SchemaTypes.prefixes[self.schema_type], _id) def _set_properties(self, obj): if obj.get('properties'): self.properties = [] required_fields = self.raw.get('required', []) for name, property_obj in self.raw['properties'].items(): property_type, property_format, prop = self.get_type_properties(property_obj, name) if property_type not in PRIMITIVE_TYPES: self.nested_schemas.add(property_type) _obj = { 'name': name, 'description': '', 'required': name in required_fields, 'type': property_type, 'type_format': property_format, 'type_properties': prop, } if 'description' in property_obj: _obj['description'] = property_obj['description'].replace('"', '\'') self.properties.append(_obj) def _parse_all_of_property(self, obj): if not obj.get('allOf'): return None self.all_of = [] schema = None for _obj in obj['allOf']: _id = self._get_object_schema_id(_obj, SchemaTypes.INLINE) if not self.storage.contains(_id): schema = self.storage.create_schema(_obj, 'inline', SchemaTypes.INLINE, self.root) assert schema.schema_id == _id if len(self.all_of) > 0: self.storage.merge_schemas( self.storage.get(self.all_of[-1]), schema if schema else self.storage.get(_id) ) self.all_of.append(_id) self.nested_schemas.add(_id) def _after_create_schema(self, schema): pass @property def is_inline(self): return self.schema_type == SchemaTypes.INLINE @property def is_inline_array(self): return self.is_inline and self.is_array def __repr__(self): return self.name
class Schema(AbstractTypeObject): ''' Represents Swagger Schema Object ''' def __init__(self, obj, schema_type, **kwargs): pass def get_type_properties(self, property_obj, name, additional_prop=False): ''' Extend parents 'Get internal properties of property'-method ''' pass def _set_schema_id(self): pass def _set_properties(self, obj): pass def _parse_all_of_property(self, obj): pass def _after_create_schema(self, schema): pass @property def is_inline(self): pass @property def is_inline_array(self): pass def __repr__(self): pass
12
2
12
1
10
0
3
0.09
1
6
2
1
9
8
9
17
126
18
102
36
90
9
76
34
66
6
2
3
24
7,350
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/schema.py
swg2rst.swagger.schema.SchemaMapWrapper
class SchemaMapWrapper(Schema): """ Dedicated class to store AdditionalProperties in schema """ def __init__(self, obj, **kwargs): super(SchemaMapWrapper, self).__init__(obj, SchemaTypes.MAPPED, **kwargs) @staticmethod def wrap(schema): if isinstance(schema, Schema): schema.__class__ = SchemaMapWrapper
class SchemaMapWrapper(Schema): ''' Dedicated class to store AdditionalProperties in schema ''' def __init__(self, obj, **kwargs): pass @staticmethod def wrap(schema): pass
4
1
3
0
3
0
2
0.43
1
2
1
0
1
0
2
19
11
1
7
4
3
3
6
3
3
2
3
1
3
7,351
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/schema_objects.py
swg2rst.swagger.schema_objects.SchemaObjects
class SchemaObjects(object): """ Schema collection """ _schemas = OrderedDict() @classmethod def create_schema(cls, obj, name, schema_type, root): """ Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_type: schema location. Can be ``inline``, ``definition`` or ``mapped`` :param BaseSwaggerObject root: root doc :return: new schema :rtype: Schema """ if schema_type == SchemaTypes.MAPPED: schema = SchemaMapWrapper(obj, storage=cls, name=name, root=root) else: schema = Schema(obj, schema_type, storage=cls, name=name, root=root) cls.add_schema(schema) return schema @classmethod def add_schema(cls, schema): """ Add schema object to collection :param Schema schema: """ cls._schemas[schema.schema_id] = schema @classmethod def get(cls, schema_id): """ Get schema object from collection by id :param str schema_id: :return: schema :rtype: Schema """ return cls._schemas.get(schema_id) @classmethod def get_schemas(cls, schema_types=None, sort=True): """ Get schemas by type. If ``schema_type`` is None, return all schemas :param schema_types: list of schema types :type schema_types: list or None :param bool sort: sort by name :return: list of schemas :rtype: list """ result = filter(lambda x: not x.is_inline_array, cls._schemas.values()) if schema_types: result = filter(lambda x: x.schema_type in schema_types, result) if sort: result = sorted(result, key=attrgetter('name')) return result @classmethod def contains(cls, key): """ Check schema existence in collection by id :param str key: :rtype: bool """ return key in cls._schemas @classmethod def clear(cls): cls._schemas = OrderedDict() @classmethod def merge_schemas(cls, schema, _schema): """Return second Schema, which is extended by first Schema https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#composition-and-inheritance-polymorphism """ tmp = schema.properties[:] # copy prop = {} to_dict = lambda e: prop.update({e.pop('name'): e}) [to_dict(i) for i in tmp] # map(to_dict, tmp) for _prop in _schema.properties: if prop.get(_prop['name']): prop.pop(_prop['name']) if prop: for k, v in prop.items(): v['name'] = k _schema.properties.append(v) return _schema
class SchemaObjects(object): ''' Schema collection ''' @classmethod def create_schema(cls, obj, name, schema_type, root): ''' Create Schema object :param dict obj: swagger schema object :param str name: schema name :param str schema_type: schema location. Can be ``inline``, ``definition`` or ``mapped`` :param BaseSwaggerObject root: root doc :return: new schema :rtype: Schema ''' pass @classmethod def add_schema(cls, schema): ''' Add schema object to collection :param Schema schema: ''' pass @classmethod def get(cls, schema_id): ''' Get schema object from collection by id :param str schema_id: :return: schema :rtype: Schema ''' pass @classmethod def get_schemas(cls, schema_types=None, sort=True): ''' Get schemas by type. If ``schema_type`` is None, return all schemas :param schema_types: list of schema types :type schema_types: list or None :param bool sort: sort by name :return: list of schemas :rtype: list ''' pass @classmethod def contains(cls, key): ''' Check schema existence in collection by id :param str key: :rtype: bool ''' pass @classmethod def clear(cls): pass @classmethod def merge_schemas(cls, schema, _schema): '''Return second Schema, which is extended by first Schema https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#composition-and-inheritance-polymorphism ''' pass
15
7
10
1
5
5
2
0.84
1
6
3
0
0
0
7
7
92
13
44
23
29
37
36
16
28
5
1
2
14
7,352
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/security_definition.py
swg2rst.swagger.security_definition.SecurityDefinition
class SecurityDefinition(object): """ Represents Swagger Security Scheme Object """ scopes = None location_in = None param_name = None flow = None auth_url = None token_url = None def __init__(self, name, obj): self.name = name self.type = obj['type'] assert self.type in SecurityTypes.names self.description = obj.get('description', '') self.raw = obj if self.type == SecurityTypes.API_KEY: self.location_in = obj['in'] self.param_name = obj['name'] elif self.type == SecurityTypes.OAUTH2: self.flow = obj['flow'] assert self.flow in ('implicit', 'password', 'application', 'accessCode') if self.flow in ('implicit', 'accessCode'): self.auth_url = obj['authorizationUrl'] if self.flow in ('password', 'accessCode', 'application'): self.token_url = obj['tokenUrl'] self.scopes = obj['scopes'] @property def type_name(self): return SecurityTypes.names[self.type]
class SecurityDefinition(object): ''' Represents Swagger Security Scheme Object ''' def __init__(self, name, obj): pass @property def type_name(self): pass
4
1
12
3
10
0
3
0.11
1
1
1
0
2
4
2
2
37
7
27
14
23
3
25
13
22
5
1
2
6
7,353
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/security_mixin.py
swg2rst.swagger.security_mixin.SecurityMixin
class SecurityMixin(object): security = None def _fill_securities(self, obj): if obj.get('security'): self.security = {} for security in obj['security']: self.security.update(security)
class SecurityMixin(object): def _fill_securities(self, obj): pass
2
0
5
0
5
0
3
0
1
0
0
2
1
0
1
1
9
2
7
4
5
0
7
4
5
3
1
2
3
7,354
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/utils/exampilators.py
swg2rst.utils.exampilators.Exampilator
class Exampilator(object): """ Example Manager """ DEFAULT_EXAMPLES = DEFAULT_EXAMPLES.copy() CUSTOM_EXAMPLES = dict() EXAMPLE_ARRAY_ITEMS_COUNT = 2 logger = get_logger() _json_format_checker = FormatChecker() @classmethod def fill_examples(cls, examples): if 'array_items_count' in examples: cls.EXAMPLE_ARRAY_ITEMS_COUNT = examples['array_items_count'] if 'types' in examples: cls.DEFAULT_EXAMPLES.update(examples['types']) if 'definitions' in examples: for path, fields in examples['definitions'].items(): for field, value in fields.items(): key = '.'.join((path, field)) cls.CUSTOM_EXAMPLES[key] = value if 'paths' in examples: for path, methods in examples['paths'].items(): key = "#/paths/'{}'".format(path) for method, operations in methods.items(): for section, fields in operations.items(): for field, value in fields.items(): _key = '/'.join((key, method, section, field)) cls.CUSTOM_EXAMPLES[_key] = value @classmethod def get_example_value_for_primitive_type(cls, type_, properties, format_, **kw): paths = kw.get('paths') if paths: result, path = cls._get_custom_example(paths) if result: cls._example_validate(path, result, type_, format_) return result if properties.get('default') is not None: result = properties['default'] elif properties.get('enum'): result = properties['enum'][0] else: result = getattr(cls, '%s_example' % type_)(properties, format_) return result @classmethod def string_example(cls, properties, type_format): if type_format in cls.DEFAULT_EXAMPLES: result = cls.DEFAULT_EXAMPLES[type_format] else: result = cls.DEFAULT_EXAMPLES['string'] if properties.get('min_length'): result.ljust(properties['min_length'], 'a') if properties.get('max_length'): result = result[:properties['max_length']] return result @classmethod def integer_example(cls, properties, *args): result = cls.DEFAULT_EXAMPLES['integer'] if properties.get('minimum') is not None and result < properties['minimum']: result = properties['minimum'] if properties.get('exclusive_minimum', False): result += 1 elif properties.get('maximum') is not None and result > properties['maximum']: result = properties['maximum'] if properties.get('exclusive_maximum', False): result -= 1 return result @classmethod def number_example(cls, properties, *args): return cls.integer_example(properties) @classmethod def boolean_example(cls, *args): return cls.DEFAULT_EXAMPLES['boolean'] @classmethod def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''): """ Get example by schema object :param Schema schema: current schema :param list ignored_schemas: list of previous schemas for avoid circular references :param list paths: list object paths (ex. #/definitions/Model.property) If nested schemas exists, custom examples checks in order from paths :param str name: name of property schema object if exists :return: dict or list (if schema is array) """ if schema.schema_example: return schema.schema_example if ignored_schemas is None: ignored_schemas = [] if paths is None: paths = [] if name: paths = list(map(lambda path: '.'.join((path, name)), paths)) if schema.ref_path: paths.append(schema.ref_path) if schema.schema_id in ignored_schemas: result = [] if schema.is_array else {} else: schemas = ignored_schemas + [schema.schema_id] kwargs = dict( ignored_schemas=schemas, paths=paths ) if schema.is_array: result = cls.get_example_for_array( schema.item, **kwargs) elif schema.type in PRIMITIVE_TYPES: result = cls.get_example_value_for_primitive_type( schema.type, schema.raw, schema.type_format, paths=paths ) elif schema.all_of: result = {} for _schema_id in schema.all_of: schema = SchemaObjects.get(_schema_id) result.update(cls.get_example_by_schema(schema, **kwargs)) else: result = cls.get_example_for_object( schema.properties, nested=schema.nested_schemas, **kwargs) return result @classmethod def get_body_example(cls, operation): """ Get example for body parameter example by operation :param Operation operation: operation object """ path = "#/paths/'{0.path}'/{0.method}/parameters/{name}".format( operation, name=operation.body.name or 'body') return cls.get_example_by_schema(operation.body, paths=[path]) @classmethod def get_response_example(cls, operation, response): """ Get example for response object by operation object :param Operation operation: operation object :param Response response: response object """ path = "#/paths/'{}'/{}/responses/{}".format( operation.path, operation.method, response.name) kwargs = dict(paths=[path]) if response.type in PRIMITIVE_TYPES: result = cls.get_example_value_for_primitive_type( response.type, response.properties, response.type_format, **kwargs) else: schema = SchemaObjects.get(response.type) result = cls.get_example_by_schema(schema, **kwargs) return result @classmethod def get_header_example(cls, header): """ Get example for header object :param Header header: Header object :return: example :rtype: dict """ if header.is_array: result = cls.get_example_for_array(header.item) else: example_method = getattr(cls, '{}_example'.format(header.type)) result = example_method(header.properties, header.type_format) return {header.name: result} @classmethod def get_property_example(cls, property_, nested=None, **kw): """ Get example for property :param dict property_: :param set nested: :return: example value """ paths = kw.get('paths', []) name = kw.get('name', '') result = None if name and paths: paths = list(map(lambda path: '.'.join((path, name)), paths)) result, path = cls._get_custom_example(paths) if result is not None and property_['type'] in PRIMITIVE_TYPES: cls._example_validate( path, result, property_['type'], property_['type_format']) return result if SchemaObjects.contains(property_['type']): schema = SchemaObjects.get(property_['type']) if result is not None: if schema.is_array: if not isinstance(result, list): result = [result] * cls.EXAMPLE_ARRAY_ITEMS_COUNT else: if isinstance(result, list): cls.logger.warning( 'Example type mismatch in path {}'.format(schema.ref_path)) else: result = cls.get_example_by_schema(schema, **kw) if (not result) and schema.nested_schemas: for _schema_id in schema.nested_schemas: _schema = SchemaObjects.get(_schema_id) if _schema: if isinstance(_schema, SchemaMapWrapper): result[_schema.name] = cls.get_example_by_schema(_schema, **kw) elif _schema.nested_schemas: for _schema__id in _schema.nested_schemas: _schema_ = SchemaObjects.get(_schema__id) if isinstance(_schema_, SchemaMapWrapper): result[_schema.name] = cls.get_example_by_schema(_schema_, **kw) else: result = cls.get_example_value_for_primitive_type( property_['type'], property_['type_properties'], property_['type_format'], **kw ) return result @classmethod def _get_custom_example(cls, paths): if cls.CUSTOM_EXAMPLES: for path in paths: if path in cls.CUSTOM_EXAMPLES: return cls.CUSTOM_EXAMPLES[path], path return None, '' @classmethod def get_example_for_array(cls, obj_item, **kw): return [cls.get_property_example(obj_item, **kw)] * cls.EXAMPLE_ARRAY_ITEMS_COUNT @classmethod def get_example_for_object(cls, properties, nested=None, **kw): result = {} if properties: for _property in properties: kw['name'] = _property['name'] result[_property['name']] = cls.get_property_example( _property, nested=nested, **kw) return result @classmethod def schema_validate(cls, obj, json_schema): schema_validate(obj, json_schema, format_checker=cls._json_format_checker) @classmethod def _example_validate(cls, path, value, type_, format_=None): _json_schema = {'type': type_} if format_: _json_schema['format'] = format_ try: cls.schema_validate(value, _json_schema) except (ValidationError, SchemaError): cls.logger.warning('Example type mismatch in path {}'.format(path))
class Exampilator(object): ''' Example Manager ''' @classmethod def fill_examples(cls, examples): pass @classmethod def get_example_value_for_primitive_type(cls, type_, properties, format_, **kw): pass @classmethod def string_example(cls, properties, type_format): pass @classmethod def integer_example(cls, properties, *args): pass @classmethod def number_example(cls, properties, *args): pass @classmethod def boolean_example(cls, *args): pass @classmethod def get_example_by_schema(cls, schema, ignored_schemas=None, paths=None, name=''): ''' Get example by schema object :param Schema schema: current schema :param list ignored_schemas: list of previous schemas for avoid circular references :param list paths: list object paths (ex. #/definitions/Model.property) If nested schemas exists, custom examples checks in order from paths :param str name: name of property schema object if exists :return: dict or list (if schema is array) ''' pass @classmethod def get_body_example(cls, operation): ''' Get example for body parameter example by operation :param Operation operation: operation object ''' pass @classmethod def get_response_example(cls, operation, response): ''' Get example for response object by operation object :param Operation operation: operation object :param Response response: response object ''' pass @classmethod def get_header_example(cls, header): ''' Get example for header object :param Header header: Header object :return: example :rtype: dict ''' pass @classmethod def get_property_example(cls, property_, nested=None, **kw): ''' Get example for property :param dict property_: :param set nested: :return: example value ''' pass @classmethod def _get_custom_example(cls, paths): pass @classmethod def get_example_for_array(cls, obj_item, **kw): pass @classmethod def get_example_for_object(cls, properties, nested=None, **kw): pass @classmethod def schema_validate(cls, obj, json_schema): pass @classmethod def _example_validate(cls, path, value, type_, format_=None): pass
33
6
14
1
11
2
4
0.16
1
7
2
0
0
0
16
16
269
36
204
73
171
32
156
57
139
15
1
7
71
7,355
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/test.py
swg2rst.test.BaseSwaggerTestCase
class BaseSwaggerTestCase(object): swagger_filename = None swagger_doc = None example_filename = None examples = None @classmethod def setUpClass(cls): swagger_file = os.path.join(SAMPLES_PATH, cls.swagger_filename) with codecs.open(swagger_file, 'r', encoding='utf-8') as _file: doc = json.load(_file) if doc is None: raise SkipTest('File is empty') if cls.example_filename: example_file = os.path.join(SAMPLES_PATH, cls.example_filename) with codecs.open(example_file, 'r', encoding='utf-8') as _file: cls.examples = json.load(_file) if not cls.examples: raise SkipTest('Example file is empty') cls.swagger_doc = BaseSwaggerObject(doc) cls.exampilator = cls.swagger_doc.exampilator def test_swagger_root(self): map(functools.partial(self.assertIsInstance, cls=list), self.swagger_doc.tags.values()) if 'parameters' in self.swagger_doc.raw: self.assertEqual( len(self.swagger_doc.raw['parameters']), len(self.swagger_doc.parameter_definitions) ) def test_security_definitions(self): if 'securityDefinitions' in self.swagger_doc.raw: getting = sorted(self.swagger_doc.raw['securityDefinitions'].keys()) expected = sorted(self.swagger_doc.security_definitions.keys()) self.assertSequenceEqual(getting, expected) def test_doc_security(self): if 'security' in self.swagger_doc.raw: self._test_security(self.swagger_doc.security) def _test_security(self, security_obj): for key, security in security_obj.items(): self.assertIn(key, self.swagger_doc.security_definitions) if security: # list is not empty security_def = self.swagger_doc.security_definitions[key] self.assertEqual(security_def.type, SecurityTypes.OAUTH2) # security scopes in security definition self.assertLessEqual(set(security), set(security_def.scopes)) def test_schemas(self): definition_schemas = self.swagger_doc.schemas.get_schemas( [SchemaTypes.DEFINITION]) self.assertEqual(len(definition_schemas), len(self.swagger_doc.raw['definitions'])) def _get_definition_schema(self, name): schema_obj = self.swagger_doc.raw['definitions'][name] schema = Schema( schema_obj, SchemaTypes.DEFINITION, name=name, root=None, storage=self.swagger_doc.schemas) self.assertTrue(self.swagger_doc.schemas.contains(schema.schema_id)) self.assertEqual(self.swagger_doc.schemas.get(schema.schema_id).name, name) return schema def test_operations(self): for path, operations in self.swagger_doc.raw['paths'].items(): path_params_count = 0 if 'parameters' in operations: self._check_parameters(operations['parameters']) path_params_count += len(operations['parameters']) for method, operation_obj in operations.items(): if method == 'parameters': continue operation_id = operation_obj.get( 'operationId', Operation.get_operation_id(method, path)) self.assertIn(operation_id, self.swagger_doc.operations) operation = self.swagger_doc.operations[operation_id] self._test_parameters(operation_obj, operation, path_params_count) self._test_responses(operation_obj, operation) if 'security' in operation_obj: self._test_security(operation.security) def test_primitive_examples(self): examples = self.exampilator.DEFAULT_EXAMPLES method = self.exampilator.get_example_value_for_primitive_type pairs = ( (method('string', {}, ''), examples['string']), (method('string', {}, 'date'), examples['date']), (method('string', {}, 'date-time'), examples['date-time']), (method('', {'default': 'default'}, ''), 'default'), (method('', {'enum': [1, 2, 3]}, ''), 1), (method('integer', {}, ''), examples['integer']), (method('integer', {'minimum': 1000}, ''), examples['integer'] if examples['integer'] >= 1000 else 1000), (method('integer', {'maximum': -1000}, ''), examples['integer'] if examples['integer'] <= -1000 else -1000), (method('integer', {'minimum': 1000, 'exclusive_minimum': True}, ''), examples['integer'] if examples['integer'] > 1000 else 1001), (method('integer', {'maximum': -1000, 'exclusive_maximum': True}, ''), examples['integer'] if examples['integer'] < -1000 else -1001), (method('boolean', {}, ''), examples['boolean']), ) for pair in pairs: self.assertEqual(*pair) def test_custom_examples(self): self.exampilator.fill_examples(self.examples) if 'types' in self.examples: for _type, value in self.examples['types'].items(): self.assertEqual(self.exampilator.DEFAULT_EXAMPLES[_type], value) else: self.assertDictEqual( self.exampilator.DEFAULT_EXAMPLES, exampilators.DEFAULT_EXAMPLES) if 'array_items_count' in self.examples: self.assertEqual(self.exampilator.EXAMPLE_ARRAY_ITEMS_COUNT, self.examples['array_items_count']) integer_example = self.examples['types'].get( 'integer', exampilators.DEFAULT_EXAMPLES['integer']) len_examples = self.examples.get('array_items_count', 2) self.assertEqual( self.exampilator.get_example_for_array( {'type': 'integer', 'type_properties': {}, 'type_format': None}), [integer_example] * len_examples) def _test_parameters(self, operation_obj, operation, params_count): if 'parameters' in operation_obj: self._check_parameters(operation_obj['parameters']) params_count += len(operation_obj['parameters']) self.assertEqual(len(operation.parameters), params_count) self.assertEqual(len(operation.get_parameters_by_location()), params_count) if operation.get_parameters_by_location(['body']): self.assertIsNotNone(operation.body) else: self.assertIsNone(operation.body) def _test_responses(self, operation_obj, operation): self.assertEqual(len(operation_obj['responses']), len(operation.responses)) for response in operation_obj['responses'].values(): if '$ref' in response: self.assertIn(response['$ref'], self.swagger_doc.response_definitions) def _check_parameters(self, params_obj): for param in params_obj: if '$ref' in param: self.assertIn(param['$ref'], self.swagger_doc.parameter_definitions) def _make_operation(self, path, method): path_obj = self.swagger_doc.raw['paths'][path] operation_obj = path_obj[method] operation = Operation( operation_obj, method, path, self.swagger_doc, self.swagger_doc.schemas) return operation
class BaseSwaggerTestCase(object): @classmethod def setUpClass(cls): pass def test_swagger_root(self): pass def test_security_definitions(self): pass def test_doc_security(self): pass def _test_security(self, security_obj): pass def test_schemas(self): pass def _get_definition_schema(self, name): pass def test_operations(self): pass def test_primitive_examples(self): pass def test_custom_examples(self): pass def _test_parameters(self, operation_obj, operation, params_count): pass def _test_responses(self, operation_obj, operation): pass def _check_parameters(self, params_obj): pass def _make_operation(self, path, method): pass
16
0
11
2
9
0
3
0.01
1
10
5
1
13
1
14
14
174
37
135
49
119
2
103
46
88
6
1
3
41
7,356
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/test.py
swg2rst.test.InstagramTestCase
class InstagramTestCase(BaseSwaggerTestCase, TestCase): swagger_filename = 'instagram.json' example_filename = 'instagram_examples.json' def test_custom_examples(self): super(InstagramTestCase, self).test_custom_examples() self.assertEqual( self.exampilator.CUSTOM_EXAMPLES['#/definitions/Media.likes.count'], self.examples['definitions']['#/definitions/Media']['likes.count'] ) self._test_schema_example() self._test_operation_example() def _test_schema_example(self): schema = self._get_definition_schema('MiniProfile') raw_definition = self.examples['definitions']['#/definitions/MiniProfile'] self.assertEqual(self.exampilator.get_example_by_schema(schema), { 'full_name': raw_definition['full_name'], 'id': self.examples['types']['integer'], 'profile_picture': self.examples['types']['string'], 'user_name': raw_definition['user_name'], }) def _test_operation_example(self): raw = self.examples['paths']['/users/{user-id}/relationship']['post'] operation = self._make_operation('/users/{user-id}/relationship', 'post') self.assertEqual(self.exampilator.get_body_example(operation), raw['parameters']['action']) self.assertSequenceEqual( self.exampilator.get_response_example(operation, operation.responses['200']), {'data': [raw['responses']['200.data']] * self.examples['array_items_count']} )
class InstagramTestCase(BaseSwaggerTestCase, TestCase): def test_custom_examples(self): pass def _test_schema_example(self): pass def _test_operation_example(self): pass
4
0
10
1
9
1
1
0.1
2
1
0
0
3
0
3
89
36
7
29
10
25
3
17
10
13
1
2
0
3
7,357
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/test.py
swg2rst.test.RSTIntegrationsTestCase
class RSTIntegrationsTestCase(TestCase): """ Testing rst-specific methods """ @staticmethod def prepare_env(cnt, file_name=True, inline=False): this = {} if file_name: this['file_name_json'] = os.path.join(SAMPLES_PATH, '{}.json'.format(cnt)) this['file_name_rst'] = os.path.join(SAMPLES_PATH, '{}{inline}.rst'.format(cnt, inline='_inline' if inline else '') ) with codecs.open(this['file_name_json'], 'r', encoding='utf-8') as _file: doc = json.load(_file) else: this['file_name_json'] = False this['file_name_rst'] = False doc = json.load(cnt) this['swagger_doc'] = rst.SwaggerObject(doc) doc_module = importlib.import_module('swg2rst.utils.rst') jinja_env = Environment(lstrip_blocks=True, trim_blocks=True) jinja_env.loader = PackageLoader('swg2rst') for name, function in inspect.getmembers(doc_module, inspect.isfunction): jinja_env.filters[name] = function jinja_env.filters['sorted'] = sorted template = jinja_env.get_template('main.rst') this['raw_rst'] = template.render(doc=this['swagger_doc'], inline=inline) this['pattern'] = re.compile(r'[idm]_\w{32}') this['normalize'] = lambda x: x[:-1] if x[-1] == '\n' else x return this @staticmethod def run_integration(this): log = [] flag = None counter = 5 original_i = 0 generated_i = 0 generated_lines = (i.strip() for i in this['raw_rst'].split('\n')) with codecs.open(this['file_name_rst'], 'r', encoding='utf-8') as _file: original_lines = (this['normalize'](i).strip() for i in _file.readlines()) original_line, original_i = iterate(original_lines, original_i) generated_line, generated_i = iterate(generated_lines, generated_i) while generated_line or original_line: log.append('o{}:{}\ng{}:{}'.format(original_i, repr(original_line), generated_i, repr(generated_line))) if (len(log) > counter) and (not flag): log.pop(0) if (len(log) > 2 * counter - 1) and flag: print('\n'.join(log) + '\no:Original rst / g:Generated rst') raise Exception('Differences found at {} line!'.format(flag)) if original_line == ' ' and generated_line == ' ': pass elif original_line != ' ' and generated_line == ' ': while generated_line == ' ': generated_line, generated_i = iterate(generated_lines, generated_i) elif original_line == ' ' and generated_line != ' ': while original_line == ' ': original_line, original_i = iterate(original_lines, original_i) else: if this['pattern'].search(original_line): pass elif (original_line != generated_line) and (not flag): flag = 'o{}/g{}'.format(original_i, generated_i) # up flag original_line, original_i = iterate(original_lines, original_i) generated_line, generated_i = iterate(generated_lines, generated_i) @staticmethod def make_content(): return File_obj(u"""{ "swagger": "2.0", "info": { "version": "0.0.1", "description": "", "title": "API title" }, "host": "", "basePath": "/", "produces": [ "application/json" ], "consumes": [ "application/json" ], "paths": { "/api/v1/short_path": { "get": { "responses": { "999": { "schema": { "type": "object", "properties": { "ReferenceProperty": { "additionalProperties": { "$ref": "#/definitions/SimpleSerializer" } } } } } } } } }, "definitions": { "SimpleSerializer": { "type": "object", "properties": { "MyProp": { "type": "string" } } }, "DifficultSerializer": { "schema": { "allOf": [ {"$ref": "#/definitions/SimpleSerializer"}, { "type": "object", "properties":{ "YouProp": { "type": "string" } } } ] } } } }""") def test_get_regular(self): """ SwaggerObject.get_regular_properties """ this = self.prepare_env(self.make_content(), file_name=False) result = this['swagger_doc'].get_regular_properties('d_3dccce5dab252608978d2313d304bfbd', definition=True) expect = """.. csv-table:: :delim: | :header: "Name", "Required", "Type", "Format", "Properties", "Description" :widths: 20, 10, 15, 15, 30, 25 MyProp | No | string | | | """ assert(result.strip() == expect.strip()) def test_get_type_definition(self): """SwaggerObject.get_type_description""" this = self.prepare_env(self.make_content(), file_name=False) result = this['swagger_doc'].get_type_description('d_3dccce5dab252608978d2313d304bfbd') expect = ':ref:`SimpleSerializer <d_3dccce5dab252608978d2313d304bfbd>`' assert(result == expect) def test_get_type_inline(self): """SwaggerObject.get_type_description""" this = self.prepare_env(self.make_content(), file_name=False) result = this['swagger_doc'].get_type_description('i_7886d86d0baffa0e753f35d813f3cec6') expect = ':ref:`ReferenceProperty <i_7886d86d0baffa0e753f35d813f3cec6>`' assert(result == expect) def test_get_additional(self): """SwaggerObject.get_additional_properties""" this = self.prepare_env(self.make_content(), file_name=False) result = this['swagger_doc'].get_additional_properties('i_7886d86d0baffa0e753f35d813f3cec6') expect = """ Map of {"key":":ref:`SimpleSerializer <d_3dccce5dab252608978d2313d304bfbd>`"} """ assert(result.strip() == expect.strip()) def test_additionalprop(self): file_name = 'additionalProperties' this = self.prepare_env(file_name) self.run_integration(this) def test_additionalprop_inline(self): file_name = 'additionalProperties' this = self.prepare_env(file_name, inline=True) self.run_integration(this) def test_intergation_allof(self): file_name = 'allOf' this = self.prepare_env(file_name) self.run_integration(this) def test_intergation_allof_inline(self): file_name = 'allOf' this = self.prepare_env(file_name, inline=True) self.run_integration(this) def test_intergation_instagram(self): file_name = 'instagram' this = self.prepare_env(file_name) self.run_integration(this)
class RSTIntegrationsTestCase(TestCase): ''' Testing rst-specific methods ''' @staticmethod def prepare_env(cnt, file_name=True, inline=False): pass @staticmethod def run_integration(this): pass @staticmethod def make_content(): pass def test_get_regular(self): ''' SwaggerObject.get_regular_properties ''' pass def test_get_type_definition(self): '''SwaggerObject.get_type_description''' pass def test_get_type_inline(self): '''SwaggerObject.get_type_description''' pass def test_get_additional(self): '''SwaggerObject.get_additional_properties''' pass def test_additionalprop(self): pass def test_additionalprop_inline(self): pass def test_intergation_allof(self): pass def test_intergation_allof_inline(self): pass def test_intergation_instagram(self): pass
16
5
15
0
14
1
2
0.07
1
2
1
0
9
0
12
84
192
13
170
55
154
12
94
50
81
11
2
3
25
7,358
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/response.py
swg2rst.swagger.response.Response
class Response(AbstractTypeObject): """ Represents Swagger Response Object """ headers = None examples = None def __init__(self, obj, **kwargs): super(Response, self).__init__(obj, **kwargs) self.description = obj.get('description') self.examples = obj.get('examples') if 'schema' in obj: self._set_type() if 'headers' in obj: self.headers = {name: Header(header, name=name, root=self.root) for name, header in obj['headers'].items()} def _set_type(self): if 'type' in self.raw['schema'] and self.raw['schema']['type'] in PRIMITIVE_TYPES: self._type = self.raw['schema']['type'] self.type_format = self.raw['schema'].get('format') _, _, self.properties = self.get_type_properties(self.raw, self.name) else: self.set_type_by_schema(self.raw['schema'], SchemaTypes.INLINE)
class Response(AbstractTypeObject): ''' Represents Swagger Response Object ''' def __init__(self, obj, **kwargs): pass def _set_type(self): pass
3
1
9
1
8
0
3
0.11
1
3
2
0
2
4
2
10
25
4
19
9
16
2
17
9
14
3
2
1
5
7,359
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/utils/rst.py
swg2rst.utils.rst.SwaggerObject
class SwaggerObject(BaseSwaggerObject): @staticmethod def sorted(collection): """ sorting dict by key, schema-collection by schema-name operations by id """ if len(collection) < 1: return collection if isinstance(collection, dict): return sorted(collection.items(), key=lambda x: x[0]) if isinstance(list(collection)[0], Operation): key = lambda x: x.operation_id elif isinstance(list(collection)[0], str): key = lambda x: SchemaObjects.get(x).name else: raise TypeError(type(collection[0])) return sorted(collection, key=key) def get_regular_properties(self, _type, *args, **kwargs): """Make table with properties by schema_id :param str _type: :rtype: str """ if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.schema_type == SchemaTypes.DEFINITION and not kwargs.get('definition'): return '' head = """.. csv-table:: :delim: | :header: "Name", "Required", "Type", "Format", "Properties", "Description" :widths: 20, 10, 15, 15, 30, 25 """ body = [] if schema.properties: for p in schema.properties: body.append(' {} | {} | {} | {} | {} | {}'.format( p.get('name') or '', 'Yes' if p.get('required') else 'No', self.get_type_description(p['type'], *args, **kwargs), p.get('type_format') or '', '{}'.format(p.get('type_properties') or ''), p.get('description') or '') ) body.sort() return (head + '\n'.join(body)) def get_type_description(self, _type, suffix='', *args, **kwargs): """ Get description of type :param suffix: :param str _type: :rtype: str """ if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) if schema.all_of: models = ','.join( (self.get_type_description(_type, *args, **kwargs) for _type in schema.all_of) ) result = '{}'.format(models.split(',')[0]) for r in models.split(',')[1:]: result += ' extended {}'.format(r) elif schema.is_array: result = 'array of {}'.format( self.get_type_description(schema.item['type'], *args, **kwargs)) else: result = ':ref:`{} <{}{}>`'.format(schema.name, schema.schema_id, suffix) return result def get_additional_properties(self, _type, *args, **kwargs): """Make head and table with additional properties by schema_id :param str _type: :rtype: str """ if not SchemaObjects.contains(_type): return _type schema = SchemaObjects.get(_type) body = [] for sch in schema.nested_schemas: # complex types nested_schema = SchemaObjects.get(sch) if not (nested_schema or isinstance(nested_schema, SchemaMapWrapper)): continue body.append('Map of {{"key":"{}"}}\n\n'.format(self.get_type_description( nested_schema.schema_id, *args, **kwargs)) # head ) if nested_schema.is_array: # table _schema = SchemaObjects.get(nested_schema.item.get('type')) if _schema and _schema.schema_type == SchemaTypes.INLINE: body.append(self.get_regular_properties(_schema.schema_id, *args, **kwargs)) else: body.append(self.get_regular_properties(nested_schema.schema_id, *args, **kwargs)) if schema.type_format: # basic types, only head body.append( 'Map of {{"key":"{}"}}'.format(self.get_type_description(schema.type_format, *args, **kwargs))) return ''.join(body)
class SwaggerObject(BaseSwaggerObject): @staticmethod def sorted(collection): ''' sorting dict by key, schema-collection by schema-name operations by id ''' pass def get_regular_properties(self, _type, *args, **kwargs): '''Make table with properties by schema_id :param str _type: :rtype: str ''' pass def get_type_description(self, _type, suffix='', *args, **kwargs): ''' Get description of type :param suffix: :param str _type: :rtype: str ''' pass def get_additional_properties(self, _type, *args, **kwargs): '''Make head and table with additional properties by schema_id :param str _type: :rtype: str ''' pass
6
4
24
1
19
6
6
0.29
1
9
4
0
3
0
4
13
103
8
77
20
71
22
54
19
49
7
3
3
23
7,360
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/parameter.py
swg2rst.swagger.parameter.Parameter
class Parameter(AbstractTypeObject): """ Represents Swagger Parameter Object """ def __init__(self, obj, **kwargs): super(Parameter, self).__init__(obj, **kwargs) self.location_in = obj['in'] self.required = obj.get('required', False) self.description = obj.get('description', '') self.default = obj.get('default') self.collection_format = obj.get('collectionFormat') self._set_type() def _set_type(self): if 'type' in self.raw: self._type = self.raw['type'] self.type_format = self.raw.get('format') if self.is_array: self.item = dict(zip( ('type', 'type_format', 'type_properties'), self.get_type_properties(self.raw['items'], self.name))) else: _, _, self.properties = self.get_type_properties(self.raw, self.name) elif 'schema' in self.raw: self.set_type_by_schema(self.raw['schema'], SchemaTypes.INLINE) else: raise ConverterError('Invalid structure') @property def type(self): if self.is_array: return 'array of {}'.format(self.item['type']) else: return self._type def __repr__(self): return '{}_{}'.format(self.location_in, self.name)
class Parameter(AbstractTypeObject): ''' Represents Swagger Parameter Object ''' def __init__(self, obj, **kwargs): pass def _set_type(self): pass @property def type(self): pass def __repr__(self): pass
6
1
8
0
7
0
2
0.06
1
5
2
0
4
9
4
12
37
4
31
15
25
2
24
14
19
4
2
2
8
7,361
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/abstract_type_object.py
swg2rst.swagger.abstract_type_object.AbstractTypeObject
class AbstractTypeObject(object): _type = None type_format = None properties = None item = None #: set if type is array def __init__(self, obj, name, root, storage): self.raw = obj self.name = name self.root = root self.storage = storage def get_type_properties(self, property_obj, name, additional_prop=False): """ Get internal properties of property (extended in schema) :param dict property_obj: raw property object :param str name: name of property :param bool additional_prop: recursion's param :return: Type, format and internal properties of property :rtype: tuple(str, str, dict) """ property_type = property_obj.get('type', 'object') property_format = property_obj.get('format') property_dict = {} if property_type in ['object', 'array']: schema_type = SchemaTypes.MAPPED if additional_prop else SchemaTypes.INLINE schema_id = self._get_object_schema_id(property_obj, schema_type) if not ('$ref' in property_obj or self.storage.get(schema_id)): _schema = self.storage.create_schema( property_obj, name, schema_type, root=self.root) self._after_create_schema(_schema) property_type = schema_id property_dict['default'] = property_obj.get('default') property_dict['maximum'] = property_obj.get('maximum') property_dict['exclusive_maximum'] = property_obj.get('exclusiveMaximum') property_dict['minimum'] = property_obj.get('minimum') property_dict['exclusive_minimum'] = property_obj.get('exclusiveMinimum') property_dict['max_length'] = property_obj.get('maxLength') property_dict['min_length'] = property_obj.get('minLength') #TODO: fixme. remove ugly convert. add property template renderer instead property_dict['enum'] = convert(property_obj.get('enum')) #TODO: fixme. cleanup empty properties. add configurable filter for properties instead property_dict = {k: v for k, v in property_dict.items() if v} return property_type, property_format, property_dict @staticmethod def _get_id(base): m = md5() m.update(base.encode('utf-8')) return m.hexdigest() def _get_object_schema_id(self, obj, schema_type): if (schema_type == SchemaTypes.prefixes[SchemaTypes.MAPPED]) and ('$ref' in obj): base = obj['$ref'] prefix = schema_type elif '$ref' in obj: base = obj['$ref'] prefix = SchemaTypes.prefixes[SchemaTypes.DEFINITION] else: base = json.dumps(obj) prefix = SchemaTypes.prefixes[schema_type] return '{}_{}'.format(prefix, self._get_id(base)) def set_type_by_schema(self, schema_obj, schema_type): """ Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type: """ schema_id = self._get_object_schema_id(schema_obj, schema_type) if not self.storage.contains(schema_id): schema = self.storage.create_schema( schema_obj, self.name, schema_type, root=self.root) assert schema.schema_id == schema_id self._type = schema_id def _after_create_schema(self, schema): pass @property def type(self): return self._type @property def is_array(self): return self._type == 'array'
class AbstractTypeObject(object): def __init__(self, obj, name, root, storage): pass def get_type_properties(self, property_obj, name, additional_prop=False): ''' Get internal properties of property (extended in schema) :param dict property_obj: raw property object :param str name: name of property :param bool additional_prop: recursion's param :return: Type, format and internal properties of property :rtype: tuple(str, str, dict) ''' pass @staticmethod def _get_id(base): pass def _get_object_schema_id(self, obj, schema_type): pass def set_type_by_schema(self, schema_obj, schema_type): ''' Set property type by schema object Schema will create, if it doesn't exists in collection :param dict schema_obj: raw schema object :param str schema_type: ''' pass def _after_create_schema(self, schema): pass @property def type(self): pass @property def is_array(self): pass
12
2
10
1
7
2
2
0.25
1
1
1
4
7
4
8
8
94
16
63
31
51
16
56
28
47
4
1
2
14
7,362
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/header.py
swg2rst.swagger.header.Header
class Header(AbstractTypeObject): """ Represents Swagger Header Object """ def __init__(self, obj, **kwargs): super(Header, self).__init__(obj, **kwargs) self.description = obj.get('description') self._set_type() def _set_type(self): self._type = self.raw['type'] if self._type not in PRIMITIVE_TYPES and self._type != 'array': raise ConverterError( 'Invalid type of response header {}'.format(self.name)) self.type_format = self.raw.get('format') if self.is_array: self.item = dict(zip( ('type', 'type_format', 'type_properties'), self.get_type_properties(self.raw['items'], self.name))) else: _, _, self.properties = self.get_type_properties(self.raw, self.name)
class Header(AbstractTypeObject): ''' Represents Swagger Header Object ''' def __init__(self, obj, **kwargs): pass def _set_type(self): pass
3
1
9
1
8
0
2
0.18
1
4
1
0
2
5
2
10
23
3
17
8
14
3
13
8
10
3
2
1
4
7,363
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/constants.py
swg2rst.swagger.constants.SecurityTypes
class SecurityTypes(object): """ Types of the security scheme """ BASIC = 'basic' OAUTH2 = 'oauth2' API_KEY = 'apiKey' names = { BASIC: 'HTTP Basic Authentication', OAUTH2: 'OAuth 2.0', API_KEY: 'API Key', }
class SecurityTypes(object): ''' Types of the security scheme ''' pass
1
1
0
0
0
0
0
0.22
1
0
0
0
0
0
0
0
12
1
9
5
8
2
5
5
4
0
1
0
0
7,364
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/constants.py
swg2rst.swagger.constants.SchemaTypes
class SchemaTypes(object): """ Types of the schema object """ INLINE = 'inline' DEFINITION = 'definition' MAPPED = 'mapped' prefixes = { INLINE: INLINE[0], DEFINITION: DEFINITION[0], MAPPED: MAPPED[0], }
class SchemaTypes(object): ''' Types of the schema object ''' pass
1
1
0
0
0
0
0
0.22
1
0
0
0
0
0
0
0
12
1
9
5
8
2
5
5
4
0
1
0
0
7,365
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/base_swagger_object.py
swg2rst.swagger.base_swagger_object.BaseSwaggerObject
class BaseSwaggerObject(SecurityMixin): """ Represents Swagger Object """ raw = None #: Operation collection #: #: key: operation_id, value: Operation object operations = None #: Operations grouped by tags #: #: key: tag name, value: list of Operation object tags = None schemas = SchemaObjects #: Parameter definitions from Parameters Definitions Object #: #: key: reference path, value: Parameter object parameter_definitions = None #: Response definitions from Responses Definitions Object #: #: key: reference path, value: Response object response_definitions = None #: Security definitions from Security Definitions Object #: #: key: security name, value: SecurityDefinition object security_definitions = None #: Represents tag descriptions from Swagger Tag Object #: #: key: tag name, value: dict with keys ``description`` and ``externalDocs`` tag_descriptions = None #: Example Manager. Must be subclass of Exampilator exampilator = None def __init__(self, obj, exampilator=None, examples=None): self.exampilator = exampilator or Exampilator assert issubclass(self.exampilator, Exampilator) if examples: try: self.exampilator.schema_validate(examples, examples_json_schema) except ValidationError as err: raise ConverterError(err.message) self.exampilator.fill_examples(examples) if obj.get('swagger') != '2.0': raise ConverterError('Invalid Swagger version') self._fill_root_parameters(obj) self._fill_schemas_from_definitions(obj) self._fill_parameter_definitions(obj) self._fill_response_definitions(obj) self._fill_security_definitions(obj) self._fill_securities(obj) self._fill_operations(obj) def _fill_operations(self, *args): self.operations = {} self._fill_tag_descriptions() self.tags = defaultdict(list) for path, operations in self.raw['paths'].items(): path_params = [] for param in operations.get('parameters', []): if param.get('$ref'): path_params.append(self.parameter_definitions[param['$ref']]) else: path_params.append( Parameter(param, name=param['name'], root=self, storage=self.schemas)) for method, operation in operations.items(): if method == 'parameters': continue op = Operation(operation, method, path, self, self.schemas, path_params) self.operations[op.operation_id] = op for tag in op.tags: self.tags[tag].append(op) def _fill_tag_descriptions(self): if 'tags' in self.raw: self.tag_descriptions = {} for tag in self.raw['tags']: if 'description' in tag or 'externalDocs' in tag: self.tag_descriptions[tag['name']] = { 'description': tag.get('description'), 'externalDocs': tag.get('externalDocs') } def _fill_schemas_from_definitions(self, obj): """At first create schemas without 'AllOf' :param obj: :return: None """ if obj.get('definitions'): self.schemas.clear() all_of_stack = [] for name, definition in obj['definitions'].items(): if 'allOf' in definition: all_of_stack.append((name, definition)) else: self.schemas.create_schema( definition, name, SchemaTypes.DEFINITION, root=self) while all_of_stack: name, definition = all_of_stack.pop(0) self.schemas.create_schema( definition, name, SchemaTypes.DEFINITION, root=self) def _fill_parameter_definitions(self, obj): if obj.get('parameters'): self.parameter_definitions = {} for name, parameter in obj['parameters'].items(): key = '#/parameters/{}'.format(name) self.parameter_definitions[key] = Parameter( parameter, name=parameter['name'], root=self, storage=self.schemas) def _fill_response_definitions(self, obj): if obj.get('responses'): self.response_definitions = {} for name, response in obj['responses'].items(): key = '#/responses/{}'.format(name) self.response_definitions[key] = Response( response, name=name, root=self, storage=self.schemas) def _fill_security_definitions(self, obj): if obj.get('securityDefinitions'): self.security_definitions = { name: SecurityDefinition(name, _obj) for name, _obj in obj['securityDefinitions'].items() } def _fill_root_parameters(self, obj): if not obj: return None self.raw = obj self.info = obj.get('info') self.host = obj.get('host', '') self.base_path = obj.get('basePath', '') self.consumes = obj.get('consumes', ['application/json']) self.produces = obj.get('produces', ['application/json']) self.schemes = obj.get('schemes', ['http']) self.external_docs = obj.get('externalDocs')
class BaseSwaggerObject(SecurityMixin): ''' Represents Swagger Object ''' def __init__(self, obj, exampilator=None, examples=None): pass def _fill_operations(self, *args): pass def _fill_tag_descriptions(self): pass def _fill_schemas_from_definitions(self, obj): '''At first create schemas without 'AllOf' :param obj: :return: None ''' pass def _fill_parameter_definitions(self, obj): pass def _fill_response_definitions(self, obj): pass def _fill_security_definitions(self, obj): pass def _fill_root_parameters(self, obj): pass
9
2
12
0
11
1
4
0.28
1
9
7
1
8
7
8
9
145
19
100
39
91
28
88
38
79
7
2
3
30
7,366
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/converter_exceptions.py
swg2rst.converter_exceptions.ConverterError
class ConverterError(Exception): pass
class ConverterError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
7,367
Arello-Mobile/swagger2rst
Arello-Mobile_swagger2rst/swg2rst/swagger/operation.py
swg2rst.swagger.operation.Operation
class Operation(SecurityMixin): """ Represents Swagger Operation Object """ parameters = None responses = None method = None path = None root = None #: root swagger object def __init__(self, obj, method, path, root, storage, path_params=None): self.method = method self.path = path self.root = root self.storage = storage self.operation_id = obj.get( 'operationId', self.get_operation_id(method, path)) self.summary = obj.get('summary') self.description = obj.get('description') self.consumes = obj.get('consumes', self.root.consumes) self.produces = obj.get('produces', self.root.produces) self.schemes = obj.get('schemes', self.root.schemes) self._fill_parameters(obj.get('parameters', []), path_params) self._fill_responses(obj['responses']) self.deprecated = obj.get('deprecated', False) self.tags = obj.get('tags', ['default']) self.external_docs = obj.get('externalDocs') self._fill_securities(obj) @staticmethod def get_operation_id(method, path): op_id = '{}_{}'.format(method, path) # copy-paste from swagger-js op_id = re.sub(r'[\s!@#$%^&*()+=\[{\]};:<>|./?,\'"-]', '_', op_id) op_id = re.sub(r'(_){2,}', '_', op_id) op_id = re.sub(r'^[_]*', '', op_id) op_id = re.sub(r'([_]*)$', '', op_id) return op_id def _fill_parameters(self, params, path_params): self.parameters = [] for obj in params: if '$ref' in obj: self.parameters.append(self.root.parameter_definitions[obj['$ref']]) else: self.parameters.append( Parameter(obj, name=obj['name'], root=self.root, storage=self.storage)) if path_params: self.parameters += path_params if len(self.get_parameters_by_location(['body'])) > 1: raise ConverterError( 'Invalid source file: More than one body parameters in %s' % self.path) def _fill_responses(self, responses): self.responses = {} for code, obj in responses.items(): if '$ref' in obj: self.responses[code] = self.root.response_definitions[obj['$ref']] else: self.responses[code] = Response(obj, name=code, root=self.root, storage=self.storage) def get_parameters_by_location(self, locations=None, excludes=None): """ Get parameters list by location :param locations: list of locations :type locations: list or None :param excludes: list of excludes locations :type excludes: list or None :return: list of Parameter :rtype: list """ result = self.parameters if locations: result = filter(lambda x: x.location_in in locations, result) if excludes: result = filter(lambda x: x.location_in not in excludes, result) return list(result) @cached_property def body(self): """ Return body request parameter :return: Body parameter :rtype: Parameter or None """ body = self.get_parameters_by_location(['body']) return self.root.schemas.get(body[0].type) if body else None
class Operation(SecurityMixin): ''' Represents Swagger Operation Object ''' def __init__(self, obj, method, path, root, storage, path_params=None): pass @staticmethod def get_operation_id(method, path): pass def _fill_parameters(self, params, path_params): pass def _fill_responses(self, responses): pass def get_parameters_by_location(self, locations=None, excludes=None): ''' Get parameters list by location :param locations: list of locations :type locations: list or None :param excludes: list of excludes locations :type excludes: list or None :return: list of Parameter :rtype: list ''' pass @cached_property def body(self): ''' Return body request parameter :return: Body parameter :rtype: Parameter or None ''' pass
9
3
12
1
9
2
3
0.29
1
5
3
0
5
10
6
7
89
10
63
29
54
18
56
27
49
5
2
2
15
7,368
Arkq/flake8-requirements
test/test_setup.py
test_setup.SetupTestCase
class SetupTestCase(unittest.TestCase): def test_detect_setup(self): code = "setup({})".format(",".join(( "name='A'", "version='1'", "author='A'", "packages=['']", "url='URL'", ))) setup = SetupVisitor(ast.parse(code), "") self.assertEqual(setup.redirected, True) self.assertDictEqual(setup.keywords, { 'name': 'A', 'version': '1', 'packages': [''], 'author': 'A', 'url': 'URL', }) code = "setup({})".format(",".join( "{}='{}'".format(x, x) for x in SetupVisitor.attributes )) setup = SetupVisitor(ast.parse(code), "") self.assertEqual(setup.redirected, True) self.assertDictEqual(setup.keywords, { x: x for x in SetupVisitor.attributes }) code = "setup({})".format(",".join(( "name='A'", "version='1'", "package='ABC'", "processing=True", "verbose=True", ))) setup = SetupVisitor(ast.parse(code), "") self.assertEqual(setup.redirected, False) def test_detect_setup_wrong_num_of_args(self): setup = SetupVisitor(ast.parse("setup(name='A')"), "") self.assertEqual(setup.redirected, False) def test_detect_setup_wrong_function(self): setup = SetupVisitor(ast.parse("setup(1, name='A')"), "") self.assertEqual(setup.redirected, False) def test_detect_setup_oops(self): setup = SetupVisitor(ast.parse("\n".join(( "from .myModule import setup", "setup({})".format(",".join(( "name='A'", "version='1'", "author='A'", "packages=['']", "url='URL'", ))), ))), "") self.assertEqual(setup.redirected, False) def test_get_requirements(self): setup = SetupVisitor(ast.parse("setup(**{})".format(str({ 'name': 'A', 'version': '1', 'packages': [''], 'install_requires': ["ABC > 1.0.0", "bar.cat > 2, < 3"], 'extras_require': { 'extra': ["extra < 10"], }, }))), "") self.assertEqual(setup.redirected, True) self.assertEqual( sorted(setup.get_requirements(), key=lambda x: x.project_name), sorted(parse_requirements([ "ABC > 1.0.0", "bar.cat > 2, < 3", "extra < 10", ]), key=lambda x: x.project_name), ) def test_get_setup_cfg_requirements(self): curdir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(curdir, "test_setup.cfg")) as f: content = f.read() with mock.patch('builtins.open', mock_open(read_data=content)): checker = Flake8Checker(None, None) self.assertEqual( checker.get_setup_cfg_requirements(False), list(parse_requirements([ "requests", "importlib; python_version == \"2.6\"", "pytest", "ReportLab>=1.2", "docutils>=0.3", ])), )
class SetupTestCase(unittest.TestCase): def test_detect_setup(self): pass def test_detect_setup_wrong_num_of_args(self): pass def test_detect_setup_wrong_function(self): pass def test_detect_setup_oops(self): pass def test_get_requirements(self): pass def test_get_setup_cfg_requirements(self): pass
7
0
15
0
15
0
1
0
1
4
2
0
6
0
6
78
97
8
89
17
82
0
33
16
26
1
2
1
6
7,369
Arkq/flake8-requirements
test/test_requirements.py
test_requirements.RequirementsTestCase
class RequirementsTestCase(unittest.TestCase): def setUp(self): memoize.mem = {} def test_resolve_requirement(self): self.assertEqual( Flake8Checker.resolve_requirement("foo >= 1.0.0"), ["foo >= 1.0.0"], ) def test_resolve_requirement_with_option(self): self.assertEqual( Flake8Checker.resolve_requirement("foo-bar.v1==1.0 --hash=md5:."), ["foo-bar.v1==1.0"], ) def test_resolve_requirement_standalone_option(self): self.assertEqual( Flake8Checker.resolve_requirement("--extra-index-url"), [], ) def test_resolve_requirement_with_file_beyond_max_depth(self): with self.assertRaises(RuntimeError): Flake8Checker.resolve_requirement("-r requirements.txt") def test_resolve_requirement_with_file_empty(self): with mock.patch('builtins.open', mock_open()) as m: self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 1), [], ) m.assert_called_once_with("requirements.txt") def test_resolve_requirement_with_file_content(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo >= 1.0.0\nbar <= 1.0.0\n"), )))): self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 1), ["foo >= 1.0.0", "bar <= 1.0.0"], ) def test_resolve_requirement_with_file_content_line_continuation(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo[bar] \\\n>= 1.0.0\n"), )))): self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 1), ["foo[bar] >= 1.0.0"], ) def test_resolve_requirement_with_file_content_line_continuation_2(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo \\\n>= 1.0.0 \\\n# comment \\\nbar \\"), )))): self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 1), ["foo >= 1.0.0", "bar"], ) def test_resolve_requirement_with_file_recursion_beyond_max_depth(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "-r requirements.txt\n"), )))): with self.assertRaises(RuntimeError): Flake8Checker.resolve_requirement("-r requirements.txt", 1), def test_resolve_requirement_with_file_recursion(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "--requirement inner.txt\nbar <= 1.0.0\n"), ("inner.txt", "# inner\nbaz\n\nqux\n"), )))): self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 2), ["baz", "qux", "bar <= 1.0.0"], ) def test_resolve_requirement_with_relative_include(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "-r requirements/production.txt"), ("requirements/production.txt", "-r node/one.txt\nfoo"), ("requirements/node/one.txt", "-r common.txt\n-r /abs/path.txt"), ("requirements/node/common.txt", "bar"), ("/abs/path.txt", "bis"), )))) as m: self.assertEqual( Flake8Checker.resolve_requirement("-r requirements.txt", 5), ["bar", "bis", "foo"], ) m.assert_has_calls([ mock.call("requirements.txt"), mock.call("requirements/production.txt"), mock.call("requirements/node/one.txt"), mock.call("requirements/node/common.txt"), mock.call("/abs/path.txt"), ]) def test_init_with_no_requirements(self): with mock.patch('builtins.open', mock_open()) as m: m.side_effect = IOError("No such file or directory"), checker = Flake8Checker(None, None) self.assertEqual(checker.get_requirements_txt(), ()) def test_init_with_user_requirements(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements/base.txt", "foo >= 1.0.0\n-r inner.txt\n"), ("requirements/inner.txt", "bar\n"), )))) as m: try: Flake8Checker.requirements_file = "requirements/base.txt" checker = Flake8Checker(None, None) self.assertEqual( checker.get_requirements_txt(), tuple(parse_requirements([ "foo >= 1.0.0", "bar", ])), ) m.assert_has_calls([ mock.call("requirements/base.txt"), mock.call("requirements/inner.txt"), ]) finally: Flake8Checker.requirements_file = None def test_init_with_simple_requirements(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo >= 1.0.0\nbar <= 1.0.0\n"), )))): checker = Flake8Checker(None, None) self.assertEqual( checker.get_requirements_txt(), tuple(parse_requirements([ "foo >= 1.0.0", "bar <= 1.0.0", ])), ) def test_init_with_recursive_requirements_beyond_max_depth(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo >= 1.0.0\n-r inner.txt\nbar <= 1.0.0\n"), ("inner.txt", "# inner\nbaz\n\nqux\n"), )))): with self.assertRaises(RuntimeError): try: Flake8Checker.requirements_max_depth = 0 checker = Flake8Checker(None, None) checker.get_requirements_txt() finally: Flake8Checker.requirements_max_depth = 1 def test_init_with_recursive_requirements(self): with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", "foo >= 1.0.0\n-r inner.txt\nbar <= 1.0.0\n"), ("inner.txt", "# inner\nbaz\n\nqux\n"), )))): checker = Flake8Checker(None, None) self.assertEqual( checker.get_requirements_txt(), tuple(parse_requirements([ "foo >= 1.0.0", "baz", "qux", "bar <= 1.0.0", ])), ) def test_init_misc(self): curdir = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(curdir, "test_requirements.txt")) as f: requirements_content = f.read() with mock.patch('builtins.open', mock_open_multiple(files=OrderedDict(( ("requirements.txt", requirements_content), )))): checker = Flake8Checker(None, None) self.assertEqual( checker.get_requirements_txt(), tuple(parse_requirements([ "nose", "apache == 0.6.9", "coverage[graph,test] ~= 3.1", "graph <2.0, >=1.2 ; python_version < '3.8'", "foo-project >= 1.2", "bar-project == 8.8", "configuration", "blackBox == 1.4.4", "exPackage_paint == 1.4.8.dev1984+49a8814", "package-one", "package-two", "whiteBox", ])), )
class RequirementsTestCase(unittest.TestCase): def setUp(self): pass def test_resolve_requirement(self): pass def test_resolve_requirement_with_option(self): pass def test_resolve_requirement_standalone_option(self): pass def test_resolve_requirement_with_file_beyond_max_depth(self): pass def test_resolve_requirement_with_file_empty(self): pass def test_resolve_requirement_with_file_content(self): pass def test_resolve_requirement_with_file_content_line_continuation(self): pass def test_resolve_requirement_with_file_content_line_continuation_2(self): pass def test_resolve_requirement_with_file_recursion_beyond_max_depth(self): pass def test_resolve_requirement_with_file_recursion_beyond_max_depth(self): pass def test_resolve_requirement_with_relative_include(self): pass def test_init_with_no_requirements(self): pass def test_init_with_user_requirements(self): pass def test_init_with_simple_requirements(self): pass def test_init_with_recursive_requirements_beyond_max_depth(self): pass def test_init_with_recursive_requirements_beyond_max_depth(self): pass def test_init_misc(self): pass
19
0
10
0
10
0
1
0.02
1
4
1
0
18
0
18
90
194
18
176
32
157
4
72
27
53
1
2
3
18
7,370
Arkq/flake8-requirements
test/test_poetry.py
test_poetry.PoetryTestCase
class PoetryTestCase(unittest.TestCase): def setUp(self): memoize.mem = {} def test_get_pyproject_toml_poetry(self): content = b"[tool.poetry]\nname='x'\n[tool.poetry.tag]\nx=0\n" with mock.patch('builtins.open', mock_open(read_data=content)): poetry = Flake8Checker.get_pyproject_toml_poetry() self.assertDictEqual(poetry, {'name': "x", 'tag': {'x': 0}}) def test_1st_party(self): content = b"[tool.poetry]\nname='book'\n" with mock.patch('builtins.open', mock_open()) as m: m.side_effect = ( IOError("No such file or directory: 'setup.py'"), IOError("No such file or directory: 'setup.cfg'"), mock_open(read_data=content).return_value, ) checker = Flake8Checker(None, None) mods = checker.get_mods_1st_party() self.assertEqual(mods, ModuleSet({"book": {}})) def test_3rd_party(self): content = b"[tool.poetry.dependencies]\ntools='1.0'\n" content += b"[tool.poetry.dev-dependencies]\ndev-tools='1.0'\n" with mock.patch('builtins.open', mock_open()) as m: m.side_effect = ( IOError("No such file or directory: 'setup.py'"), IOError("No such file or directory: 'setup.cfg'"), mock_open(read_data=content).return_value, ) checker = Flake8Checker(None, None) mods = checker.get_mods_3rd_party(False) self.assertEqual(mods, ModuleSet({"tools": {}, "dev_tools": {}})) def test_3rd_party_groups(self): content = b"[tool.poetry.dependencies]\ntools='1.0'\n" content += b"[tool.poetry.group.dev.dependencies]\ndev-tools='1.0'\n" with mock.patch('builtins.open', mock_open()) as m: m.side_effect = ( IOError("No such file or directory: 'setup.py'"), IOError("No such file or directory: 'setup.cfg'"), mock_open(read_data=content).return_value, ) checker = Flake8Checker(None, None) mods = checker.get_mods_3rd_party(False) self.assertEqual(mods, ModuleSet({"tools": {}, "dev_tools": {}}))
class PoetryTestCase(unittest.TestCase): def setUp(self): pass def test_get_pyproject_toml_poetry(self): pass def test_1st_party(self): pass def test_3rd_party(self): pass def test_3rd_party_groups(self): pass
6
0
10
1
8
0
1
0
1
2
2
0
5
0
5
77
54
11
43
20
37
0
31
17
25
1
2
1
5
7,371
Arkq/flake8-requirements
test/test_pep621.py
test_pep621.Flake8Options
class Flake8Options: known_modules = "" requirements_file = None requirements_max_depth = 1 scan_host_site_packages = False
class Flake8Options: pass
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
5
0
5
5
4
0
5
5
4
0
0
0
0
7,372
Arkq/flake8-requirements
test/test_checker.py
test_checker.SetupVisitorMock
class SetupVisitorMock(checker.SetupVisitor): def __init__(self): self.redirected = True self.keywords = { 'name': "flake8-requires", 'install_requires': [ "foo", "bar", "hyp-hen", "python-boom", "python-snake", "pillow", "space.module", ], }
class SetupVisitorMock(checker.SetupVisitor): def __init__(self): pass
2
0
14
0
14
0
1
0
1
0
0
0
1
2
1
7
16
1
15
4
13
0
4
4
2
1
3
0
1
7,373
Arkq/flake8-requirements
test/test_checker.py
test_checker.Flake8OptionManagerMock
class Flake8OptionManagerMock(dict): def add_option(self, name, **kw): self[name] = kw
class Flake8OptionManagerMock(dict): def add_option(self, name, **kw): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
28
4
1
3
2
1
0
3
2
1
1
2
0
1
7,374
Arkq/flake8-requirements
test/test_checker.py
test_checker.Flake8CheckerTestCase
class Flake8CheckerTestCase(unittest.TestCase): def test_add_options(self): manager = Flake8OptionManagerMock() Flake8Checker.add_options(manager) self.assertEqual( sorted(manager.keys()), ['--known-modules', '--requirements-file', '--requirements-max-depth', '--scan-host-site-packages'], ) def test_stdlib(self): errors = check("import os\nfrom unittest import TestCase") self.assertEqual(len(errors), 0) def test_stdlib_case(self): errors = check("from cProfile import Profile") self.assertEqual(len(errors), 0) errors = check("from cprofile import Profile") self.assertEqual(len(errors), 1) self.assertEqual( errors[0][2], "I900 'cprofile' not listed as a requirement", ) def test_1st_party(self): errors = check("import flake8_requires") self.assertEqual(len(errors), 0) def test_3rd_party(self): errors = check("import foo\nfrom bar import Bar") self.assertEqual(len(errors), 0) def test_3rd_party_python_prefix(self): errors = check("from boom import blast") self.assertEqual(len(errors), 0) def test_3rd_party_python_prefix_no_strip(self): errors = check("import python_snake as snake") self.assertEqual(len(errors), 0) def test_3rd_party_missing(self): errors = check("import os\nfrom cat import Cat") self.assertEqual(len(errors), 1) self.assertEqual( errors[0][2], "I900 'cat' not listed as a requirement", ) def test_3rd_party_hyphen(self): errors = check("from hyp_hen import Hyphen") self.assertEqual(len(errors), 0) def test_3rd_party_known_module(self): errors = check("import PIL") self.assertEqual(len(errors), 0) def test_non_top_level_import(self): errors = check("def function():\n import cat") self.assertEqual(len(errors), 1) self.assertEqual( errors[0][2], "I900 'cat' not listed as a requirement", ) def test_namespace(self): errors = check("import space.module") self.assertEqual(len(errors), 0) errors = check("from space import module") self.assertEqual(len(errors), 0) errors = check("import space") self.assertEqual(len(errors), 1) def test_relative(self): errors = check("from . import local") self.assertEqual(len(errors), 0) errors = check("from ..local import local") self.assertEqual(len(errors), 0) def test_discover_host_3rd_party_modules(self): class Options(Flake8Options): scan_host_site_packages = True Flake8Checker.parse_options(Options) self.assertEqual( type(Flake8Checker.known_host_3rd_parties), dict, ) # Since flake8-requirements (this package) is a plugin for flake8, it # is very likely that one will have flake8 installed in the host # site-packages. However, that is not the case for our GitHub Actions # runners, so we can not enforce this assertion. if 'flake8' in Flake8Checker.known_host_3rd_parties: self.assertEqual( Flake8Checker.known_host_3rd_parties['flake8'], ['flake8'], ) def test_custom_mapping_parser(self): class Options(Flake8Options): known_modules = ":[pydrmcodec],mylib:[mylib.drm,mylib.ex]" Flake8Checker.parse_options(Options) self.assertEqual( Flake8Checker.known_modules, {"": ["pydrmcodec"], "mylib": ["mylib.drm", "mylib.ex"]}, ) def test_custom_mapping(self): class Options(Flake8Options): known_modules = "flake8-requires:[flake8req]" errors = check("from flake8req import mymodule", options=Options) self.assertEqual(len(errors), 0) def test_setup_py(self): errors = check("from setuptools import setup", "setup.py") self.assertEqual(len(errors), 0) # mods_3rd_party errors = check("from setuptools import setup", "xxx.py") self.assertEqual(len(errors), 1) self.assertEqual( errors[0][2], "I900 'setuptools' not listed as a requirement", )
class Flake8CheckerTestCase(unittest.TestCase): def test_add_options(self): pass def test_stdlib(self): pass def test_stdlib_case(self): pass def test_1st_party(self): pass def test_3rd_party(self): pass def test_3rd_party_python_prefix(self): pass def test_3rd_party_python_prefix_no_strip(self): pass def test_3rd_party_missing(self): pass def test_3rd_party_hyphen(self): pass def test_3rd_party_known_module(self): pass def test_non_top_level_import(self): pass def test_namespace(self): pass def test_relative(self): pass def test_discover_host_3rd_party_modules(self): pass class Options(Flake8Options): def test_custom_mapping_parser(self): pass class Options(Flake8Options): def test_custom_mapping_parser(self): pass class Options(Flake8Options): def test_setup_py(self): pass
21
0
6
0
6
0
1
0.05
1
7
5
0
17
0
17
89
122
17
100
39
79
5
75
39
54
2
2
1
18
7,375
Arkq/flake8-requirements
test/test_checker.py
test_checker.Flake8Checker
class Flake8Checker(checker.Flake8Checker): @classmethod def get_setup_py(cls): return SetupVisitorMock() @staticmethod def is_project_setup_py(project_root_dir, filename): return filename == "setup.py"
class Flake8Checker(checker.Flake8Checker): @classmethod def get_setup_py(cls): pass @staticmethod def is_project_setup_py(project_root_dir, filename): pass
5
0
2
0
2
0
1
0
1
1
1
0
0
0
2
26
9
2
7
5
2
0
5
3
2
1
2
0
2
7,376
Arkq/flake8-requirements
test/test_pep621.py
test_pep621.Pep621TestCase
class Pep621TestCase(unittest.TestCase): content = b""" [project] name="test" dependencies=["tools==1.0"] [project.optional-dependencies] dev = ["dev-tools==1.0"] """ def setUp(self): memoize.mem = {} def tearDown(self): Flake8Checker.root_dir = "" def test_pyproject_custom_mapping_parser(self): class Options(Flake8Options): known_modules = {"mylib": ["mylib.drm", "mylib.ex"]} Flake8Checker.parse_options(Options) self.assertEqual( Flake8Checker.known_modules, {"mylib": ["mylib.drm", "mylib.ex"]}, ) def test_get_pyproject_toml_pep621(self): with mock.patch('builtins.open', mock_open(read_data=self.content)): pep621 = Flake8Checker.get_pyproject_toml_pep621() expected = { "name": "test", "dependencies": ["tools==1.0"], "optional-dependencies": { "dev": ["dev-tools==1.0"] }, } self.assertDictEqual(pep621, expected) def test_get_pyproject_toml_invalid(self): content = self.content + b"invalid" with mock.patch('builtins.open', mock_open(read_data=content)): self.assertDictEqual(Flake8Checker.get_pyproject_toml_pep621(), {}) def test_1st_party(self): with mock.patch('builtins.open', mock_open()) as m: m.side_effect = ( IOError("No such file or directory: 'setup.py'"), IOError("No such file or directory: 'setup.cfg'"), mock_open(read_data=self.content).return_value, ) checker = Flake8Checker(None, None) mods = checker.get_mods_1st_party() self.assertEqual(mods, ModuleSet({"test": {}})) def test_3rd_party(self): with mock.patch('builtins.open', mock_open()) as m: m.side_effect = ( IOError("No such file or directory: 'setup.py'"), IOError("No such file or directory: 'setup.cfg'"), mock_open(read_data=self.content).return_value, ) checker = Flake8Checker(None, None) mods = checker.get_mods_3rd_party(False) self.assertEqual(mods, ModuleSet({"tools": {}, "dev_tools": {}})) def test_dynamic_requirements(self): requirements_content = "package1\npackage2>=2.0" data = { "project": {"dynamic": ["dependencies"]}, "tool": { "setuptools": { "dynamic": {"dependencies": {"file": ["requirements.txt"]}} } }, } with patch( 'flake8_requirements.checker.Flake8Checker.get_pyproject_toml', return_value=data, ): with patch( 'builtins.open', mock_open(read_data=requirements_content) ): result = Flake8Checker.get_setuptools_dynamic_requirements() expected_results = ['package1', 'package2>=2.0'] parsed_results = [str(req) for req in result] self.assertEqual(parsed_results, expected_results) def test_dynamic_optional_dependencies(self): data = { "project": {"dynamic": ["dependencies", "optional-dependencies"]}, "tool": { "setuptools": { "dynamic": { "dependencies": {"file": ["requirements.txt"]}, "optional-dependencies": { "test": {"file": ["optional-requirements.txt"]} }, } } }, } requirements_content = """ package1 package2>=2.0 """ optional_requirements_content = "package3[extra] >= 3.0" with mock.patch( 'flake8_requirements.checker.Flake8Checker.get_pyproject_toml', return_value=data, ): with mock.patch('builtins.open', mock.mock_open()) as mocked_file: mocked_file.side_effect = [ mock.mock_open( read_data=requirements_content ).return_value, mock.mock_open( read_data=optional_requirements_content ).return_value, ] result = Flake8Checker.get_setuptools_dynamic_requirements() expected = list(parse_requirements(requirements_content)) expected += list( parse_requirements(optional_requirements_content) ) self.assertEqual(len(result), len(expected)) for i in range(len(result)): self.assertEqual(result[i], expected[i]) def test_missing_requirements_file(self): data = { "project": {"dynamic": ["dependencies"]}, "tool": { "setuptools": { "dynamic": { "dependencies": { "file": ["nonexistent-requirements.txt"] } } } }, } with mock.patch( 'flake8_requirements.checker.Flake8Checker.get_pyproject_toml', return_value=data, ): result = Flake8Checker.get_setuptools_dynamic_requirements() self.assertEqual(result, [])
class Pep621TestCase(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_pyproject_custom_mapping_parser(self): pass class Options(Flake8Options): def test_get_pyproject_toml_pep621(self): pass def test_get_pyproject_toml_invalid(self): pass def test_1st_party(self): pass def test_3rd_party(self): pass def test_dynamic_requirements(self): pass def test_dynamic_optional_dependencies(self): pass def test_missing_requirements_file(self): pass
12
0
13
0
13
0
1
0
1
6
3
0
10
0
10
82
150
15
135
37
117
0
59
34
47
2
2
3
11
7,377
Arkq/flake8-requirements
src/flake8_requirements/checker.py
flake8_requirements.checker.ModuleSet
class ModuleSet(dict): """Radix-tree-like structure for modules lookup.""" requirement = None def add(self, module, requirement): for mod in module: self = self.setdefault(mod, ModuleSet()) self.requirement = requirement def __contains__(self, module): for mod in module: self = self.get(mod) if self is None: return False if self.requirement is not None: return True return False
class ModuleSet(dict): '''Radix-tree-like structure for modules lookup.''' def add(self, module, requirement): pass def __contains__(self, module): pass
3
1
6
0
6
0
3
0.07
1
0
0
0
2
0
2
29
18
3
14
6
11
1
14
6
11
4
2
2
6
7,378
Arkq/flake8-requirements
src/flake8_requirements/checker.py
flake8_requirements.checker.ImportVisitor
class ImportVisitor(ast.NodeVisitor): """Import statement visitor.""" # Convenience structure for storing import statement. Import = namedtuple('Import', ('line', 'offset', 'module')) def __init__(self, tree): """Initialize import statement visitor.""" self.imports = [] self.visit(tree) def visit_Import(self, node): self.imports.append(ImportVisitor.Import( node.lineno, node.col_offset, modsplit(node.names[0].name), )) def visit_ImportFrom(self, node): if node.level != 0: # Omit relative imports (local modules). return self.imports.append(ImportVisitor.Import( node.lineno, node.col_offset, # Module name which covers: # > from namespace import module modsplit(node.module) + modsplit(node.names[0].name), ))
class ImportVisitor(ast.NodeVisitor): '''Import statement visitor.''' def __init__(self, tree): '''Initialize import statement visitor.''' pass def visit_Import(self, node): pass def visit_ImportFrom(self, node): pass
4
2
7
0
6
1
1
0.32
1
0
0
0
3
1
3
6
29
4
19
6
15
6
11
6
7
2
2
1
4
7,379
Arkq/flake8-requirements
src/flake8_requirements/checker.py
flake8_requirements.checker.Flake8Checker
class Flake8Checker(object): """Package requirements checker.""" name = "flake8-requirements" version = __version__ # Build-in mapping for known 3rd party modules. known_3rd_parties = { k: v for k, v in KNOWN_3RD_PARTIES.items() for k in project2modules(k) } # Host-based mapping for 3rd party modules. known_host_3rd_parties = {} # Collect and report I901 errors error_I901_enabled = False # User defined project->modules mapping. known_modules = {} # User provided requirements file. requirements_file = None # Max depth to resolve recursive requirements. requirements_max_depth = 1 # Root directory of the project. root_dir = "" def __init__(self, tree, filename, lines=None): """Initialize requirements checker.""" self.tree = tree self.filename = filename self.lines = lines @classmethod def add_options(cls, manager): """Register plug-in specific options.""" manager.add_option( "--known-modules", action='store', default="", parse_from_config=True, help=( "User defined mapping between a project name and a list of" " provided modules. For example: ``--known-modules=project:" "[Project],extra-project:[extras,utilities]``." )) manager.add_option( "--requirements-file", action='store', parse_from_config=True, help=( "Specify the name (location) of the requirements text file. " "Unless an absolute path is given, the file will be searched " "relative to the project's root directory. If this option is " "not specified, the plugin look up for requirements in " "(1) setup.py, (2) setup.cfg, (3) pyproject.toml, and (4) " "requirements.txt. If specified, look up will not take place." )) manager.add_option( "--requirements-max-depth", type=int, default=1, parse_from_config=True, help=( "Max depth to resolve recursive requirements. Defaults to 1 " "(one level of recursion allowed)." )) manager.add_option( "--scan-host-site-packages", action='store_true', parse_from_config=True, help=( "Scan host's site-packages directory for 3rd party projects, " "which provide more than one module or the name of the module" " is different than the project name itself." )) @classmethod def parse_options(cls, options): """Parse plug-in specific options.""" if isinstance(options.known_modules, dict): # Support for nicer known-modules using flake8-pyproject. cls.known_modules = { k: v for k, v in options.known_modules.items() for k in project2modules(k) } else: cls.known_modules = { k: v.split(",") for k, v in [ x.split(":[") for x in re.split(r"],?", options.known_modules)[:-1]] for k in project2modules(k) } cls.requirements_file = options.requirements_file cls.requirements_max_depth = options.requirements_max_depth if options.scan_host_site_packages: cls.known_host_3rd_parties = cls.discover_host_3rd_party_modules() cls.root_dir = cls.discover_project_root_dir(os.getcwd()) @staticmethod def discover_host_3rd_party_modules(): """Scan host site-packages for 3rd party modules.""" mapping = {} try: site_packages_dirs = site.getsitepackages() site_packages_dirs.append(site.getusersitepackages()) except AttributeError as e: LOG.error("Couldn't get site packages: %s", e) return mapping for site_dir in site_packages_dirs: try: dir_entries = os.listdir(site_dir) except IOError: continue for egg in (x for x in dir_entries if x.endswith(".egg-info")): pkg_info_path = os.path.join(site_dir, egg, "PKG-INFO") modules_path = os.path.join(site_dir, egg, "top_level.txt") if not os.path.isfile(pkg_info_path): continue with open(pkg_info_path) as f: name = next(iter( line.split(":")[1].strip() for line in yield_lines(f.readlines()) if line.lower().startswith("name:") ), "") with open(modules_path) as f: modules = list(yield_lines(f.readlines())) for name in project2modules(name): mapping[name] = modules return mapping @staticmethod def discover_project_root_dir(path): """Discover project's root directory starting from given path.""" root_files = ["pyproject.toml", "requirements.txt", "setup.py"] while path != os.path.abspath(os.sep): paths = [os.path.join(path, x) for x in root_files] if any(map(os.path.exists, paths)): LOG.info("Discovered root directory: %s", path) return path path = os.path.abspath(os.path.join(path, "..")) return "" @staticmethod def is_project_setup_py(project_root_dir, filename): """Determine whether given file is project's setup.py file.""" project_setup_py = os.path.join(project_root_dir, "setup.py") try: return os.path.samefile(filename, project_setup_py) except OSError: return False _requirement_match_option = re.compile( r"(-[\w-]+)(.*)").match _requirement_match_extras = re.compile( r"(.*?)\s*(\[[^]]+\])").match _requirement_match_spec = re.compile( r"(.*?)\s+--(global-option|install-option|hash)").match _requirement_match_archive = re.compile( r"(.*)(\.(tar(\.(bz2|gz|lz|lzma|xz))?|tbz|tgz|tlz|txz|whl|zip))", re.IGNORECASE).match _requirement_match_archive_spec = re.compile( r"(\w+)(-[^-]+)?").match _requirement_match_vcs = re.compile( r"(git|hg|svn|bzr)\+(.*)").match _requirement_match_vcs_spec = re.compile( r".*egg=([\w\-\.]+)").match @classmethod def resolve_requirement(cls, requirement, max_depth=0, path=None): """Resolves flags like -r in an individual requirement line.""" option = None option_match = cls._requirement_match_option(requirement) if option_match is not None: option = option_match.group(1) requirement = option_match.group(2).lstrip() editable = False if option in ("-e", "--editable"): editable = True # We do not care about installation mode. option = None if option in ("-r", "--requirement"): # Error out if we need to recurse deeper than allowed. if max_depth <= 0: msg = ( "Cannot resolve {}: " "Beyond max depth (--requirements-max-depth={})") raise RuntimeError(msg.format( requirement, cls.requirements_max_depth)) resolved = [] # Error out if requirements file cannot be opened. with open(os.path.join(path or cls.root_dir, requirement)) as f: for line in joinlines(f.readlines()): resolved.extend(cls.resolve_requirement( line, max_depth - 1, os.path.dirname(f.name))) return resolved if option: # Skip whole line if option was not processed earlier. return [] # Check for a requirement given as a VCS link. vcs_match = cls._requirement_match_vcs(requirement) vcs_spec_match = cls._requirement_match_vcs_spec( vcs_match.group(2) if vcs_match is not None else "") if vcs_spec_match is not None: return [vcs_spec_match.group(1)] # Check for a requirement given as a local archive file. archive_ext_match = cls._requirement_match_archive(requirement) if archive_ext_match is not None: base = os.path.basename(archive_ext_match.group(1)) archive_spec_match = cls._requirement_match_archive_spec(base) if archive_spec_match is not None: name, version = archive_spec_match.groups() return [ name if not version else "{} == {}".format(name, version[1:]) ] # Editable installation is made either from local path or from VCS # URL. In case of VCS, the URL should be already handled in the if # block above. Here we shall get a local project path. if editable: requirement = os.path.basename(requirement) if requirement.split()[0] == ".": requirement = "" # It seems that the parse_requirements() function does not like # ".[foo,bar]" syntax (current directory with extras). extras_match = cls._requirement_match_extras(requirement) if extras_match is not None and extras_match.group(1) == ".": requirement = "" # Extract requirement specifier (skip in-line options). spec_match = cls._requirement_match_spec(requirement) if spec_match is not None: requirement = spec_match.group(1) return [requirement.strip()] @classmethod @memoize def get_pyproject_toml(cls): """Try to load PEP 518 configuration file.""" pyproject_config_path = os.path.join(cls.root_dir, "pyproject.toml") try: with open(pyproject_config_path, mode="rb") as f: return tomllib.load(f) except (IOError, tomllib.TOMLDecodeError) as e: LOG.debug("Couldn't load pyproject: %s", e) return {} @classmethod def get_pyproject_toml_pep621(cls): """Try to get PEP 621 metadata.""" cfg_pep518 = cls.get_pyproject_toml() return cfg_pep518.get('project', {}) @classmethod def get_setuptools_dynamic_requirements(cls): """Retrieve dynamic requirements defined in setuptools config.""" cfg = cls.get_pyproject_toml() dynamic_keys = cfg.get('project', {}).get('dynamic', []) dynamic_config = ( cfg.get('tool', {}).get('setuptools', {}).get('dynamic', {}) ) requirements = [] files_to_parse = [] if 'dependencies' in dynamic_keys: files_to_parse.extend( dynamic_config.get('dependencies', {}).get('file', []) ) if 'optional-dependencies' in dynamic_keys: for element in dynamic_config.get( 'optional-dependencies', {} ).values(): files_to_parse.extend(element.get('file', [])) for file_path in files_to_parse: try: with open(file_path, 'r') as file: requirements.extend(parse_requirements(file)) except IOError as e: LOG.debug("Couldn't open requirements file: %s", e) return requirements @classmethod def get_pyproject_toml_pep621_requirements(cls): """Try to get PEP 621 metadata requirements.""" pep621 = cls.get_pyproject_toml_pep621() requirements = [] requirements.extend(parse_requirements( pep621.get("dependencies", ()))) for r in pep621.get("optional-dependencies", {}).values(): requirements.extend(parse_requirements(r)) if len(requirements) == 0: requirements = cls.get_setuptools_dynamic_requirements() return requirements @classmethod def get_pyproject_toml_poetry(cls): """Try to get poetry configuration.""" cfg_pep518 = cls.get_pyproject_toml() return cfg_pep518.get('tool', {}).get('poetry', {}) @classmethod def get_pyproject_toml_poetry_requirements(cls): """Try to get poetry configuration requirements.""" poetry = cls.get_pyproject_toml_poetry() requirements = [] requirements.extend(parse_requirements( poetry.get('dependencies', ()))) requirements.extend(parse_requirements( poetry.get('dev-dependencies', ()))) # Collect dependencies from groups (since poetry-1.2). for _, group in poetry.get('group', {}).items(): requirements.extend(parse_requirements( group.get('dependencies', ()))) return requirements @classmethod def get_requirements_txt(cls): """Try to load requirements from text file.""" path = cls.requirements_file or "requirements.txt" if not os.path.isabs(path): path = os.path.join(cls.root_dir, path) try: return tuple(parse_requirements(cls.resolve_requirement( "-r {}".format(path), cls.requirements_max_depth + 1))) except IOError as e: LOG.error("Couldn't load requirements: %s", e) return () @classmethod @memoize def get_setup_cfg(cls): """Try to load standard configuration file.""" config = ConfigParser() config.read_dict({ 'metadata': {'name': ""}, 'options': { 'install_requires': "", 'setup_requires': "", 'tests_require': ""}, 'options.extras_require': {}, }) if not config.read(os.path.join(cls.root_dir, "setup.cfg")): LOG.debug("Couldn't load setup configuration: setup.cfg") return config @classmethod def get_setup_cfg_requirements(cls, is_setup_py): """Try to load standard configuration file requirements.""" config = cls.get_setup_cfg() requirements = [] requirements.extend(parse_requirements( config.get('options', 'install_requires'))) requirements.extend(parse_requirements( config.get('options', 'tests_require'))) for _, r in config.items('options.extras_require'): requirements.extend(parse_requirements(r)) setup_requires = config.get('options', 'setup_requires') if setup_requires and is_setup_py: requirements.extend(parse_requirements(setup_requires)) return requirements @classmethod @memoize def get_setup_py(cls): """Try to load standard setup file.""" try: with open(os.path.join(cls.root_dir, "setup.py")) as f: return SetupVisitor(ast.parse(f.read()), cls.root_dir) except IOError as e: LOG.debug("Couldn't load setup: %s", e) return SetupVisitor(ast.parse(""), cls.root_dir) @classmethod def get_setup_py_requirements(cls, is_setup_py): """Try to load standard setup file requirements.""" setup = cls.get_setup_py() if not setup.redirected: return [] return setup.get_requirements( setup=is_setup_py, tests=True, ) @classmethod @memoize def get_mods_1st_party(cls): mods_1st_party = ModuleSet() # Get 1st party modules (used for absolute imports). modules = project2modules( cls.get_setup_py().keywords.get('name') or cls.get_setup_cfg().get('metadata', 'name') or cls.get_pyproject_toml_pep621().get('name') or cls.get_pyproject_toml_poetry().get('name') or "") # Use known module mappings to correct auto-detected name. Please note # that we're using the first module name only, since all mappings shall # contain all possible auto-detected module names. if modules[0] in cls.known_modules: modules = cls.known_modules[modules[0]] for module in modules: mods_1st_party.add(modsplit(module), True) return mods_1st_party @classmethod @memoize def get_mods_3rd_party(cls, is_setup_py): mods_3rd_party = ModuleSet() # Get 3rd party module names based on requirements. for requirement in cls.get_mods_3rd_party_requirements(is_setup_py): modules = project2modules(requirement.project_name) # Use known module mappings to correct auto-detected module name. if modules[0] in cls.known_modules: modules = cls.known_modules[modules[0]] elif modules[0] in cls.known_3rd_parties: modules = cls.known_3rd_parties[modules[0]] elif modules[0] in cls.known_host_3rd_parties: modules = cls.known_host_3rd_parties[modules[0]] for module in modules: mods_3rd_party.add(modsplit(module), requirement) return mods_3rd_party @classmethod def get_mods_3rd_party_requirements(cls, is_setup_py): """Get list of 3rd party requirements.""" # Use user provided requirements text file. if cls.requirements_file: return cls.get_requirements_txt() return ( # Use requirements from setup if available. cls.get_setup_py_requirements(is_setup_py) or # Check setup configuration file for requirements. cls.get_setup_cfg_requirements(is_setup_py) or # Check PEP 621 metadata for requirements. cls.get_pyproject_toml_pep621_requirements() or # Check project configuration for requirements. cls.get_pyproject_toml_poetry_requirements() or # Fall-back to requirements.txt in our root directory. cls.get_requirements_txt() ) def check_I900(self, node): """Run missing requirement checker.""" if node.module[0] in STDLIB: return None is_setup_py = self.is_project_setup_py(self.root_dir, self.filename) if node.module in self.get_mods_3rd_party(is_setup_py): return None if node.module in self.get_mods_1st_party(): return None # When processing setup.py file, forcefully add setuptools to the # project requirements. Setuptools might be required to build the # project, even though it is not listed as a requirement - this # package is required to run setup.py, so listing it as a setup # requirement would be pointless. if (is_setup_py and node.module[0] in KNOWN_3RD_PARTIES["setuptools"]): return None return ERRORS['I900'].format(pkg=node.module[0]) def check_I901(self, node): """Run not-used requirement checker.""" if node.module[0] in STDLIB: return None # TODO: Implement this check. return None def run(self): """Run checker.""" checkers = [] checkers.append(self.check_I900) if self.error_I901_enabled: checkers.append(self.check_I901) for node in ImportVisitor(self.tree).imports: for err in filter(None, map(lambda c: c(node), checkers)): yield node.line, node.offset, err, type(self)
class Flake8Checker(object): '''Package requirements checker.''' def __init__(self, tree, filename, lines=None): '''Initialize requirements checker.''' pass @classmethod def add_options(cls, manager): '''Register plug-in specific options.''' pass @classmethod def parse_options(cls, options): '''Parse plug-in specific options.''' pass @staticmethod def discover_host_3rd_party_modules(): '''Scan host site-packages for 3rd party modules.''' pass @staticmethod def discover_project_root_dir(path): '''Discover project's root directory starting from given path.''' pass @staticmethod def is_project_setup_py(project_root_dir, filename): '''Determine whether given file is project's setup.py file.''' pass @classmethod def resolve_requirement(cls, requirement, max_depth=0, path=None): '''Resolves flags like -r in an individual requirement line.''' pass @classmethod @memoize def get_pyproject_toml(cls): '''Try to load PEP 518 configuration file.''' pass @classmethod def get_pyproject_toml_pep621(cls): '''Try to get PEP 621 metadata.''' pass @classmethod def get_setuptools_dynamic_requirements(cls): '''Retrieve dynamic requirements defined in setuptools config.''' pass @classmethod def get_pyproject_toml_pep621_requirements(cls): '''Try to get PEP 621 metadata requirements.''' pass @classmethod def get_pyproject_toml_poetry(cls): '''Try to get poetry configuration.''' pass @classmethod def get_pyproject_toml_poetry_requirements(cls): '''Try to get poetry configuration requirements.''' pass @classmethod def get_requirements_txt(cls): '''Try to load requirements from text file.''' pass @classmethod @memoize def get_setup_cfg(cls): '''Try to load standard configuration file.''' pass @classmethod def get_setup_cfg_requirements(cls, is_setup_py): '''Try to load standard configuration file requirements.''' pass @classmethod @memoize def get_setup_py(cls): '''Try to load standard setup file.''' pass @classmethod def get_setup_py_requirements(cls, is_setup_py): '''Try to load standard setup file requirements.''' pass @classmethod @memoize def get_mods_1st_party(cls): pass @classmethod @memoize def get_mods_3rd_party(cls, is_setup_py): pass @classmethod def get_mods_3rd_party_requirements(cls, is_setup_py): '''Get list of 3rd party requirements.''' pass def check_I900(self, node): '''Run missing requirement checker.''' pass def check_I901(self, node): '''Run not-used requirement checker.''' pass def run(self): '''Run checker.''' pass
50
23
16
0
14
2
3
0.16
1
15
3
1
4
3
24
24
494
48
384
134
334
62
251
104
226
16
1
3
82
7,380
Arkq/flake8-requirements
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Arkq_flake8-requirements/test/test_checker.py
test_checker.Flake8CheckerTestCase.test_custom_mapping.Options
class Options(Flake8Options): known_modules = "flake8-requires:[flake8req]"
class Options(Flake8Options): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
7,381
Arkq/flake8-requirements
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Arkq_flake8-requirements/test/test_checker.py
test_checker.Flake8CheckerTestCase.test_custom_mapping_parser.Options
class Options(Flake8Options): known_modules = ":[pydrmcodec],mylib:[mylib.drm,mylib.ex]"
class Options(Flake8Options): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
7,382
Arkq/flake8-requirements
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Arkq_flake8-requirements/test/test_checker.py
test_checker.Flake8CheckerTestCase.test_discover_host_3rd_party_modules.Options
class Options(Flake8Options): scan_host_site_packages = True
class Options(Flake8Options): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
7,383
Arkq/flake8-requirements
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Arkq_flake8-requirements/test/test_pep621.py
test_pep621.Pep621TestCase.test_pyproject_custom_mapping_parser.Options
class Options(Flake8Options): known_modules = {"mylib": ["mylib.drm", "mylib.ex"]}
class Options(Flake8Options): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
2
1
0
2
2
1
0
1
0
0
7,384
Arkq/flake8-requirements
src/flake8_requirements/checker.py
flake8_requirements.checker.SetupVisitor
class SetupVisitor(ast.NodeVisitor): """Package setup visitor. Warning: This visitor class executes given Abstract Syntax Tree! """ # Set of keywords used by the setup() function. attributes = { # Attributes present in almost every setup(), however # due to very generic name the score is not very high. 'name': 0.7, 'version': 0.7, # One of these attributes is present in every setup(), # scoring depends on the name uniqueness. 'ext_modules': 1.0, 'packages': 0.8, 'py_modules': 1.0, # Mostly used (hence listed here) optional attributes. 'author': 0.5, 'author_email': 0.6, 'classifiers': 0.6, 'cmdclass': 0.6, 'convert_2to3_doctests': 1.0, 'dependency_links': 0.7, 'description': 0.5, 'download_url': 0.5, 'eager_resources': 0.7, 'entry_points': 0.7, 'exclude_package_data': 0.9, 'extras_require': 0.7, 'include_package_data': 0.9, 'install_requires': 0.7, 'keywords': 0.5, 'license': 0.5, 'long_description': 0.5, 'maintainer': 0.5, 'maintainer_email': 0.6, 'namespace_packages': 0.6, 'package_data': 0.6, 'package_dir': 0.6, 'platforms': 0.5, 'python_requires': 0.7, 'scripts': 0.5, 'setup_requires': 0.7, 'test_loader': 0.6, 'test_suite': 0.6, 'tests_require': 0.7, 'url': 0.5, 'use_2to3': 0.9, 'use_2to3_fixers': 1.0, 'zip_safe': 0.6, } def __init__(self, tree, cwd): """Initialize package setup visitor.""" self.redirected = False self.keywords = {} # Find setup() call and redirect it. self.visit(tree) if not self.redirected: return def setup(**kw): """Setup() arguments hijacking.""" self.keywords = kw # XXX: If evaluated script (setup.py) depends on local modules we # have to add its root directory to the import search path. # Note however, that this hack might break further imports # for OUR Python instance (we're changing our own sys.path)! sys.path.insert(0, cwd) try: tree = ast.fix_missing_locations(tree) eval(compile(tree, "<str>", mode='exec'), { '__name__': "__main__", '__file__': os.path.join(cwd, "setup.py"), '__f8r_setup': setup, }) except BaseException as e: # XXX: Exception during setup.py evaluation might not necessary # mean "fatal error". This exception might occur if e.g. # we have hijacked local setup() function (due to matching # heuristic for function arguments). Anyway, we shall not # break flake8 execution due to our eval() usage. LOG.error("Couldn't evaluate setup.py: %r", e) self.redirected = False # Restore import search path. sys.path.pop(0) def get_requirements( self, install=True, extras=True, setup=False, tests=False): """Get package requirements.""" requires = [] if install: requires.extend(parse_requirements( self.keywords.get('install_requires', ()), )) if extras: for r in self.keywords.get('extras_require', {}).values(): requires.extend(parse_requirements(r)) if setup: requires.extend(parse_requirements( self.keywords.get('setup_requires', ()), )) if tests: requires.extend(parse_requirements( self.keywords.get('tests_require', ()), )) return requires def visit_Call(self, node): """Call visitor - used for finding setup() call.""" self.generic_visit(node) # Setup() is a keywords-only function. if node.args: return keywords = set() for k in node.keywords: if k.arg is not None: keywords.add(k.arg) # Simple case for dictionary expansion for Python >= 3.5. if k.arg is None and isinstance(k.value, ast.Dict): keywords.update(x.s for x in k.value.keys) # Simple case for dictionary expansion for Python <= 3.4. if getattr(node, 'kwargs', ()) and isinstance(node.kwargs, ast.Dict): keywords.update(x.s for x in node.kwargs.keys) # The bare minimum number of arguments seems to be around five, which # includes author, name, version, module/package and something extra. if len(keywords) < 5: return score = sum( self.attributes.get(x, 0) for x in keywords ) / len(keywords) if score < 0.5: LOG.debug( "Scoring for setup%r below 0.5: %.2f", tuple(keywords), score) return # Redirect call to our setup() tap function. node.func = ast.Name(id='__f8r_setup', ctx=node.func.ctx) self.redirected = True
class SetupVisitor(ast.NodeVisitor): '''Package setup visitor. Warning: This visitor class executes given Abstract Syntax Tree! ''' def __init__(self, tree, cwd): '''Initialize package setup visitor.''' pass def setup(**kw): '''Setup() arguments hijacking.''' pass def get_requirements( self, install=True, extras=True, setup=False, tests=False): '''Get package requirements.''' pass def visit_Call(self, node): '''Call visitor - used for finding setup() call.''' pass
5
5
25
3
17
6
5
0.29
1
3
0
1
3
2
3
6
155
18
106
15
100
31
50
13
45
8
2
2
18
7,385
ArtoLabs/SimpleSteem
ArtoLabs_SimpleSteem/simplesteem/simplesteem.py
simplesteem.simplesteem.SimpleSteem
class SimpleSteem: def __init__(self, **kwargs): ''' Looks for config.py if not found runs setup which prompts user for the config values one time only. ''' for key, value in kwargs.items(): setattr(self, key, value) try: imp.find_module('config', [os.path.dirname(os.path.realpath(__file__))]) except ImportError: makeconfig.MakeConfig().setup() from simplesteem import config try: self.mainaccount except: self.mainaccount = config.mainaccount try: self.keys except: self.keys = config.keys try: self.nodes except: self.nodes = config.nodes try: self.client_id except: self.client_id = config.client_id try: self.client_secret except: self.client_secret = config.client_secret try: self.callback_url except: self.callback_url = config.callback_url try: self.permissions except: self.permissions = config.permissions try: self.logpath except: self.logpath = config.logpath try: self.screenmode except: self.screenmode = config.screenmode self.s = None self.c = None self.e = None self.dex = None self.msg = Msg("simplesteem.log", self.logpath, self.screenmode) self.util = util.Util("simplesteem.log", self.logpath, self.screenmode) self.connect = steemconnectutil.SteemConnect( self.client_id, self.client_secret, self.callback_url, self.permissions) self.checkedaccount = None self.accountinfo = None self.blognumber = 0 self.reward_balance = 0 self.price_of_steem = 0 def account(self, account=None): ''' Fetches account information and stores the result in a class variable. Returns that variable if the account has not changed. ''' for num_of_retries in range(default.max_retry): if account is None: account = self.mainaccount if account == self.checkedaccount: return self.accountinfo self.checkedaccount = account try: self.accountinfo = self.steem_instance().get_account(account) except Exception as e: self.util.retry(("COULD NOT GET ACCOUNT INFO FOR " + str(account)), e, num_of_retries, default.wait_time) self.s = None self.e = e else: if self.accountinfo is None: self.msg.error_message("COULD NOT FIND ACCOUNT: " + str(account)) return False else: return self.accountinfo def steem_instance(self): ''' Returns the steem instance if it already exists otherwise uses the goodnode method to fetch a node and instantiate the Steem class. ''' if self.s: return self.s for num_of_retries in range(default.max_retry): node = self.util.goodnode(self.nodes) try: self.s = Steem(keys=self.keys, nodes=[node]) except Exception as e: self.util.retry("COULD NOT GET STEEM INSTANCE", e, num_of_retries, default.wait_time) self.s = None self.e = e else: return self.s return False def claim_rewards(self): if self.steem_instance().claim_reward_balance( account=self.mainaccount): time.sleep(5) return True else: return False def verify_key (self, acctname=None, tokenkey=None): ''' This can be used to verify either a private posting key or to verify a steemconnect refresh token and retreive the access token. ''' if (re.match( r'^[A-Za-z0-9]+$', tokenkey) and tokenkey is not None and len(tokenkey) <= 64 and len(tokenkey) >= 16): pubkey = PrivateKey(tokenkey).pubkey or 0 pubkey2 = self.account(acctname) if (str(pubkey) == str(pubkey2['posting']['key_auths'][0][0])): self.privatekey = tokenkey self.refreshtoken = None self.accesstoken = None return True else: return False elif (re.match( r'^[A-Za-z0-9\-\_\.]+$', tokenkey) and tokenkey is not None and len(tokenkey) > 64): self.privatekey = None self.accesstoken = self.connect.get_token(tokenkey) if self.accesstoken: self.username = self.connect.username self.refreshtoken = self.connect.refresh_token return True else: return False else: return False def reward_pool_balances(self): ''' Fetches and returns the 3 values needed to calculate the reward pool and other associated values such as rshares. Returns the reward balance, all recent claims and the current price of steem. ''' if self.reward_balance > 0: return self.reward_balance else: reward_fund = self.steem_instance().get_reward_fund() self.reward_balance = Amount( reward_fund["reward_balance"]).amount self.recent_claims = float(reward_fund["recent_claims"]) self.base = Amount( self.steem_instance( ).get_current_median_history_price()["base"] ).amount self.quote = Amount( self.steem_instance( ).get_current_median_history_price()["quote"] ).amount self.price_of_steem = self.base / self.quote return [self.reward_balance, self.recent_claims, self.price_of_steem] def rshares_to_steem (self, rshares): ''' Gets the reward pool balances then calculates rshares to steem ''' self.reward_pool_balances() return round( rshares * self.reward_balance / self.recent_claims * self.price_of_steem, 4) def global_props(self): ''' Retrieves the global properties used to determine rates used for calculations in converting steempower to vests etc. Stores these in the Utilities class as that is where the conversions take place, however SimpleSteem is the class that contains steem_instance, so to to preserve heirarchy and to avoid "spaghetti code", this method exists in this class. ''' if self.util.info is None: self.util.info = self.steem_instance().get_dynamic_global_properties() self.util.total_vesting_fund_steem = Amount(self.util.info["total_vesting_fund_steem"]).amount self.util.total_vesting_shares = Amount(self.util.info["total_vesting_shares"]).amount self.util.vote_power_reserve_rate = self.util.info["vote_power_reserve_rate"] return self.util.info def current_vote_value(self, **kwargs): ''' Ensures the needed variables are created and set to defaults although a variable number of variables are given. ''' try: kwargs.items() except: pass else: for key, value in kwargs.items(): setattr(self, key, value) try: self.lastvotetime except: self.lastvotetime=None try: self.steempower except: self.steempower=0 try: self.voteweight except: self.voteweight=100 try: self.votepoweroverride except: self.votepoweroverride=0 try: self.accountname except: self.accountname=None if self.accountname is None: self.accountname = self.mainaccount if self.check_balances(self.accountname) is not False: if self.voteweight > 0 and self.voteweight < 101: self.voteweight = self.util.scale_vote(self.voteweight) if self.votepoweroverride > 0 and self.votepoweroverride < 101: self.votepoweroverride = self.util.scale_vote(self.votepoweroverride) else: self.votepoweroverride = (self.votepower + self.util.calc_regenerated( self.lastvotetime)) self.vpow = round(self.votepoweroverride / 100, 2) self.global_props() self.rshares = self.util.sp_to_rshares(self.steempower, self.votepoweroverride, self.voteweight) self.votevalue = self.rshares_to_steem(self.rshares) return self.votevalue return None def check_balances(self, account=None): ''' Fetches an account balance and makes necessary conversions ''' a = self.account(account) if a is not False and a is not None: self.sbdbal = Amount(a['sbd_balance']).amount self.steembal = Amount(a['balance']).amount self.votepower = a['voting_power'] self.lastvotetime = a['last_vote_time'] vs = Amount(a['vesting_shares']).amount dvests = Amount(a['delegated_vesting_shares']).amount rvests = Amount(a['received_vesting_shares']).amount vests = (float(vs) - float(dvests)) + float(rvests) try: self.global_props() self.steempower_delegated = self.util.vests_to_sp(dvests) self.steempower_raw = self.util.vests_to_sp(vs) self.steempower = self.util.vests_to_sp(vests) except Exception as e: self.msg.error_message(e) self.e = e else: return [self.sbdbal, self.steembal, self.steempower, self.votepower, self.lastvotetime] return False def transfer_funds(self, to, amount, denom, msg): ''' Transfer SBD or STEEM to the given account ''' try: self.steem_instance().commit.transfer(to, float(amount), denom, msg, self.mainaccount) except Exception as e: self.msg.error_message(e) self.e = e return False else: return True def get_my_history(self, account=None, limit=10000): ''' Fetches the account history from most recent back ''' if not account: account = self.mainaccount try: h = self.steem_instance().get_account_history( account, -1, limit) except Exception as e: self.msg.error_message(e) self.e = e return False else: return h def post(self, title, body, permlink, tags): ''' Used for creating a main post to an account's blog. Waits 20 seconds after posting as that is the required amount of time between posting. ''' for num_of_retries in range(default.max_retry): try: self.msg.message("Attempting to post " + permlink) self.steem_instance().post(title, body, self.mainaccount, permlink, None, None, None, None, tags, None, False) except Exception as e: self.util.retry("COULD NOT POST '" + title + "'", e, num_of_retries, 10) self.s = None self.e = e else: self.msg.message("Post seems successful. Wating 60 seconds before verifying...") self.s = None time.sleep(60) checkident = self.recent_post() ident = self.util.identifier(self.mainaccount, permlink) if checkident == ident: return True else: self.util.retry('A POST JUST CREATED WAS NOT FOUND IN THE ' + 'BLOCKCHAIN {}'''.format(title), "Identifiers do not match", num_of_retries, default.wait_time) self.s = None def reply(self, permlink, msgbody): ''' Used for creating a reply to a post. Waits 20 seconds after posting as that is the required amount of time between posting. ''' for num_of_retries in range(default.max_retry): try: self.steem_instance().post("message", msgbody, self.mainaccount, None, permlink, None, None, "", None, None, False) except Exception as e: self.util.retry("COULD NOT REPLY TO " + permlink, e, num_of_retries, default.wait_time) self.s = None self.e = e else: self.msg.message("Replied to " + permlink) time.sleep(20) return True def follow(self, author): ''' Follows the given account ''' try: self.steem_instance().commit.follow(author, ['blog'], self.mainaccount) except Exception as e: self.msg.error_message(e) self.e = e return False else: return True def unfollow(self, author): ''' Unfollows the given account ''' try: self.steem_instance().commit.unfollow(author, ['blog'], self.mainaccount) except Exception as e: self.msg.error_message(e) self.e = e return False else: return True def following(self, account=None, limit=100): ''' Gets a list of all the followers of a given account. If no account is given the followers of the mainaccount are returned. ''' if not account: account = self.mainaccount followingnames = [] try: self.followed = self.steem_instance().get_following(account, '', 'blog', limit) except Exception as e: self.msg.error_message(e) self.e = e return False else: for a in self.followed: followingnames.append(a['following']) return followingnames def recent_post(self, author=None, daysback=0, flag=0): ''' Returns the most recent post from the account given. If the days back is greater than zero then the most recent post is returned for that day. For instance if daysback is set to 2 then it will be the most recent post from 2 days ago (48 hours). ''' if not author: author = self.mainaccount for num_of_retries in range(default.max_retry): try: self.blog = self.steem_instance().get_blog(author, 0, 30) except Exception as e: self.util.retry('COULD NOT GET THE ' + 'MOST RECENT POST FOR ' + '{}'.format(author), e, num_of_retries, default.wait_time) self.s = None self.e = e else: i = 0 for p in self.blog: if p != "error": if p['comment']['author'] == author: self.blognumber = i ageinminutes = self.util.minutes_back(p['comment']['created']) ageindays = (ageinminutes / 60) / 24 if (int(ageindays) == daysback): if flag == 1 and ageinminutes < 15: return None else: return self.util.identifier( p['comment']['author'], p['comment']['permlink']) else: return None i += 1 def vote_history(self, permlink, author=None): ''' Returns the raw vote history of a given post from a given account ''' if author is None: author = self.mainaccount return self.steem_instance().get_active_votes(author, permlink) def vote(self, identifier, weight=100.0): ''' Waits 5 seconds as that is the required amount of time between votes. ''' for num_of_retries in range(default.max_retry): try: self.steem_instance().vote(identifier, weight, self.mainaccount) self.msg.message("voted for " + identifier) time.sleep(5) except Exception as e: if re.search(r'You have already voted in a similar way', str(e)): self.msg.error_message('''Already voted on {}'''.format(identifier)) return "already voted" else: self.util.retry('''COULD NOT VOTE ON {}'''.format(identifier), e, num_of_retries, default.wait_time) self.s = None self.e = e else: return True def resteem(self, identifier): ''' Waits 20 seconds as that is the required amount of time between resteems ''' for num_of_retries in range(default.max_retry): try: self.steem_instance().resteem( identifier, self.mainaccount) self.msg.message("resteemed " + identifier) time.sleep(10) except Exception as e: self.util.retry('''COULD NOT RESTEEM {}'''.format(identifier), e, num_of_retries, default.wait_time) self.s = None self.e = e else: return True def dex_ticker(self): ''' Simply grabs the ticker using the steem_instance method and adds it to a class variable. ''' self.dex = Dex(self.steem_instance()) self.ticker = self.dex.get_ticker(); return self.ticker def steem_to_sbd(self, steemamt=0, price=0, account=None): ''' Uses the ticker to get the highest bid and moves the steem at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if steemamt == 0: steemamt = self.steembal elif steemamt > self.steembal: self.msg.error_message("INSUFFICIENT FUNDS. CURRENT STEEM BAL: " + str(self.steembal)) return False if price == 0: price = self.dex_ticker()['highest_bid'] try: self.dex.sell(steemamt, "STEEM", price, account=account) except Exception as e: self.msg.error_message("COULD NOT SELL STEEM FOR SBD: " + str(e)) self.e = e return False else: self.msg.message("TRANSFERED " + str(steemamt) + " STEEM TO SBD AT THE PRICE OF: $" + str(price)) return True else: return False def sbd_to_steem(self, sbd=0, price=0, account=None): ''' Uses the ticker to get the lowest ask and moves the sbd at that price. ''' if not account: account = self.mainaccount if self.check_balances(account): if sbd == 0: sbd = self.sbdbal elif sbd > self.sbdbal: self.msg.error_message("INSUFFICIENT FUNDS. CURRENT SBD BAL: " + str(self.sbdbal)) return False if price == 0: price = 1 / self.dex_ticker()['lowest_ask'] try: self.dex.sell(sbd, "SBD", price, account=account) except Exception as e: self.msg.error_message("COULD NOT SELL SBD FOR STEEM: " + str(e)) self.e = e return False else: self.msg.message("TRANSFERED " + str(sbd) + " SBD TO STEEM AT THE PRICE OF: $" + str(price)) return True else: return False def vote_witness(self, witness, account=None): ''' Uses the steem_instance method to vote on a witness. ''' if not account: account = self.mainaccount try: self.steem_instance().approve_witness(witness, account=account) except Exception as e: self.msg.error_message("COULD NOT VOTE " + witness + " AS WITNESS: " + e) self.e = e return False else: return True def unvote_witness(self, witness, account=None): ''' Uses the steem_instance method to unvote a witness. ''' if not account: account = self.mainaccount try: self.steem_instance().disapprove_witness(witness, account=account) except Exception as e: self.msg.error_message("COULD NOT UNVOTE " + witness + " AS WITNESS: " + e) self.e = e return False else: return True def voted_me_witness(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have voted that account as witness. ''' if not account: account = self.mainaccount self.has_voted = [] self.has_not_voted = [] following = self.following(account, limit) for f in following: wv = self.account(f)['witness_votes'] voted = False for w in wv: if w == account: self.has_voted.append(f) voted = True if not voted: self.has_not_voted.append(f) return self.has_voted def muted_me(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have muted that account. ''' self.has_muted = [] if account is None: account = self.mainaccount following = self.following(account, limit) if following is False: self.msg.error_message("COULD NOT GET FOLLOWING FOR MUTED") return False for f in following: h = self.get_my_history(f) for a in h: if a[1]['op'][0] == "custom_json": j = a[1]['op'][1]['json'] d = json.loads(j) try: d[1] except: pass else: for i in d[1]: if i == "what": if len(d[1]['what']) > 0: if d[1]['what'][0] == "ignore": if d[1]['follower'] == account: self.msg.message("MUTED BY " + f) self.has_muted.append(f) return self.has_muted def delegate(self, to, steempower): ''' Delegates based on Steem Power rather than by vests. ''' self.global_props() vests = self.util.sp_to_vests(steempower) strvests = str(vests) strvests = strvests + " VESTS" try: self.steem_instance().commit.delegate_vesting_shares(to, strvests, account=self.mainaccount) except Exception as e: self.msg.error_message("COULD NOT DELEGATE " + str(steempower) + " SP TO " + to + ": " + str(e)) self.e = e return False else: self.msg.message("DELEGATED " + str(steempower) + " STEEM POWER TO " + str(to)) return True def create_account(new_account, new_account_master_key, creator): self.steem_instance().create_account( new_account, delegation_fee_steem="3 STEEM", password=new_account_master_key, creator=creator, ) keys = {} for key_type in ['posting','active','owner','memo']: private_key = PasswordKey( new_account, new_account_master_key, key_type).get_private_key() keys[key_type] = { "public": str(private_key.pubkey), "private": str(private_key), } return keys
class SimpleSteem: def __init__(self, **kwargs): ''' Looks for config.py if not found runs setup which prompts user for the config values one time only. ''' pass def account(self, account=None): ''' Fetches account information and stores the result in a class variable. Returns that variable if the account has not changed. ''' pass def steem_instance(self): ''' Returns the steem instance if it already exists otherwise uses the goodnode method to fetch a node and instantiate the Steem class. ''' pass def claim_rewards(self): pass def verify_key (self, acctname=None, tokenkey=None): ''' This can be used to verify either a private posting key or to verify a steemconnect refresh token and retreive the access token. ''' pass def reward_pool_balances(self): ''' Fetches and returns the 3 values needed to calculate the reward pool and other associated values such as rshares. Returns the reward balance, all recent claims and the current price of steem. ''' pass def rshares_to_steem (self, rshares): ''' Gets the reward pool balances then calculates rshares to steem ''' pass def global_props(self): ''' Retrieves the global properties used to determine rates used for calculations in converting steempower to vests etc. Stores these in the Utilities class as that is where the conversions take place, however SimpleSteem is the class that contains steem_instance, so to to preserve heirarchy and to avoid "spaghetti code", this method exists in this class. ''' pass def current_vote_value(self, **kwargs): ''' Ensures the needed variables are created and set to defaults although a variable number of variables are given. ''' pass def check_balances(self, account=None): ''' Fetches an account balance and makes necessary conversions ''' pass def transfer_funds(self, to, amount, denom, msg): ''' Transfer SBD or STEEM to the given account ''' pass def get_my_history(self, account=None, limit=10000): ''' Fetches the account history from most recent back ''' pass def post(self, title, body, permlink, tags): ''' Used for creating a main post to an account's blog. Waits 20 seconds after posting as that is the required amount of time between posting. ''' pass def reply(self, permlink, msgbody): ''' Used for creating a reply to a post. Waits 20 seconds after posting as that is the required amount of time between posting. ''' pass def follow(self, author): ''' Follows the given account ''' pass def unfollow(self, author): ''' Unfollows the given account ''' pass def following(self, account=None, limit=100): ''' Gets a list of all the followers of a given account. If no account is given the followers of the mainaccount are returned. ''' pass def recent_post(self, author=None, daysback=0, flag=0): ''' Returns the most recent post from the account given. If the days back is greater than zero then the most recent post is returned for that day. For instance if daysback is set to 2 then it will be the most recent post from 2 days ago (48 hours). ''' pass def vote_history(self, permlink, author=None): ''' Returns the raw vote history of a given post from a given account ''' pass def vote_history(self, permlink, author=None): ''' Waits 5 seconds as that is the required amount of time between votes. ''' pass def resteem(self, identifier): ''' Waits 20 seconds as that is the required amount of time between resteems ''' pass def dex_ticker(self): ''' Simply grabs the ticker using the steem_instance method and adds it to a class variable. ''' pass def steem_to_sbd(self, steemamt=0, price=0, account=None): ''' Uses the ticker to get the highest bid and moves the steem at that price. ''' pass def sbd_to_steem(self, sbd=0, price=0, account=None): ''' Uses the ticker to get the lowest ask and moves the sbd at that price. ''' pass def vote_witness(self, witness, account=None): ''' Uses the steem_instance method to vote on a witness. ''' pass def unvote_witness(self, witness, account=None): ''' Uses the steem_instance method to unvote a witness. ''' pass def voted_me_witness(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have voted that account as witness. ''' pass def muted_me(self, account=None, limit=100): ''' Fetches all those a given account is following and sees if they have muted that account. ''' pass def delegate(self, to, steempower): ''' Delegates based on Steem Power rather than by vests. ''' pass def create_account(new_account, new_account_master_key, creator): pass
31
28
23
0
19
4
4
0.19
0
6
0
0
30
47
30
30
741
61
571
141
539
109
464
123
432
12
0
9
130
7,386
ArtoLabs/SimpleSteem
ArtoLabs_SimpleSteem/simplesteem/makeconfig.py
simplesteem.makeconfig.MakeConfig
class MakeConfig: def setup (self): ''' Runs only the first time SimpleSteem() is instantiated. Prompts user for the values that are then written to config.py ''' mainaccount = self.add_quotes(self.enter_config_value("mainaccount", 'ned')) keys = self.enter_config_value("keys", '[]') nodes = self.enter_config_value("nodes", '["https://steemd.minnowsupportproject.org",' + '"https://rpc.usesteem.com",' + '"https://rpc.steemviz.com",' + '"https://anyx.io",' + '"https://api.steemitdev.com",' + '"https://appbasetest.timcliff.com",' + '"https://steemd.privex.io",' + '"https://api.steem.house"]') client_id = self.add_quotes(self.enter_config_value("client_id")) client_secret = self.add_quotes(self.enter_config_value("client_secret")) callback_url = self.add_quotes(self.enter_config_value("callback_url")) permissions = self.add_quotes(self.enter_config_value("permissions", "login,offline,vote")) logpath = self.add_quotes(self.enter_config_value("logpath", "")) screenmode = self.add_quotes(self.enter_config_value("screenmode", "quiet")) self.make(mainaccount=mainaccount, keys=keys, nodes=nodes, client_id=client_id, client_secret=client_secret, callback_url=callback_url, permissions=permissions, logpath=logpath, screenmode=screenmode) def add_quotes(self, value): return '"'+str(value)+'"' def make(self, **kwargs): ''' takes the arguments and writes them as variable / value pairs to config.py ''' configpath = os.path.dirname(os.path.abspath(__file__)) + "/config.py" print ("Writing to " + configpath) with open(configpath, 'w+') as fh: try: fh.write("#!/usr/bin/python3\n\n") except Exception as e: print(e) else: for key, value in kwargs.items(): fh.write(key + ' = ' + value + "\n") def enter_config_value(self, key, default=""): ''' Prompts user for a value ''' if key == "keys" or key == "nodes": value = input('Please enter a value for ' + key + ' [\' \', \' \']: ') else: value = input('Please enter a value for ' + key + ': ') if value: return value else: return default
class MakeConfig: def setup (self): ''' Runs only the first time SimpleSteem() is instantiated. Prompts user for the values that are then written to config.py ''' pass def add_quotes(self, value): pass def make(self, **kwargs): ''' takes the arguments and writes them as variable / value pairs to config.py ''' pass def enter_config_value(self, key, default=""): ''' Prompts user for a value ''' pass
5
3
13
0
11
3
2
0.23
0
2
0
0
4
0
4
4
61
8
44
19
39
10
32
17
27
3
0
3
8
7,387
ArtoLabs/SimpleSteem
ArtoLabs_SimpleSteem/simplesteem/util.py
simplesteem.util.Util
class Util: def __init__(self, filename, path, screenmode): self.msg = Msg(filename, path, screenmode) self.total_vesting_fund_steem = None self.total_vesting_shares = None self.vote_power_reserve_rate = None self.info = None self.currentnode = 0 def current_node(self, listlength): newnodenumber = 0 path = os.path.dirname(os.path.abspath(__file__)) + "/node.dat" try: with open(path, 'r') as fh: try: self.currentnode = fh.read() except Exception as e: self.msg.error_message(e) finally: fh.close() except Exception as e: self.msg.error_message(e) if int(self.currentnode) >= int(listlength): self.currentnode = 0 else: newnodenumber = int(self.currentnode) + 1 with open(path, 'w+') as fh: try: fh.write(str(newnodenumber)) except Exception as e: self.msg.error_message(e) finally: fh.close() return int(self.currentnode) def goodnode(self, nodelist): ''' Goes through the provided list and returns the first server node that does not return an error. ''' l = len(nodelist) for n in range(self.current_node(l), l): self.msg.message("Trying node " + str(n) + ": " + nodelist[n]) try: req = urllib.request.Request(url=nodelist[n]) urllib.request.urlopen(req) except HTTPError as e: self.msg.error_message(e) self.currentnode = int(self.currentnode) + 1 else: self.msg.message("Using " + nodelist[n]) return nodelist[n] def identifier(self, author, permlink): ''' Converts an author's name and permlink into an identifier ''' strlink = ("@" + author + "/" + permlink) return strlink def permlink(self, identifier): ''' Deconstructs an identifier into an account name and permlink ''' temp = identifier.split("@") temp2 = temp[1].split("/") return [temp2[0], temp2[1]] def minutes_back(self, date): ''' Gives a number (integer) of days since a given date ''' elapsed = (datetime.utcnow() - datetime.strptime(date,'%Y-%m-%dT%H:%M:%S')) if elapsed.days > 0: secondsback = (elapsed.days * 24 * 60 * 60) + elapsed.seconds else: secondsback = elapsed.seconds minutesback = secondsback / 60 return int(minutesback) def scale_vote(self, value): ''' Scales a vote value between 1 and 100 to 150 to 10000 as required by Steem-Python for certain method calls ''' value = int(value) * 100 if value < 100: value = 100 if value > 10000: value = 10000 return value def calc_regenerated(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S') td = delta.days ts = delta.seconds tt = (td * 86400) + ts return tt * 10000 / 86400 / 5 def retry(self, msg, e, retry_num, waittime): ''' Creates the retry message and waits the given default time when a method call fails or a server does not respond appropriately. ''' self.msg.error_message(msg) self.msg.error_message(e) self.msg.error_message("Attempt number " + str(retry_num) + ". Retrying in " + str(waittime) + " seconds.") time.sleep(waittime) def steem_per_mvests(self): """ Obtain STEEM/MVESTS ratio """ return (self.total_vesting_fund_steem / (self.total_vesting_shares / 1e6)) def sp_to_vests(self, sp): """ Obtain VESTS (not MVESTS!) from SP :param number sp: SP to convert """ return sp * 1e6 / self.steem_per_mvests() def vests_to_sp(self, vests): """ Obtain SP from VESTS (not MVESTS!) :param number vests: Vests to convert to SP """ return vests / 1e6 * self.steem_per_mvests() def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000): """ Obtain the r-shares :param number sp: Steem Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting participation (100% = 10000) """ vesting_shares = int(self.sp_to_vests(sp) * 1e6) used_power = int((voting_power * vote_pct) / 10000); max_vote_denom = self.vote_power_reserve_rate * (5 * 60 * 60 * 24) / (60 * 60 * 24); used_power = int((used_power + max_vote_denom - 1) / max_vote_denom) rshares = ((vesting_shares * used_power) / 10000) return rshares
class Util: def __init__(self, filename, path, screenmode): pass def current_node(self, listlength): pass def goodnode(self, nodelist): ''' Goes through the provided list and returns the first server node that does not return an error. ''' pass def identifier(self, author, permlink): ''' Converts an author's name and permlink into an identifier ''' pass def permlink(self, identifier): ''' Deconstructs an identifier into an account name and permlink ''' pass def minutes_back(self, date): ''' Gives a number (integer) of days since a given date ''' pass def scale_vote(self, value): ''' Scales a vote value between 1 and 100 to 150 to 10000 as required by Steem-Python for certain method calls ''' pass def calc_regenerated(self, lastvotetime): ''' Uses math formula to calculate the amount of steem power that would have been regenerated given a certain datetime object ''' pass def retry(self, msg, e, retry_num, waittime): ''' Creates the retry message and waits the given default time when a method call fails or a server does not respond appropriately. ''' pass def steem_per_mvests(self): ''' Obtain STEEM/MVESTS ratio ''' pass def sp_to_vests(self, sp): ''' Obtain VESTS (not MVESTS!) from SP :param number sp: SP to convert ''' pass def vests_to_sp(self, vests): ''' Obtain SP from VESTS (not MVESTS!) :param number vests: Vests to convert to SP ''' pass def sp_to_rshares(self, sp, voting_power=10000, vote_pct=10000): ''' Obtain the r-shares :param number sp: Steem Power :param int voting_power: voting power (100% = 10000) :param int vote_pct: voting participation (100% = 10000) ''' pass
14
11
10
0
7
3
2
0.41
0
7
0
0
13
6
13
13
157
26
93
42
79
38
88
39
74
5
0
3
22
7,388
ArtoLabs/SimpleSteem
ArtoLabs_SimpleSteem/simplesteem/steemconnectutil.py
simplesteem.steemconnectutil.SteemConnect
class SteemConnect: def __init__(self, client_id="", client_secret="", callback_url="", permissions="login,offline,vote"): self.client_id = client_id self.client_secret = client_secret self.callback_url = callback_url self.permissions = permissions self.sc = None self.accesstoken = None self.msg = Msg("simplesteem.log", "~", "quiet") def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' if self.sc is not None: return self.sc if accesstoken is not None: self.accesstoken = accesstoken if self.accesstoken is None: self.sc = Client(client_id=self.client_id, client_secret=self.client_secret) else: self.sc = Client(access_token=self.accesstoken, client_id=self.client_id, client_secret=self.client_secret) return self.sc def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' tokenobj = self.steemconnect().get_access_token(code) for t in tokenobj: if t == 'error': self.msg.error_message(str(tokenobj[t])) return False elif t == 'access_token': self.username = tokenobj['username'] self.refresh_token = tokenobj['refresh_token'] return tokenobj[t] def auth_url(self): ''' Returns the SteemConnect url used for authentication ''' return self.steemconnect().get_login_url( self.callback_url, self.permissions, "get_refresh_token=True") def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' vote = Vote(voter, author, permlink, voteweight) result = self.steemconnect().broadcast( [vote.to_operation_structure()]) return result
class SteemConnect: def __init__(self, client_id="", client_secret="", callback_url="", permissions="login,offline,vote"): pass def steemconnect(self, accesstoken=None): ''' Initializes the SteemConnect Client class ''' pass def get_token(self, code=None): ''' Uses a SteemConnect refresh token to retreive an access token ''' pass def auth_url(self): ''' Returns the SteemConnect url used for authentication ''' pass def vote(self, voter, author, permlink, voteweight): ''' Uses a SteemConnect accses token to vote. ''' pass
6
4
11
0
9
2
2
0.27
0
1
0
0
5
9
5
5
67
10
45
22
36
12
33
19
27
4
0
2
11
7,389
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/VmTypes/__init__.py
ArubaCloud.objects.VmTypes.Smart
class Smart(VM): def __init__(self, interface, sid): super(Smart, self).__init__(interface) self.cltype = 'smart' self.sid = sid self.ip_addr = Ip() self.package = None def __str__(self): msg = super(Smart, self).__str__() msg += ' -> IPAddr: %s\n' % self.ip_addr return msg def upgrade_vm(self, package_id, debug=False): if not self.status == 2: raise OperationNotPermitted("Cannot edit resources in the current state of the VM. Turn off the VM first.") if package_id > 4 or package_id <= 0: return MalformedJsonRequest("Packages available are: 1, 2, 3, 4.") method_json = { "Server": { "ServerId": self.sid, "SmartVMWarePackageID": package_id } } json_obj = self.interface.call_method_post(method='SetEnqueueServerUpdate', json_scheme=self.interface.gen_def_json_scheme( req='SetEnqueueServerUpdate', method_fields=method_json ), debug=debug) if debug is True: print(json_obj) return True if json_obj['Success'] is True else False
class Smart(VM): def __init__(self, interface, sid): pass def __str__(self): pass def upgrade_vm(self, package_id, debug=False): pass
4
0
10
0
10
0
2
0
1
4
3
0
3
4
3
12
33
2
31
11
27
0
21
11
17
5
2
1
7
7,390
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/__init__.py
ArubaCloud.objects.Vlan
class Vlan(object): name = None resource_id = None vlan_code = None def __repr__(self): return 'Vlan(name={}, resource_id={}, vlan_code={})'.format(self.name, self.resource_id, self.vlan_code) def __str__(self): return 'Vlan(name={}, resource_id={}, vlan_code={})'.format(self.name, self.resource_id, self.vlan_code)
class Vlan(object): def __repr__(self): pass def __str__(self): pass
3
0
2
0
2
0
1
0
1
0
0
0
2
0
2
2
10
2
8
6
5
0
8
6
5
1
1
0
2
7,391
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/__init__.py
ArubaCloud.objects.VirtualDiskOperation
class VirtualDiskOperation(object): resize = 1 create = 2 delete = 3
class VirtualDiskOperation(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
4
0
4
4
3
0
4
4
3
0
1
0
0
7,392
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/__init__.py
ArubaCloud.objects.VirtualDisk
class VirtualDisk(object): primary_disk_type = 3 additional_disk1_type = 7 additional_disk2_type = 8 additional_disk3_type = 9 primary_disk_id = 0 additional_disk1_id = 1 additional_disk2_id = 2 additional_disk3_id = 3
class VirtualDisk(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
9
0
9
9
8
0
9
9
8
0
1
0
0
7,393
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/Templates.py
ArubaCloud.objects.Templates.Template
class Template(object): descr = None template_id = '' id_code = None hypervisor = None name = None enabled = None class ResourceBounds(object): def __init__(self): self.max_cpu = None self.max_memory = None self.hdd0 = None self.hdd1 = None self.hdd2 = None self.hdd3 = None def __init__(self, hypervisor): self.hypervisor = hypervisor self.resource_bounds = self.ResourceBounds() def __str__(self): msg = 'Template Name: %s\n' % self.descr msg += ' -> Hypervisor: %s\n' % self.hypervisor msg += ' -> IdCode: %s\n' % self.id_code msg += ' -> Id: %s\n' % self.template_id msg += ' -> Enabled: %s\n' % self.enabled return msg def __repr__(self): return 'Template Name: %s, Hypervisor: %s, Id: %s, Enabled: %s' % ( self.descr, self.hypervisor, self.template_id, self.enabled )
class Template(object): class ResourceBounds(object): def __init__(self): pass def __init__(self): pass def __str__(self): pass def __repr__(self): pass
6
0
5
0
5
0
1
0
1
1
1
0
3
1
3
3
33
4
29
20
23
0
27
20
21
1
1
0
4
7,394
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/__init__.py
ArubaCloud.objects.SmartVmCreator
class SmartVmCreator(Creator): def __init__(self, name, admin_password, template_id, auth_obj, note=None): self.name = name self.admin_password = admin_password self.template_id = template_id self.auth_obj = auth_obj self.note = 'Create by pyArubaCloud' if note is None else note self.json_msg = { 'ApplicationId': 'SetEnqueueServerCreation', 'RequestId': 'SetEnqueueServerCreation', 'Username': self.auth_obj.username, 'Password': self.auth_obj.password, 'Server': { 'AdministratorPassword': self.admin_password, 'Name': self.name, 'SmartVMWarePackageID': 1, 'Note': self.note, 'OSTemplateId': self.template_id } } def set_type(self, package_id): """ Define the size of the VM. Size available: - small - medium - large - extralarge :param size: str() :return: """ self.json_msg['Server']['SmartVMWarePackageID'] = package_id return True def set_ssh_key(self, public_key_path): with open(public_key_path, 'r') as content_file: content = content_file.read() self.json_msg['Server']['SshKey'] = content self.json_msg['Server']['SshPasswordAuthAllowed'] = True
class SmartVmCreator(Creator): def __init__(self, name, admin_password, template_id, auth_obj, note=None): pass def set_type(self, package_id): ''' Define the size of the VM. Size available: - small - medium - large - extralarge :param size: str() :return: ''' pass def set_ssh_key(self, public_key_path): pass
4
1
12
0
9
3
1
0.32
1
0
0
0
3
6
3
6
40
3
28
12
24
9
16
11
12
2
2
1
4
7,395
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/Scheduled.py
ArubaCloud.objects.Scheduled.ScheduledCreator
class ScheduledCreator(Creator): def __init__(self, name, serverid, operationtype, start, end, DC, auth_obj): self.name = name self.serverid = serverid self.operationtype = ['CreateSnapshot', 'DeleteSnapshot', 'RestoreSnapShot', 'ShutdownVirtualMachine', 'StartVirtualMachine', 'StopVirtualMachine', 'UpdateVirtualMachine'] for _optype_ in operationtype: if operationtype not in _optype_: raise Exception('error') self.start = start self.end = end self.auth = auth_obj self.wcf_baseurl = 'https://api.dc%s.computing.cloud.it/WsEndUser/v2.9/WsEndUser.svc/json' % (str(DC)) self.json_msg = { 'ApplicationId': 'SetAddServerScheduledOperation', 'RequestId': 'SetAddServerScheduledOperation', 'SessionId': '', 'Password': auth_obj.password, 'Username': self.auth.username, 'SetAddServerScheduledOperation': { 'ScheduledOperationTypes': self.operationtype, 'ScheduleOperationLabel': self.name, 'ServerID': self.serverid, 'ScheduleStartDateTime': self.start, 'ScheduleEndDateTime': self.end, 'ScheduleFrequencyType': 'RunOnce', 'ScheduledPlanStatus': 'Enabled', 'ScheduledMontlyRecurrence': 'FirstDay' } }
class ScheduledCreator(Creator): def __init__(self, name, serverid, operationtype, start, end, DC, auth_obj): pass
2
0
30
0
30
0
3
0
1
2
0
0
1
8
1
4
31
0
31
11
29
0
13
11
11
3
2
2
3
7,396
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/Scheduled.py
ArubaCloud.objects.Scheduled.Scheduled
class Scheduled(JsonInterfaceBase): def __init__(self, DC): super(Scheduled, self).__init__() self.wcf_baseurl = 'https://api.dc%s.computing.cloud.it/WsEndUser/v2.9/WsEndUser.svc/json' % (str(DC)) @property def name(self): return self.name def get_scheduled_operations(self, start, end): get_shed_ops_request = { "GetScheduledOperations": { "EndDate": end, "StartDate": start } } scheme = self.gen_def_json_scheme('GetScheduledOperations', method_fields=get_shed_ops_request) json_obj = self.call_method_post('GetScheduledOperations', json_scheme=scheme) return json_obj def suspend_scheduled_operation(self, operationid): suspend_request = { "SetUpdateServerScheduledOperation": { "ScheduledOperationId": operationid } } scheme = self.gen_def_json_scheme('SetUpdateServerScheduledOperation', method_fields=suspend_request) json_obj = self.call_method_post('SetUpdateServerScheduledOperation', json_scheme=scheme) return True if json_obj['Success'] is True else False def delete_scheduled_operation(self, operationid): delete_request = { "SetRemoveServerScheduledOperation": { "ScheduledOperationId": operationid } } scheme = self.gen_def_json_scheme('SetRemoveServerScheduledOperation', method_fields=delete_request) json_obj = self.call_method_post('SetRemoveServerScheduledOperation', json_scheme=scheme) return True if json_obj['Success'] is True else False
class Scheduled(JsonInterfaceBase): def __init__(self, DC): pass @property def name(self): pass def get_scheduled_operations(self, start, end): pass def suspend_scheduled_operation(self, operationid): pass def delete_scheduled_operation(self, operationid): pass
7
0
7
0
7
0
1
0
1
2
0
0
5
1
5
8
40
5
35
17
28
0
21
16
15
2
2
0
7
7,397
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/ArubaCloud/objects/Scheduled.py
ArubaCloud.objects.Scheduled.Creator
class Creator(object): __metaclass__ = ABCMeta json_msg = OrderedDict() def get_raw(self): return self.json_msg def get_json(self): return json.dumps(self.json_msg) def commit(self, url, debug=False): from ArubaCloud.helper import Http url = '{}/{}'.format(url, 'SetAddServerScheduledOperation') headers = {'Content-Type': 'application/json', 'Content-Length': len(self.get_json())} response = Http.post(url=url, data=self.get_json(), headers=headers) parsed_response = json.loads(response.content) if debug is True: print(parsed_response) if parsed_response["Success"]: return True return False
class Creator(object): def get_raw(self): pass def get_json(self): pass def commit(self, url, debug=False): pass
4
0
5
0
5
0
2
0
1
1
1
1
3
0
3
3
21
3
18
10
13
0
18
10
13
3
1
1
5
7,398
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/test/ReverseDns.py
test.ReverseDns.ReverseDnsTest
class ReverseDnsTest(unittest.TestCase): def setUp(self): self.reverseDns = ReverseDns(ws_uri=ws_uri, username=username, password=password) def test_get_reverse_dns(self): response = self.reverseDns.get(addresses=['77.81.230.29']) self.assertIsNotNone(response) self.assertIsInstance(response, list) def test_set_enqueue_set_reverse_dns(self): response = self.reverseDns.set(address='95.110.165.246', host_name=['myTestUnit.py']) self.assertIs(response, True) def test_set_enqueue_reset_reverse_dns(self): response = self.reverseDns.reset(address=['95.110.165.246']) self.assertIs(response, True)
class ReverseDnsTest(unittest.TestCase): def setUp(self): pass def test_get_reverse_dns(self): pass def test_set_enqueue_set_reverse_dns(self): pass def test_set_enqueue_reset_reverse_dns(self): pass
5
0
3
0
3
0
1
0
1
1
0
0
4
1
4
76
16
3
13
9
8
0
13
9
8
1
2
0
4
7,399
Arubacloud/pyArubaCloud
Arubacloud_pyArubaCloud/test/SharedStorage.py
test.SharedStorage.ReverseDnsTest
class ReverseDnsTest(unittest.TestCase): def setUp(self): self.sharedStorage = SharedStorage(ws_uri=ws_uri, username=username, password=password) def test_set_enqueue_purchase_shared_storage_iscsi(self): iqns = ['hsadfl.fsadf234f', 'f34f34f.2f43f2f3f'] response = self.sharedStorage.purchase_iscsi(quantity=100, name='TestSharedStorage', iqn=iqns) self.assertIsNotNone(response) def test_get_shared_storage(self): response = self.sharedStorage.get() self.assertIsNotNone(response) self.assertIsInstance(response, list)
class ReverseDnsTest(unittest.TestCase): def setUp(self): pass def test_set_enqueue_purchase_shared_storage_iscsi(self): pass def test_get_shared_storage(self): pass
4
0
4
0
4
0
1
0
1
1
0
0
3
1
3
75
14
2
12
8
8
0
11
8
7
1
2
0
3