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:
submenu.Check(self.id()+i, True)
menu.AppendMenu(-1, self.name, submenu)
|
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_submenu(submenu_path[1:], item)
return
self.add(MPMenuSubMenu(submenu_path[0], []))
self.add_to_submenu(submenu_path, item)
|
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
updated = True
if not updated:
self.items.append(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], self.flags)
dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flags)
if dlg.ShowModal() != wx.ID_OK:
return None
return dlg.GetPath()
|
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 know why yet
font = wx.Font(self.font_size, wx.MODERN, wx.NORMAL, wx.NORMAL)
dlg = GenericMessageDialog(None, self.message, self.title, wx.ICON_INFORMATION|wx.OK)
dlg.SetFont(font)
dlg.ShowModal()
app.MainLoop()
|
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'
self.header = self.read_ermapper_header(header_file)
nroflines = int(self.header['nroflines'])
nrofcellsperlines = int(self.header['nrofcellsperline'])
self.data = self.read_ermapper_data(data_file, offset=int(self.header['headeroffset']))
self.data = numpy.reshape(self.data,(nroflines,nrofcellsperlines))
longy = numpy.fromstring(self.getHeaderParam('longitude'), sep=':')
latty = numpy.fromstring(self.getHeaderParam('latitude'), sep=':')
self.deltalatitude = float(self.header['ydimension'])
self.deltalongitude = float(self.header['xdimension'])
if longy[0] < 0:
self.startlongitude = longy[0]+-((longy[1]/60)+(longy[2]/3600))
self.endlongitude = self.startlongitude - int(self.header['nrofcellsperline'])*self.deltalongitude
else:
self.startlongitude = longy[0]+(longy[1]/60)+(longy[2]/3600)
self.endlongitude = self.startlongitude + int(self.header['nrofcellsperline'])*self.deltalongitude
if latty[0] < 0:
self.startlatitude = latty[0]-((latty[1]/60)+(latty[2]/3600))
self.endlatitude = self.startlatitude - int(self.header['nroflines'])*self.deltalatitude
else:
self.startlatitude = latty[0]+(latty[1]/60)+(latty[2]/3600)
self.endlatitude = self.startlatitude + int(self.header['nroflines'])*self.deltalatitude
|
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 tiles = ", blank, "out of ", (nonblank+blank))
|
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,
self.target_component,
*self.override)
|
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 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))
|
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(outfile)
return geo_ref
|
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
elif origin is None:
geo_ref = None
else:
geo_ref = apply(Geo_reference, origin)
return geo_ref
|
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
# remember if we got a list
is_list = isinstance(points, list)
points = ensure_numeric(points, num.float)
# sanity checks
if len(points.shape) == 1:
#One point has been passed
msg = 'Single point must have two elements'
assert len(points) == 2, msg
points = num.reshape(points, (1,2))
msg = 'Points array must be two dimensional.\n'
msg += 'I got %d dimensions' %len(points.shape)
assert len(points.shape) == 2, msg
msg = 'Input must be an N x 2 array or list of (x,y) values. '
msg += 'I got an %d x %d array' %points.shape
assert points.shape[1] == 2, msg
# FIXME (Ole): Could also check if zone, xllcorner, yllcorner
# are identical in the two geo refs.
if points_geo_ref is not self:
# If georeferences are different
points = copy.copy(points) # Don't destroy input
if not points_geo_ref is None:
# Convert points to absolute coordinates
points[:,0] += points_geo_ref.xllcorner
points[:,1] += points_geo_ref.yllcorner
# Make points relative to primary geo reference
points[:,0] -= self.xllcorner
points[:,1] -= self.yllcorner
if is_list:
points = points.tolist()
return points
|
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.
# Moreover, this little function is responsible for a large fraction of the time
# using in data fitting (something in like 40 - 50%.
# This was due to the repeated calls to allclose.
# With the flag method fitting is much faster (18 Mar 2009).
# FIXME(Ole): HACK to be able to reuse data already cached (18 Mar 2009).
# Remove at some point
if not hasattr(self, 'absolute'):
self.absolute = num.allclose([self.xllcorner, self.yllcorner], 0)
# Return absolute flag
return self.absolute
|
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)
dLat = lat2 - lat1
dLon = lon2 - lon1
a = math.sin(0.5*dLat)**2 + math.sin(0.5*dLon)**2 * math.cos(lat1) * math.cos(lat2)
c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1.0-a))
return radius_of_earth * c
|
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
dLon = lon2 - lon1
y = math.sin(dLon) * math.cos(lat2)
x = math.cos(lat1)*math.sin(lat2) - math.sin(lat1)*math.cos(lat2)*math.cos(dLon)
bearing = math.degrees(math.atan2(y, x))
if bearing < 0:
bearing += 360.0
return bearing
|
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 RuntimeError("invalid polygon line: %s" % line)
ret.append((float(a[0]), float(a[1])))
f.close()
return ret
|
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 (minx, miny, maxx-minx, maxy-miny)
|
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, hemisphere=hemisphere)
|
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:
pass
|
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('ascii', 'ignore').strip()))
sys.exit(2)
except FileNotFoundError as e:
logger.error("Error: {}".format(e))
sys.exit(2)
ds = stdout.decode('ascii', 'ignore').strip()
dt = datetime.fromisoformat(ds)
utc = dt - dt.utcoffset()
return utc.strftime("%Y%m%d_%H%M%S")
|
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 ...', "image")
'http://example.com/img2.jpg'
>>> opengraph_get('<html><head><meta name="og:image" property="og:image" content="http://example.com/img3.jpg"><meta ...', "image")
'http://example.com/img3.jpg'
|
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.com/img2.jpg" property="og:image"><meta ...', "image")
'http://example.com/img2.jpg'
>>> opengraph_get('<html><head><meta name="og:image" property="og:image" content="http://example.com/img3.jpg"><meta ...', "image")
'http://example.com/img3.jpg'
"""
match = re.search('<meta [^>]*property="og:' + prop + '" content="([^"]*)"', html)
if match is None:
match = re.search('<meta [^>]*content="([^"]*)" property="og:' + prop + '"', html)
if match is None:
return None
return match.group(1)
|
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_unicode(s))
|
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 diacritical mark, which
# means that we will get base char when we strip out non-ascii.
title = unicodedata.normalize('NFD', title)
# Convert to lowercase
# Drop any non ascii letters/digits
# Drop any leading/trailing whitespace that may have appeared
title = re.sub(r'[^a-z0-9 .-]', '', title.lower().strip())
# Replace whitespace with dot
title = re.sub(r'\s+', '.', title)
title = re.sub(r'\.-\.', '-', title)
return title
|
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 to the reverse of the list's index values
proto_score = dict(zip(priolist, range(len(priolist), 0, -1)))
logging.debug("Protocol priority scores (higher is better): %s", str(proto_score))
# Build a tuple (bitrate, proto_score, stream), and use it
# for sorting.
prioritized = [(s.bitrate, proto_score[s.name], s) for
s in streams if s.name in proto_score]
return [x[2] for x in sorted(prioritized, key=itemgetter(0, 1), reverse=True)]
|
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)
try:
total_size = data.headers['content-length']
except KeyError:
total_size = 0
total_size = int(total_size)
bytes_so_far = 0
file_d = output(self.output, self.config, self.output_extention)
if file_d is None:
return
eta = ETA(total_size)
for i in data.iter_content(8192):
bytes_so_far += len(i)
file_d.write(i)
if not self.config.get("silent"):
eta.update(bytes_so_far)
progressbar(total_size, bytes_so_far, ''.join(["ETA: ", str(eta)]))
file_d.close()
self.finished = 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(setup_defaults(), options)
if len(urls) < 1:
parse.error("Incorrect number of arguments")
setup_log(config.get("silent"), config.get("verbose"))
if options.cmoreoperatorlist:
config = parsertoconfig(setup_defaults(), options)
c = Cmore(config, urls)
c.operatorlist()
sys.exit(0)
try:
if len(urls) == 1:
get_media(urls[0], config, __version__)
else:
get_multiple_media(urls, config)
except KeyboardInterrupt:
print("")
except (yaml.YAMLError, yaml.MarkedYAMLError) as e:
logging.error('Your settings file(s) contain invalid YAML syntax! Please fix and restart!, {}'.format(str(e)))
sys.exit(2)
|
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 progress bar will look something like this:
[099/500][=========...............................] ETA: 13:36:59
Of course, the ETA part should be supplied be the calling
function.
|
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
progressbar. It must not contain newlines.
The progress bar will look something like this:
[099/500][=========...............................] ETA: 13:36:59
Of course, the ETA part should be supplied be the calling
function.
"""
width = get_terminal_size()[0] - 40
rel_pos = int(float(pos) / total * width)
bar = ''.join(["=" * rel_pos, "." * (width - rel_pos)])
# Determine how many digits in total (base 10)
digits_total = len(str(total))
fmt_width = "%0" + str(digits_total) + "d"
fmt = "\r[" + fmt_width + "/" + fmt_width + "][%s] %s"
progress_stream.write(fmt % (pos, total, bar, msg))
|
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)
sec -= minutes * 60
output = "%02d:%02d:%06.3f" % (hours, minutes, sec)
return output.replace(".", ",")
|
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 url:
html_data = self.http.request("get", url).text
else:
html_data = self.get_urldata()
html_data = self.get_urldata()
match = re.search(r'data-video-id="([0-9]+)"', html_data)
if match:
return match.group(1)
match = re.search(r'data-videoid="([0-9]+)', html_data)
if match:
return match.group(1)
match = re.search(r'"mediaGuid":"([0-9]+)"', html_data)
if match:
return match.group(1)
clips = False
slug = None
match = re.search('params":({.*}),"query', self.get_urldata())
if match:
jansson = json.loads(match.group(1))
if "seasonNumberOrVideoId" in jansson:
season = jansson["seasonNumberOrVideoId"]
match = re.search(r"\w-(\d+)$", season)
if match:
season = match.group(1)
else:
match = self._conentpage(self.get_urldata())
if match: # this only happen on the program page?
janson2 = json.loads(match.group(1))
if janson2["formatPage"]["format"]:
season = janson2["formatPage"]["format"]["seasonNumber"]
return janson2["formatPage"]["format"]["videos"][str(season)]["program"][0]["id"]
return None
if "videoIdOrEpisodeNumber" in jansson:
videp = jansson["videoIdOrEpisodeNumber"]
match = re.search(r'(\w+)-(\d+)', videp)
if match:
episodenr = match.group(2)
else:
episodenr = videp
clips = True
match = re.search(r'(s\w+)-(\d+)', season)
if match:
season = match.group(2)
else:
# sometimes videoIdOrEpisodeNumber does not work.. this is a workaround
match = re.search(r'(episode|avsnitt)-(\d+)', self.url)
if match:
episodenr = match.group(2)
else:
episodenr = season
if "slug" in jansson:
slug = jansson["slug"]
if clips:
return episodenr
else:
match = self._conentpage(self.get_urldata())
if match:
janson = json.loads(match.group(1))
for i in janson["formatPage"]["format"]["videos"].keys():
if "program" in janson["formatPage"]["format"]["videos"][str(i)]:
for n in janson["formatPage"]["format"]["videos"][i]["program"]:
if str(n["episodeNumber"]) and int(episodenr) == n["episodeNumber"] and int(season) == n["seasonNumber"]:
if slug is None or slug == n["formatSlug"]:
return n["id"]
elif n["id"] == episodenr:
return episodenr
parse = urlparse(self.url)
match = re.search(r'/\w+/(\d+)', parse.path)
if match:
return match.group(1)
match = re.search(r'iframe src="http://play.juicyplay.se[^\"]+id=(\d+)', html_data)
if match:
return match.group(1)
match = re.search(r'<meta property="og:image" content="([\S]+)"', html_data)
if match:
return match.group(1).split("/")[-2]
return None
|
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 import ConsoleFrame
app = wx.App(False)
app.frame = ConsoleFrame(state=self, title=self.title)
app.frame.SetDoubleBuffered(True)
app.frame.Show()
app.MainLoop()
|
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_layout(msg, self.set_layout)
elif self.menu_callback is not None:
self.menu_callback(msg)
time.sleep(0.1)
except EOFError:
pass
|
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: auxopt set|show|reset|list")
return
if args[0] == 'list':
print("Options available:")
for s in sorted(aux_options.keys()):
print(' ' + s)
elif args[0] == 'show':
if len(args) > 2 and args[1] not in ['7', '8', 'all']:
print("Usage: auxopt show [7|8|all]")
return
if len(args) < 2 or args[1] == 'all':
self.aux_show('7')
self.aux_show('8')
return
self.aux_show(args[1])
elif args[0] == 'reset':
if len(args) < 2 or args[1] not in ['7', '8', 'all']:
print("Usage: auxopt reset 7|8|all")
return
if args[1] == 'all':
self.param_set('CH7_OPT', '0')
self.param_set('CH8_OPT', '0')
return
param = "CH%s_OPT" % args[1]
self.param_set(param, '0')
elif args[0] == 'set':
if len(args) < 3 or args[1] not in ['7', '8']:
print("Usage: auxopt set 7|8 OPTION")
return
option = self.aux_option_validate(args[2])
if not option:
print("Invalid option " + args[2])
return
param = "CH%s_OPT" % args[1]
self.param_set(param, aux_options[option])
else:
print("Usage: auxopt set|show|list")
|
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" % ' '.join(graphdef.expression.split()))
#mestate.mlog.reduce_by_flightmodes(mestate.flightmode_selections)
#setup the graph, then pass to a new process and display
self.mg = grapher.MavGraph(flightmode_colourmap)
if self.mestate.settings.title is not None:
self.mg.set_title(self.mestate.settings.title)
else:
self.mg.set_title(graphdef.name)
self.mg.set_marker(self.mestate.settings.marker)
self.mg.set_condition(self.mestate.settings.condition)
self.mg.set_xaxis(self.mestate.settings.xaxis)
self.mg.set_linestyle(self.mestate.settings.linestyle)
self.mg.set_show_flightmode(self.mestate.settings.show_flightmode)
self.mg.set_legend(self.mestate.settings.legend)
self.mg.add_mav(self.mestate.mlog)
for f in graphdef.expression.split():
self.mg.add_field(f)
self.mg.process(self.mestate.flightmode_selections, self.mestate.mlog._flightmodes)
self.lenmavlist = len(self.mg.mav_list)
#Important - mg.mav_list is the full logfile and can be very large in size
#To avoid slowdowns in Windows (which copies the vars to the new process)
#We need to empty this var when we're finished with it
self.mg.mav_list = []
child = multiproc.Process(target=self.mg.show, args=[self.lenmavlist,], kwargs={"xlim_pipe" : self.xlim_pipe})
child.start()
self.xlim_pipe[1].close()
self.mestate.mlog.rewind()
|
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 xlim != self.xlim:
return xlim
return None
|
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
return True
|
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.serial_settings.port,
flags,
0, 0, 0, [0]*70)
|
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 self.serial_settings.timeout >= 500:
flags |= mavutil.mavlink.SERIAL_CONTROL_FLAG_MULTI
s = ' '.join(args)
s = s.replace('\\r', '\r')
s = s.replace('\\n', '\n')
buf = [ord(x) for x in s]
buf.extend([0]*(70-len(buf)))
mav.serial_control_send(self.serial_settings.port,
flags,
self.serial_settings.timeout,
self.serial_settings.baudrate,
len(s), buf)
|
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(False)
elif args[0] == "set":
self.serial_settings.command(args[1:])
elif args[0] == "send":
self.serial_send(args[1:])
else:
print(usage)
|
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_map.mp_tile"
stream = pkg_resources.resource_stream(name, "data/%s" % filename).read()
raw = np.fromstring(stream, dtype=np.uint8)
except Exception:
try:
stream = open(os.path.join(__file__, 'data', filename)).read()
raw = np.fromstring(stream, dtype=np.uint8)
except Exception:
#we're in a Windows exe, where pkg_resources doesn't work
import pkgutil
raw = pkgutil.get_data( 'MAVProxy', 'modules//mavproxy_map//data//' + filename)
img = cv2.imdecode(raw, cv2.IMREAD_COLOR)
return img
|
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[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)
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:
#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
|
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 = 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)
img = cv2.imread(path)
if img is None:
continue
# 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
scaled = cv2.resize(roi, (TILES_HEIGHT,TILES_WIDTH))
#cv.Rectangle(scaled, (0,0), (255,255), (0,255,0), 1)
return scaled
return None
|
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(tile)
if img is None:
img = self._unavailable
return img
path = self.tile_to_path(tile)
ret = cv2.imread(path)
if ret is not None:
# 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
|
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 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 = min(width - t.dstx, scaled_tile.shape[1] - t.srcx)
h = min(height - t.dsty, scaled_tile.shape[0] - t.srcy)
if w > 0 and h > 0:
scaled_tile_roi = scaled_tile[t.srcy:t.srcy+h, t.srcx:t.srcx+w]
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
|
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)
elif args[0] == "download":
self.cmd_fw_download(rest)
elif args[0] in ["help","usage"]:
self.cmd_fw_help(rest)
else:
print(self.usage())
|
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",
"tri": "TRICOPTER",
"octa": "OCTOROTOR",
"octa-quad": "ARDUPILOT_OCTAQUAD",
"heli": "HELICOPTER",
"Plane": "FIXED_WING",
"Tracker": "ANTENNA_TRACKER",
"Rover": "GROUND_ROVER",
"PX4IO": "ARDUPILOT_PX4IO",
}
mavlink_to_frame_dict = { v : k for k,v in frame_to_mavlink_dict.items() }
x = firmware["mav-type"]
if firmware["mav-autopilot"] != "ARDUPILOTMEGA":
return x
if x in mavlink_to_frame_dict:
return mavlink_to_frame_dict[x]
return x
|
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"],
firmware["mav-firmware-version-minor"],
firmware["mav-firmware-version-patch"])
|
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(row_subs_value) != str(filtervalue):
return True
else:
print("fw: Unknown filter keyword (%s)" % (filtername,))
return False
|
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 form key-value is taken as a filter
filters[arg[0:equals]] = arg[equals+1:];
except ValueError:
remainder.append(arg)
return (filters,remainder)
|
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"],
"frame": frame,
# "type": firmware["mav-type"],
"releasetype": firmware["mav-firmware-version-type"],
"latest": firmware["latest"],
"git-sha": firmware["git-sha"][0:7],
"format": firmware["format"],
"_firmware": firmware,
}
(major,minor,patch) = self.semver_from_firmware(firmware)
if major is None:
row["version"] = ""
row["major"] = ""
row["minor"] = ""
row["patch"] = ""
else:
row["version"] = firmware["mav-firmware-version"]
row["major"] = major
row["minor"] = minor
row["patch"] = patch
i += 1
rows.append(row)
return rows
|
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)
all = self.all_firmwares()
rows = self.rows_for_firmwares(all)
filtered = self.filter_rows(filters, rows)
return (filtered, remainder)
|
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 row in filtered:
print("{seq:>5} {platform:<13} {frame:<10} {version:<10} {releasetype:<9} {latest:<6} {git-sha} {format}".format(**row))
|
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
if len(filtered) > 1:
print("fw: No single firmware specified")
return
firmware = filtered[0]["_firmware"]
url = firmware["url"]
try:
print("fw: URL: %s" % (url,))
filename=os.path.basename(url)
files = []
files.append((url,filename))
child = multiproc.Process(target=mp_util.download_files, args=(files,))
child.start()
except Exception as e:
print("fw: download failed")
print(e)
|
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))
except ValueError:
pass
return ret
|
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":
return self.cmd_fw_manifest_list()
if args[0] == "load":
return self.cmd_fw_manifest_load()
if args[0] == "purge":
return self.cmd_fw_manifest_purge()
if args[0] == "help":
return self.cmd_fw_manifest_help()
else:
print("fw: Unknown manifest option (%s)" % args[0])
print(fw_manifest_usage())
|
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))
manifest = self.manifest_parse(manifest_path)
if self.semver_major(manifest["format-version"]) != 1:
print("fw: Manifest (%s) has major version %d; MAVProxy only understands version 1" % (manifest_path,manifest["format-version"]))
continue
self.manifests.append(manifest)
|
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)
del self.downloaders[url]
removed_one = True
if removed_one and not self.downloaders.keys():
# all downloads finished - parse them
self.manifests_parse()
self.downloaders_lock.release()
|
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://firmware.ardupilot.org/manifest.json']:
filename = self.make_safe_filename_from_url(url)
path = mp_util.dot_mavproxy("manifest-%s" % filename)
self.downloaders[url] = threading.Thread(target=self.download_url, args=(url, path))
self.downloaders[url].start()
self.downloaders_lock.release()
else:
print("fw: Failed to acquire download lock")
|
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":
self.heading = m.heading
self.alt = m.alt
self.airspeed = m.airspeed
self.groundspeed = m.groundspeed
|
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],
width, height, ground_width)
while mt.tiles_pending() > 0:
print("Waiting on %u tiles" % mt.tiles_pending())
time.sleep(1)
map_img = mt.area_to_image(latlon[0], latlon[1],
width, height, ground_width)
# a function to convert from (lat,lon) to (px,py) on the map
pixmapper = functools.partial(pixel_coords, ground_width=ground_width, mt=mt, topleft=latlon, width=width)
for path_obj in path_objs:
path_obj.draw(map_img, pixmapper, None)
if mission_obj is not None:
for m in mission_obj:
m.draw(map_img, pixmapper, None)
if fence_obj is not None:
fence_obj.draw(map_img, pixmapper, None)
if (options is not None and
mav_type is not None and
options.colour_source == "flightmode"):
tuples = [ (mode, colour_for_flightmode(mav_type, mode))
for mode in used_flightmodes.keys() ]
legend = mp_slipmap.SlipFlightModeLegend("legend", tuples)
legend.draw(map_img, pixmapper, None)
map_img = cv2.cvtColor(map_img, cv2.COLOR_BGR2RGB)
cv2.imwrite(filename, map_img)
|
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(mlog, point, instance, options)
# evaluate source as an expression which should return a
# number in the range 0..255
try:
v = eval(source, globals(),mlog.messages)
except Exception as e:
str_e = str(e)
try:
count = colour_expression_exceptions[str_e]
except KeyError:
colour_expression_exceptions[str_e] = 0
count = 0
if count > 100:
print("Too many exceptions processing (%s): %s" % (source, str_e))
sys.exit(1)
colour_expression_exceptions[str_e] += 1
v = 0
# we don't use evaluate_expression as we want the exceptions...
# v = mavutil.evaluate_expression(source, mlog.messages)
if v is None:
v = 0
elif isinstance(v, str):
print("colour expression returned a string: %s" % v)
sys.exit(1)
elif v < 0:
print("colour expression returned %d (< 0)" % v)
v = 0
elif v > 255:
print("colour expression returned %d (> 255)" % v)
v = 255
if v < colour_source_min:
colour_source_min = v
if v > colour_source_max:
colour_source_max = v
r = 255
g = 255
b = v
return (b,b,b)
|
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 = True
for s in flightmode_selections:
if s:
all_false = False
idx = 0
path = [[]]
instances = {}
ekf_counter = 0
nkf_counter = 0
types = ['MISSION_ITEM','CMD']
if options.types is not None:
types.extend(options.types.split(','))
else:
types.extend(['GPS','GLOBAL_POSITION_INT'])
if options.rawgps or options.dualgps:
types.extend(['GPS', 'GPS_RAW_INT'])
if options.rawgps2 or options.dualgps:
types.extend(['GPS2_RAW','GPS2'])
if options.ekf:
types.extend(['EKF1', 'GPS'])
if options.nkf:
types.extend(['NKF1', 'GPS'])
if options.ahr2:
types.extend(['AHR2', 'AHRS2', 'GPS'])
print("Looking for types %s" % str(types))
last_timestamps = {}
used_flightmodes = {}
while True:
try:
m = mlog.recv_match(type=types)
if m is None:
break
except Exception:
break
type = m.get_type()
if type == 'MISSION_ITEM':
try:
while m.seq > wp.count():
print("Adding dummy WP %u" % wp.count())
wp.set(m, wp.count())
wp.set(m, m.seq)
except Exception:
pass
continue
if type == 'CMD':
m = mavutil.mavlink.MAVLink_mission_item_message(0,
0,
m.CNum,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
m.CId,
0, 1,
m.Prm1, m.Prm2, m.Prm3, m.Prm4,
m.Lat, m.Lng, m.Alt)
try:
while m.seq > wp.count():
print("Adding dummy WP %u" % wp.count())
wp.set(m, wp.count())
wp.set(m, m.seq)
except Exception:
pass
continue
if not mlog.check_condition(options.condition):
continue
if options.mode is not None and mlog.flightmode.lower() != options.mode.lower():
continue
if not all_false and len(flightmode_selections) > 0 and idx < len(options._flightmodes) and m._timestamp >= options._flightmodes[idx][2]:
idx += 1
elif (idx < len(flightmode_selections) and flightmode_selections[idx]) or all_false or len(flightmode_selections) == 0:
used_flightmodes[mlog.flightmode] = 1
if type in ['GPS','GPS2']:
status = getattr(m, 'Status', None)
if status is None:
status = getattr(m, 'FixType', None)
if status is None:
print("Can't find status on GPS message")
print(m)
break
if status < 2:
continue
# flash log
lat = m.Lat
lng = getattr(m, 'Lng', None)
if lng is None:
lng = getattr(m, 'Lon', None)
if lng is None:
print("Can't find longitude on GPS message")
print(m)
break
elif type in ['EKF1', 'ANU1']:
pos = mavextra.ekf1_pos(m)
if pos is None:
continue
ekf_counter += 1
if ekf_counter % options.ekf_sample != 0:
continue
(lat, lng) = pos
elif type in ['NKF1']:
pos = mavextra.ekf1_pos(m)
if pos is None:
continue
nkf_counter += 1
if nkf_counter % options.nkf_sample != 0:
continue
(lat, lng) = pos
elif type in ['ANU5']:
(lat, lng) = (m.Alat*1.0e-7, m.Alng*1.0e-7)
elif type in ['AHR2', 'POS', 'CHEK']:
(lat, lng) = (m.Lat, m.Lng)
elif type == 'AHRS2':
(lat, lng) = (m.lat*1.0e-7, m.lng*1.0e-7)
elif type == 'ORGN':
(lat, lng) = (m.Lat, m.Lng)
else:
lat = m.lat * 1.0e-7
lng = m.lon * 1.0e-7
# automatically add new types to instances
if type not in instances:
instances[type] = len(instances)
while len(instances) >= len(path):
path.append([])
instance = instances[type]
if abs(lat)>0.01 or abs(lng)>0.01:
colour = colour_for_point(mlog, (lat, lng), instance, options)
point = (lat, lng, colour)
if options.rate == 0 or not type in last_timestamps or m._timestamp - last_timestamps[type] > 1.0/options.rate:
last_timestamps[type] = m._timestamp
path[instance].append(point)
if len(path[0]) == 0:
print("No points to plot")
return None
return [path, wp, fen, used_flightmodes, getattr(mlog, 'mav_type',None)]
|
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 entire json
if not arg:
return json.dumps(status_dict)
# Get item from path
new_dict = status_dict
args = arg.split('/')
for key in args:
if key in new_dict:
new_dict = new_dict[key]
else:
return '{"key": "%s", "last_dict": %s}' % (key, json.dumps(new_dict))
return json.dumps(new_dict)
|
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
self.rest_server.start()
print("Rest server running: %s:%s" % \
(self.rest_server.address, self.rest_server.port))
elif args[0] == "stop":
if not self.rest_server.running():
print("Rest server is not running.")
return
self.rest_server.stop()
elif args[0] == "address":
# Check if have necessary amount of arguments
if len(args) != 2:
print("usage: restserver address <ip:port>")
return
address = args[1].split(':')
# Check if argument is correct
if len(address) == 2:
self.rest_server.set_ip_port(address[0], int(address[1]))
return
else:
print(self.usage())
|
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 Vservo < self.settings.servowarn:
if now - self.last_servo_warn_time > 30:
self.last_servo_warn_time = now
self.say("Servo volt %.1f" % Vservo)
if Vservo < 1:
# prevent continuous announcements on power down
self.high_servo_voltage = Vservo
if Vcc > 0 and Vcc < self.settings.vccwarn:
if now - self.last_vcc_warn_time > 30:
self.last_vcc_warn_time = now
self.say("Vcc %.1f" % Vcc)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.