INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
find the selected menu item | def find_selected(self, event):
'''find the selected menu item'''
first = self.id()
last = first + len(self.items) - 1
evid = event.GetId()
if evid >= first and evid <= last:
self.choice = evid - first
return self
return None |
append this menu item to a menu | def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
submenu = wx.Menu()
for i in range(len(self.items)):
submenu.AppendRadioItem(self.id()+i, self.items[i], self.description)
if self.items[i] == self.initial:
sub... |
add an item to a submenu using a menu path array | def add_to_submenu(self, submenu_path, item):
'''add an item to a submenu using a menu path array'''
if len(submenu_path) == 0:
self.add(item)
return
for m in self.items:
if isinstance(m, MPMenuSubMenu) and submenu_path[0] == m.name:
m.add_to_s... |
find the selected menu item | def find_selected(self, event):
'''find the selected menu item'''
for m in self.items:
ret = m.find_selected(event)
if ret is not None:
return ret
return None |
append this menu item to a menu | def _append(self, menu):
'''append this menu item to a menu'''
from wx_loader import wx
menu.AppendMenu(-1, self.name, self.wx_menu()) |
add a submenu | def add(self, items):
'''add a submenu'''
if not isinstance(items, list):
items = [items]
for m in items:
updated = False
for i in range(len(self.items)):
if self.items[i].name == m.name:
self.items[i] = m
... |
find the selected menu item | def find_selected(self, event):
'''find the selected menu item'''
for i in range(len(self.items)):
m = self.items[i]
ret = m.find_selected(event)
if ret is not None:
return ret
return None |
show a file dialog | def call(self):
'''show a file dialog'''
from wx_loader import wx
# remap flags to wx descriptors
flag_map = {
'open': wx.FD_OPEN,
'save': wx.FD_SAVE,
'overwrite_prompt': wx.FD_OVERWRITE_PROMPT,
}
flags = map(lambda x: flag_map[x], sel... |
show a value dialog | def call(self):
'''show a value dialog'''
from wx_loader import wx
dlg = wx.TextEntryDialog(None, self.title, self.title, defaultValue=str(self.default))
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetValue() |
show the dialog as a child process | def call(self):
'''show the dialog as a child process'''
mp_util.child_close_fds()
import wx_processguard
from wx_loader import wx
from wx.lib.agw.genericmessagedialog import GenericMessageDialog
app = wx.App(False)
# note! font size change is not working. I don't... |
Read in a DEM file and associated .ers file | def read_ermapper(self, ifile):
'''Read in a DEM file and associated .ers file'''
ers_index = ifile.find('.ers')
if ers_index > 0:
data_file = ifile[0:ers_index]
header_file = ifile
else:
data_file = ifile
header_file = ifile + '.ers'
... |
Print the bounding box that this DEM covers | def printBoundingBox(self):
'''Print the bounding box that this DEM covers'''
print ("Bounding Latitude: ")
print (self.startlatitude)
print (self.endlatitude)
print ("Bounding Longitude: ")
print (self.startlongitude)
print (self.endlongitude) |
Print how many null cells are in the DEM - Quality measure | def getPercentBlank(self):
'''Print how many null cells are in the DEM - Quality measure'''
blank = 0
nonblank = 0
for x in self.data.flat:
if x == -99999.0:
blank = blank + 1
else:
nonblank = nonblank + 1
print ("Blank til... |
send RC override packet | def send_rc_override(self):
'''send RC override packet'''
if self.sitl_output:
buf = struct.pack('<HHHHHHHH',
*self.override)
self.sitl_output.write(buf)
else:
self.master.mav.rc_channels_override_send(self.target_system,
... |
handle RC switch changes | 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 val... |
this is a public method for use by drone API or other scripting | 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() |
this is a public method for use by drone API or other scripting | 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() |
Write georeference info to a netcdf file, usually sww.
The origin can be a georef instance or parameters for a geo_ref instance
outfile is the name of the file to be written to. | def write_NetCDF_georeference(origin, outfile):
"""Write georeference info to a netcdf file, usually sww.
The origin can be a georef instance or parameters for a geo_ref instance
outfile is the name of the file to be written to.
"""
geo_ref = ensure_geo_reference(origin)
geo_ref.write_NetCDF(... |
Given a list/tuple of zone, xllcorner and yllcorner of a geo-ref object,
return a geo ref object.
If the origin is None, return None, so calling this function doesn't
effect code logic | def ensure_geo_reference(origin):
"""
Given a list/tuple of zone, xllcorner and yllcorner of a geo-ref object,
return a geo ref object.
If the origin is None, return None, so calling this function doesn't
effect code logic
"""
if isinstance(origin, Geo_reference):
geo_ref = origin
... |
Change the geo reference of a list or numeric array of points to
be this reference.(The reference used for this object)
If the points do not have a geo ref, assume 'absolute' values | def change_points_geo_ref(self, points, points_geo_ref=None):
"""Change the geo reference of a list or numeric array of points to
be this reference.(The reference used for this object)
If the points do not have a geo ref, assume 'absolute' values
"""
import copy
# rememb... |
Return True if xllcorner==yllcorner==0 indicating that points
in question are absolute. | def is_absolute(self):
"""Return True if xllcorner==yllcorner==0 indicating that points
in question are absolute.
"""
# FIXME(Ole): It is unfortunate that decision about whether points
# are absolute or not lies with the georeference object. Ross pointed this out.
# More... |
return distance between two points in meters,
coordinates are in degrees
thanks to http://www.movable-type.co.uk/scripts/latlong.html | def gps_distance(lat1, lon1, lat2, lon2):
'''return distance between two points in meters,
coordinates are in degrees
thanks to http://www.movable-type.co.uk/scripts/latlong.html'''
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
lon1 = math.radians(lon1)
lon2 = math.radians(lon2)
dL... |
return bearing between two points in degrees, in range 0-360
thanks to http://www.movable-type.co.uk/scripts/latlong.html | def gps_bearing(lat1, lon1, lat2, lon2):
'''return bearing between two points in degrees, in range 0-360
thanks to http://www.movable-type.co.uk/scripts/latlong.html'''
lat1 = math.radians(lat1)
lat2 = math.radians(lat2)
lon1 = math.radians(lon1)
lon2 = math.radians(lon2)
dLat = lat2 - lat1
... |
return new lat/lon after moving east/north
by the given number of meters | def gps_offset(lat, lon, east, north):
'''return new lat/lon after moving east/north
by the given number of meters'''
bearing = math.degrees(math.atan2(east, north))
distance = math.sqrt(east**2 + north**2)
return gps_newpos(lat, lon, bearing, distance) |
like mkdir -p | def mkdir_p(dir):
'''like mkdir -p'''
if not dir:
return
if dir.endswith("/") or dir.endswith("\\"):
mkdir_p(dir[:-1])
return
if os.path.isdir(dir):
return
mkdir_p(os.path.dirname(dir))
try:
os.mkdir(dir)
except Exception:
pass |
load a polygon from a file | def polygon_load(filename):
'''load a polygon from a file'''
ret = []
f = open(filename)
for line in f:
if line.startswith('#'):
continue
line = line.strip()
if not line:
continue
a = line.split()
if len(a) != 2:
raise RuntimeEr... |
return bounding box of a polygon in (x,y,width,height) form | def polygon_bounds(points):
'''return bounding box of a polygon in (x,y,width,height) form'''
(minx, miny) = (points[0][0], points[0][1])
(maxx, maxy) = (minx, miny)
for p in points:
minx = min(minx, p[0])
maxx = max(maxx, p[0])
miny = min(miny, p[1])
maxy = max(maxy, p[1... |
return true if two bounding boxes overlap | def bounds_overlap(bound1, bound2):
'''return true if two bounding boxes overlap'''
(x1,y1,w1,h1) = bound1
(x2,y2,w2,h2) = bound2
if x1+w1 < x2:
return False
if x2+w2 < x1:
return False
if y1+h1 < y2:
return False
if y2+h2 < y1:
return False
return True |
return a degrees:minutes:seconds string | def degrees_to_dms(degrees):
'''return a degrees:minutes:seconds string'''
deg = int(degrees)
min = int((degrees - deg)*60)
sec = ((degrees - deg) - (min/60.0))*60*60
return u'%d\u00b0%02u\'%05.2f"' % (deg, abs(min), abs(sec)) |
convert to grid reference | def latlon_to_grid(latlon):
'''convert to grid reference'''
from MAVProxy.modules.lib.ANUGA import redfearn
(zone, easting, northing) = redfearn.redfearn(latlon[0], latlon[1])
if latlon[0] < 0:
hemisphere = 'S'
else:
hemisphere = 'N'
return UTMGrid(zone, easting, northing, hemisp... |
round to nearest grid corner | def latlon_round(latlon, spacing=1000):
'''round to nearest grid corner'''
g = latlon_to_grid(latlon)
g.easting = (g.easting // spacing) * spacing
g.northing = (g.northing // spacing) * spacing
return g.latlon() |
convert a wxImage to a PIL Image | def wxToPIL(wimg):
'''convert a wxImage to a PIL Image'''
from PIL import Image
(w,h) = wimg.GetSize()
d = wimg.GetData()
pimg = Image.new("RGB", (w,h), color=1)
pimg.fromstring(d)
return pimg |
convert a PIL Image to a wx image | def PILTowx(pimg):
'''convert a PIL Image to a wx image'''
from wx_loader import wx
wimg = wx.EmptyImage(pimg.size[0], pimg.size[1])
wimg.SetData(pimg.convert('RGB').tostring())
return wimg |
return a path to store mavproxy data | def dot_mavproxy(name):
'''return a path to store mavproxy data'''
dir = os.path.join(os.environ['HOME'], '.mavproxy')
mkdir_p(dir)
return os.path.join(dir, name) |
download a URL and return the content | def download_url(url):
'''download a URL and return the content'''
import urllib2
try:
resp = urllib2.urlopen(url)
headers = resp.info()
except urllib2.URLError as e:
print('Error downloading %s' % url)
return None
return resp.read() |
close file descriptors that a child process should not inherit.
Should be called from child processes. | def child_close_fds():
'''close file descriptors that a child process should not inherit.
Should be called from child processes.'''
global child_fd_list
import os
while len(child_fd_list) > 0:
fd = child_fd_list.pop(0)
try:
os.close(fd)
except Exception as msg:... |
return (lat,lon) for the grid coordinates | def latlon(self):
'''return (lat,lon) for the grid coordinates'''
from MAVProxy.modules.lib.ANUGA import lat_long_UTM_conversion
(lat, lon) = lat_long_UTM_conversion.UTMtoLL(self.northing, self.easting, self.zone, isSouthernHemisphere=(self.hemisphere=='S'))
return (lat, lon) |
Use the commit date in UTC as folder name | def snapshot_folder():
"""
Use the commit date in UTC as folder name
"""
logger.info("Snapshot folder")
try:
stdout = subprocess.check_output(["git", "show", "-s", "--format=%cI", "HEAD"])
except subprocess.CalledProcessError as e:
logger.error("Error: {}".format(e.output.decode(... |
Extract specified OpenGraph property from html.
>>> opengraph_get('<html><head><meta property="og:image" content="http://example.com/img.jpg"><meta ...', "image")
'http://example.com/img.jpg'
>>> opengraph_get('<html><head><meta content="http://example.com/img2.jpg" property="og:image"><meta ..... | def opengraph_get(html, prop):
"""
Extract specified OpenGraph property from html.
>>> opengraph_get('<html><head><meta property="og:image" content="http://example.com/img.jpg"><meta ...', "image")
'http://example.com/img.jpg'
>>> opengraph_get('<html><head><meta content="http://example... |
Replaces html entities with the character they represent.
>>> print(decode_html_entities("<3 &"))
<3 & | def decode_html_entities(s):
"""
Replaces html entities with the character they represent.
>>> print(decode_html_entities("<3 &"))
<3 &
"""
parser = HTMLParser.HTMLParser()
def unesc(m):
return parser.unescape(m.group())
return re.sub(r'(&[^;]+;)', unesc, ensure_... |
Convert a string to something suitable as a file name. E.g.
Matlagning del 1 av 10 - Räksmörgås | SVT Play
-> matlagning.del.1.av.10.-.raksmorgas.svt.play | def filenamify(title):
"""
Convert a string to something suitable as a file name. E.g.
Matlagning del 1 av 10 - Räksmörgås | SVT Play
-> matlagning.del.1.av.10.-.raksmorgas.svt.play
"""
# ensure it is unicode
title = ensure_unicode(title)
# NFD decomposes chars into base char and ... |
Given a list of VideoRetriever objects and a prioritized list of
accepted protocols (as strings) (highest priority first), return
a list of VideoRetriever objects that are accepted, and sorted
by bitrate, and then protocol priority. | def protocol_prio(streams, priolist):
"""
Given a list of VideoRetriever objects and a prioritized list of
accepted protocols (as strings) (highest priority first), return
a list of VideoRetriever objects that are accepted, and sorted
by bitrate, and then protocol priority.
"""
# Map score's... |
Get the stream from HTTP | def download(self):
""" Get the stream from HTTP """
_, ext = os.path.splitext(self.url)
if ext == ".mp3":
self.output_extention = "mp3"
else:
self.output_extention = "mp4" # this might be wrong..
data = self.http.request("get", self.url, stream=True)
... |
Main program | def main():
""" Main program """
parse, options = parser(__version__)
if options.flexibleq and not options.quality:
logging.error("flexible-quality requires a quality")
if len(options.urls) == 0:
parse.print_help()
sys.exit(0)
urls = options.urls
config = parsertoconfig... |
Print some info about how much we have downloaded | def progress(byte, total, extra=""):
""" Print some info about how much we have downloaded """
if total == 0:
progresstr = "Downloaded %dkB bytes" % (byte >> 10)
progress_stream.write(progresstr + '\r')
return
progressbar(total, byte, extra) |
Given a total and a progress position, output a progress bar
to stderr. It is important to not output anything else while
using this, as it relies soley on the behavior of carriage
return (\\r).
Can also take an optioal message to add after the
progressbar. It must not contain newlines.
The pr... | def progressbar(total, pos, msg=""):
"""
Given a total and a progress position, output a progress bar
to stderr. It is important to not output anything else while
using this, as it relies soley on the behavior of carriage
return (\\r).
Can also take an optioal message to add after the
progr... |
Set new absolute progress position.
Parameters:
pos: new absolute progress | def update(self, pos):
"""
Set new absolute progress position.
Parameters:
pos: new absolute progress
"""
self.pos = pos
self.now = time.time() |
Convert a millisecond value to a string of the following
format:
HH:MM:SS,SS
with 10 millisecond precision. Note the , seperator in
the seconds. | def timestr(msec):
"""
Convert a millisecond value to a string of the following
format:
HH:MM:SS,SS
with 10 millisecond precision. Note the , seperator in
the seconds.
"""
sec = float(msec) / 1000
hours = int(sec / 3600)
sec -= hours * 3600
minutes = int(sec / 60)
... |
Extract video id. It will try to avoid making an HTTP request
if it can find the ID in the URL, but otherwise it will try
to scrape it from the HTML document. Returns None in case it's
unable to extract the ID at all. | def _get_video_id(self, url=None):
"""
Extract video id. It will try to avoid making an HTTP request
if it can find the ID in the URL, but otherwise it will try
to scrape it from the HTML document. Returns None in case it's
unable to extract the ID at all.
"""
if ... |
child process - this holds all the GUI elements | def child_task(self):
'''child process - this holds all the GUI elements'''
self.parent_pipe_send.close()
self.parent_pipe_recv.close()
from MAVProxy.modules.lib import wx_processguard
from MAVProxy.modules.lib.wx_loader import wx
from MAVProxy.modules.lib.wxconsole_ui i... |
watch for menu events from child | def watch_thread(self):
'''watch for menu events from child'''
from MAVProxy.modules.lib.mp_settings import MPSetting
try:
while True:
msg = self.parent_pipe_recv.recv()
if isinstance(msg, win_layout.WinLayout):
win_layout.set_layou... |
handle AUX switches (CH7, CH8) settings | def cmd_auxopt(self, args):
'''handle AUX switches (CH7, CH8) settings'''
if self.mpstate.vehicle_type != 'copter':
print("This command is only available for copter")
return
if len(args) == 0 or args[0] not in ('set', 'show', 'reset', 'list'):
print("Usage: au... |
display a graph | def display_graph(self, graphdef, flightmode_colourmap=None):
'''display a graph'''
if 'mestate' in globals():
self.mestate.console.write("Expression: %s\n" % ' '.join(graphdef.expression.split()))
else:
self.mestate.child_pipe_send_console.send("Expression: %s\n" % ' '.j... |
check for new X bounds | def check_xlim_change(self):
'''check for new X bounds'''
if self.xlim_pipe is None:
return None
xlim = None
while self.xlim_pipe[0].poll():
try:
xlim = self.xlim_pipe[0].recv()
except EOFError:
return None
if xl... |
set new X bounds | def set_xlim(self, xlim):
'''set new X bounds'''
if self.xlim_pipe is not None and self.xlim != xlim:
#print("send0: ", graph_count, xlim)
try:
self.xlim_pipe[0].send(xlim)
except IOError:
return False
self.xlim = xlim
... |
handle an incoming mavlink packet | def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'SERIAL_CONTROL':
data = m.data[:m.count]
s = ''.join(str(chr(x)) for x in data)
sys.stdout.write(s) |
lock or unlock the port | def serial_lock(self, lock):
'''lock or unlock the port'''
mav = self.master.mav
if lock:
flags = mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
self.locked = True
else:
flags = 0
self.locked = False
mav.serial_control_send(self.seri... |
send some bytes | def serial_send(self, args):
'''send some bytes'''
mav = self.master.mav
flags = 0
if self.locked:
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_EXCLUSIVE
if self.serial_settings.timeout != 0:
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_RESPOND
if ... |
serial control commands | def cmd_serial(self, args):
'''serial control commands'''
usage = "Usage: serial <lock|unlock|set|send>"
if len(args) < 1:
print(usage)
return
if args[0] == "lock":
self.serial_lock(True)
elif args[0] == "unlock":
self.serial_lock(F... |
load an icon from the data directory | def mp_icon(filename):
'''load an icon from the data directory'''
# we have to jump through a lot of hoops to get an OpenCV image
# when we may be in a package zip file
try:
import pkg_resources
name = __name__
if name == "__main__":
name = "MAVProxy.modules.mavproxy_... |
the download thread | 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[ke... |
load a lower resolution tile from cache to fill in a
map while waiting for a higher resolution tile | 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 = TILE... |
load a tile from cache or tile server | 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(t... |
return a scaled tile | 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 |
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 | 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 tile... |
execute command defined in args | def cmd_fw(self, args):
'''execute command defined in args'''
if len(args) == 0:
print(self.usage())
return
rest = args[1:]
if args[0] == "manifest":
self.cmd_fw_manifest(rest)
elif args[0] == "list":
self.cmd_fw_list(rest)
... |
extract information from firmware, return pretty string to user | def frame_from_firmware(self, firmware):
'''extract information from firmware, return pretty string to user'''
# see Tools/scripts/generate-manifest for this map:
frame_to_mavlink_dict = {
"quad": "QUADROTOR",
"hexa": "HEXAROTOR",
"y6": "ARDUPILOT_Y6",
... |
Extract a tuple of (major,minor,patch) from a firmware instance | def semver_from_firmware(self, firmware):
'''Extract a tuple of (major,minor,patch) from a firmware instance'''
version = firmware.get("mav-firmware-version-major",None)
if version is None:
return (None,None,None)
return (firmware["mav-firmware-version-major"],
... |
returns True if row should NOT be included according to filters | def row_is_filtered(self, row_subs, filters):
'''returns True if row should NOT be included according to filters'''
for filtername in filters:
filtervalue = filters[filtername]
if filtername in row_subs:
row_subs_value = row_subs[filtername]
if str... |
take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments | def filters_from_args(self, args):
'''take any argument of the form name=value anmd put it into a dict; return that and the remaining arguments'''
filters = dict()
remainder = []
for arg in args:
try:
equals = arg.index('=')
# anything ofthe fo... |
return firmware entries from all manifests | def all_firmwares(self):
''' return firmware entries from all manifests'''
all = []
for manifest in self.manifests:
for firmware in manifest["firmware"]:
all.append(firmware)
return all |
provide user-readable text for a firmware entry | def rows_for_firmwares(self, firmwares):
'''provide user-readable text for a firmware entry'''
rows = []
i = 0
for firmware in firmwares:
frame = self.frame_from_firmware(firmware)
row = {
"seq": i,
"platform": firmware["platform"],... |
returns rows as filtered by filters | def filter_rows(self, filters, rows):
'''returns rows as filtered by filters'''
ret = []
for row in rows:
if not self.row_is_filtered(row, filters):
ret.append(row)
return ret |
extracts filters from args, rows from manifests, returns filtered rows | def filtered_rows_from_args(self, args):
'''extracts filters from args, rows from manifests, returns filtered rows'''
if len(self.manifests) == 0:
print("fw: No manifests downloaded. Try 'manifest download'")
return None
(filters,remainder) = self.filters_from_args(args... |
cmd handler for list | def cmd_fw_list(self, args):
'''cmd handler for list'''
stuff = self.filtered_rows_from_args(args)
if stuff is None:
return
(filtered, remainder) = stuff
print("")
print(" seq platform frame major.minor.patch releasetype latest git-sha format")
for ... |
cmd handler for downloading firmware | def cmd_fw_download(self, args):
'''cmd handler for downloading firmware'''
stuff = self.filtered_rows_from_args(args)
if stuff is None:
return
(filtered, remainder) = stuff
if len(filtered) == 0:
print("fw: No firmware specified")
return
... |
locate manifests and return filepaths thereof | def find_manifests(self):
'''locate manifests and return filepaths thereof'''
manifest_dir = mp_util.dot_mavproxy()
ret = []
for file in os.listdir(manifest_dir):
try:
file.index("manifest")
ret.append(os.path.join(manifest_dir,file))
... |
remove all downloaded manifests | def cmd_fw_manifest_purge(self):
'''remove all downloaded manifests'''
for filepath in self.find_manifests():
os.unlink(filepath)
self.manifests_parse() |
cmd handler for manipulating manifests | def cmd_fw_manifest(self, args):
'''cmd handler for manipulating manifests'''
if len(args) == 0:
print(self.fw_manifest_usage())
return
rest = args[1:]
if args[0] == "download":
return self.manifest_download()
if args[0] == "list":
... |
parse manifest at path, return JSON object | def manifest_parse(self, path):
'''parse manifest at path, return JSON object'''
print("fw: parsing manifests")
content = open(path).read()
return json.loads(content) |
return true if path is more than a day old | def manifest_path_is_old(self, path):
'''return true if path is more than a day old'''
mtime = os.path.getmtime(path)
return (time.time() - mtime) > 24*60*60 |
parse manifests present on system | def manifests_parse(self):
'''parse manifests present on system'''
self.manifests = []
for manifest_path in self.find_manifests():
if self.manifest_path_is_old(manifest_path):
print("fw: Manifest (%s) is old; consider 'manifest download'" % (manifest_path))
... |
called rapidly by mavproxy | def idle_task(self):
'''called rapidly by mavproxy'''
if self.downloaders_lock.acquire(False):
removed_one = False
for url in self.downloaders.keys():
if not self.downloaders[url].is_alive():
print("fw: Download thread for (%s) done" % url)
... |
return a version of url safe for use as a filename | def make_safe_filename_from_url(self, url):
'''return a version of url safe for use as a filename'''
r = re.compile("([^a-zA-Z0-9_.-])")
filename = r.sub(lambda m : "%" + str(hex(ord(str(m.group(1))))).upper(), url)
return filename |
download manifest files | def manifest_download(self):
'''download manifest files'''
if self.downloaders_lock.acquire(False):
if len(self.downloaders):
# there already exist downloader threads
self.downloaders_lock.release()
return
for url in ['http://firmw... |
control behaviour of the module | def cmd_msg(self, args):
'''control behaviour of the module'''
if len(args) == 0:
print(self.usage())
txt = ' '.join(args)
self.master.mav.statustext_send(mavutil.mavlink.MAV_SEVERITY_NOTICE,
txt) |
handle an incoming mavlink packet | def mavlink_packet(self, m):
"""handle an incoming mavlink packet"""
mtype = m.get_type()
if mtype == 'GPS_RAW':
(self.lat, self.lon) = (m.lat, m.lon)
elif mtype == 'GPS_RAW_INT':
(self.lat, self.lon) = (m.lat / 1.0e7, m.lon / 1.0e7)
elif mtype == "VFR_HUD... |
create path and mission as an image file | def create_imagefile(options, filename, latlon, ground_width, path_objs, mission_obj, fence_obj, width=600, height=600, used_flightmodes=[], mav_type=None):
'''create path and mission as an image file'''
mt = mp_tile.MPTile(service=options.service)
map_img = mt.area_to_image(latlon[0], latlon[1],
... |
indicate a colour to be used to plot point | def colour_for_point(mlog, point, instance, options):
global colour_expression_exceptions, colour_source_max, colour_source_min
'''indicate a colour to be used to plot point'''
source = getattr(options, "colour_source", "flightmode")
if source == "flightmode":
return colour_for_point_flightmode(... |
create a map for a log file | def mavflightview_mav(mlog, options=None, flightmode_selections=[]):
'''create a map for a log file'''
wp = mavwp.MAVWPLoader()
if options.mission is not None:
wp.load(options.mission)
fen = mavwp.MAVFenceLoader()
if options.fence is not None:
fen.load(options.fence)
all_false = ... |
Translate mavlink python messages in json string | def mavlink_to_json(msg):
'''Translate mavlink python messages in json string'''
ret = '\"%s\": {' % msg._type
for fieldname in msg._fieldnames:
data = getattr(msg, fieldname)
ret += '\"%s\" : \"%s\", ' % (fieldname, data)
ret = ret[0:-2] + '}'
return ret |
Translate MPStatus in json string | def mpstatus_to_json(status):
'''Translate MPStatus in json string'''
msg_keys = list(status.msgs.keys())
data = '{'
for key in msg_keys[:-1]:
data += mavlink_to_json(status.msgs[key]) + ','
data += mavlink_to_json(status.msgs[msg_keys[-1]])
data += '}'
return data |
set ip and port | def set_ip_port(self, ip, port):
'''set ip and port'''
self.address = ip
self.port = port
self.stop()
self.start() |
Stop server | def start(self):
'''Stop server'''
# Set flask
self.app = Flask('RestServer')
self.add_endpoint()
# Create a thread to deal with flask
self.run_thread = Thread(target=self.run)
self.run_thread.start() |
Stop server | def stop(self):
'''Stop server'''
self.app = None
if self.run_thread:
self.run_thread = None
if self.server:
self.server.shutdown()
self.server = None |
Start app | def run(self):
'''Start app'''
self.server = make_server(self.address, self.port, self.app, threaded=True)
self.server.serve_forever() |
Deal with requests | def request(self, arg=None):
'''Deal with requests'''
if not self.status:
return '{"result": "No message"}'
try:
status_dict = json.loads(mpstatus_to_json(self.status))
except Exception as e:
print(e)
return
# If no key, send the ... |
Set endpoits | def add_endpoint(self):
'''Set endpoits'''
self.app.add_url_rule('/rest/mavlink/<path:arg>', 'rest', self.request)
self.app.add_url_rule('/rest/mavlink/', 'rest', self.request) |
control behaviour of the module | def cmds(self, args):
'''control behaviour of the module'''
if not args or len(args) < 1:
print(self.usage())
return
if args[0] == "start":
if self.rest_server.running():
print("Rest server already running.")
return
... |
update POWER_STATUS warnings level | def power_status_update(self, POWER_STATUS):
'''update POWER_STATUS warnings level'''
now = time.time()
Vservo = POWER_STATUS.Vservo * 0.001
Vcc = POWER_STATUS.Vcc * 0.001
self.high_servo_voltage = max(self.high_servo_voltage, Vservo)
if self.high_servo_voltage > 1 and Vs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.