Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

MAVProxy and modules: Windows compatibility fixes

Various fixes to MAVProxy and the map, console and srtm modules for
Windows compatibility. Batch files for launching MAVProxy in Windows
also included
  • Loading branch information...
commit dec3033d17dd2223a7651d693bc511c28283f7c6 1 parent ce76da6
@stephendade stephendade authored committed
View
6 MAVProxyWinLAN.bat
@@ -0,0 +1,6 @@
+setlocal
+SET PATH=%PATH%;..\mavlink;..\mavlink\pymavlink\examples
+
+mavproxy.py --master=192.168.1.6:14550
+
+pause
View
6 MAVProxyWinUSB.bat
@@ -0,0 +1,6 @@
+setlocal
+SET PATH=%PATH%;..\mavlink;..\mavlink\pymavlink\examples
+
+mavproxy.py --master=COM10 --baudrate=115200
+
+pause
View
52 mavproxy.py
@@ -17,12 +17,6 @@
os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'mavlink', 'pymavlink') ]:
if os.path.exists(d):
sys.path.insert(0, d)
- if os.name == 'nt':
- try:
- # broken python compilation of mavlink.py on windows!
- os.unlink(os.path.join(d, 'mavlink.pyc'))
- except:
- pass
# add modules path
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), 'modules'))
@@ -189,7 +183,7 @@ def set_prompt(self, prompt):
if prompt != self.prompt:
self.prompt = prompt
sys.stdout.write(prompt)
-
+
def say(text, priority='important'):
'''speak some text'''
''' http://cvs.freebsoft.org/doc/speechd/ssip.html see 4.3.1 for priorities'''
@@ -384,7 +378,7 @@ def save_waypoints(filename):
print("Failed to save %s - %s" % (filename, msg))
return
print("Saved %u waypoints to %s" % (mpstate.status.wploader.count(), filename))
-
+
def cmd_wp(args):
'''waypoint commands'''
@@ -510,7 +504,7 @@ def list_fence(filename):
if mpstate.status.logdir != None:
fencetxt = os.path.join(mpstate.status.logdir, 'fence.txt')
mpstate.status.fenceloader.save(fencetxt)
- print("Saved fence to %s" % fencetxt)
+ print("Saved fence to %s" % fencetxt)
def cmd_fence(args):
@@ -535,7 +529,7 @@ def cmd_fence(args):
if len(args) != 2:
print("usage: fence show <filename>")
return
- mpstate.status.fenceloader.load(args[1])
+ mpstate.status.fenceloader.load(args[1])
elif args[0] == "clear":
param_set('FENCE_TOTAL', 0)
else:
@@ -857,7 +851,7 @@ def system_check():
if not 'PITCH_MIN' in mpstate.mav_param:
say("WARNING no pitch parameter available")
return
-
+
if int(mpstate.mav_param['PITCH_MIN']) > 1300:
say("WARNING PITCH MINIMUM not set")
ok = False
@@ -968,7 +962,7 @@ def handle_msec_timestamp(m, master):
if msec < mpstate.status.highest_msec and len(mpstate.mav_master) > 1:
master.link_delayed = True
else:
- master.link_delayed = False
+ master.link_delayed = False
def report_altitude(altitude):
'''possibly report a new altitude'''
@@ -976,7 +970,7 @@ def report_altitude(altitude):
if getattr(mpstate.console, 'ElevationMap', None) is not None and mpstate.settings.basealt != 0:
lat = master.field('GLOBAL_POSITION_INT', 'lat', 0)*1.0e-7
lon = master.field('GLOBAL_POSITION_INT', 'lon', 0)*1.0e-7
- alt1 = mpstate.console.ElevationMap.GetElevation(lat, lon)
+ alt1 = mpstate.console.ElevationMap.GetElevation(lat, lon)
alt2 = mpstate.settings.basealt
altitude += alt2 - alt1
mpstate.status.altitude = altitude
@@ -985,7 +979,7 @@ def report_altitude(altitude):
mpstate.status.last_altitude_announce = mpstate.status.altitude
rounded_alt = int(mpstate.settings.altreadout) * ((5+int(mpstate.status.altitude)) / int(mpstate.settings.altreadout))
say("height %u" % rounded_alt, priority='notification')
-
+
def master_callback(m, master):
'''process mavlink message m on master, sending any messages to recipients'''
@@ -1013,7 +1007,7 @@ def master_callback(m, master):
master.linkerror = False
say("link %u OK" % (master.linknum+1))
mpstate.status.last_message = time.time()
- master.last_message = mpstate.status.last_message
+ master.last_message = mpstate.status.last_message
if master.link_delayed:
# don't process delayed packets that cause double reporting
@@ -1021,7 +1015,7 @@ def master_callback(m, master):
'GPS_RAW_INT', 'SCALED_PRESSURE', 'GLOBAL_POSITION_INT',
'NAV_CONTROLLER_OUTPUT' ]:
return
-
+
if mtype == 'HEARTBEAT':
if (mpstate.status.target_system != m.get_srcSystem() or
mpstate.status.target_component != m.get_srcComponent()):
@@ -1037,7 +1031,7 @@ def master_callback(m, master):
if master.linkerror:
master.linkerror = False
say("link %u OK" % (master.linknum+1))
-
+
mpstate.status.last_heartbeat = time.time()
master.last_heartbeat = mpstate.status.last_heartbeat
elif mtype == 'STATUSTEXT':
@@ -1046,7 +1040,7 @@ def master_callback(m, master):
mpstate.status.last_apm_msg = m.text
mpstate.status.last_apm_msg_time = time.time()
elif mtype == 'PARAM_VALUE':
- param_id = "%.15s" % m.param_id
+ param_id = "%.15s" % m.param_id
if m.param_index != -1 and m.param_index not in mpstate.mav_param_set:
added_new_parameter = True
mpstate.mav_param_set.add(m.param_index)
@@ -1109,7 +1103,7 @@ def master_callback(m, master):
if mpstate.status.logdir != None:
waytxt = os.path.join(mpstate.status.logdir, 'way.txt')
save_waypoints(waytxt)
- print("Saved waypoints to %s" % waytxt)
+ print("Saved waypoints to %s" % waytxt)
elif mpstate.status.wp_op == "save":
save_waypoints(mpstate.status.wp_save_filename)
mpstate.status.wp_op = None
@@ -1250,7 +1244,7 @@ def process_master(m):
mpstate.console.writeln("MAV error: %s" % msg)
mpstate.status.mav_error += 1
-
+
def process_mavlink(slave):
'''process packets from MAVLink slaves, forwarding to the master'''
@@ -1405,12 +1399,12 @@ def periodic_tasks():
seq = mpstate.status.wploader.count()
print("re-requesting WP %u" % seq)
mpstate.master().waypoint_request_send(seq)
-
+
if battery_period.trigger():
battery_report()
if mpstate.override_period.trigger():
- if (mpstate.status.override != [ 0 ] * 8 or
+ if (mpstate.status.override != [ 0 ] * 8 or
mpstate.status.override != mpstate.status.last_override or
mpstate.status.override_counter > 0):
mpstate.status.last_override = mpstate.status.override[:]
@@ -1443,7 +1437,7 @@ def main_loop():
process_master(master)
periodic_tasks()
-
+
rin = []
for master in mpstate.mav_master:
if master.fd is not None:
@@ -1486,7 +1480,7 @@ def main_loop():
print(msg)
# on an exception, remove it from the select list
mpstate.select_extra.pop(fd)
-
+
def input_loop():
@@ -1500,7 +1494,7 @@ def input_loop():
mpstate.status.exit = True
sys.exit(1)
mpstate.rl.line = line
-
+
def run_script(scriptfile):
'''run a script file'''
@@ -1516,7 +1510,7 @@ def run_script(scriptfile):
mpstate.console.writeln("-> %s" % line)
process_stdin(line)
f.close()
-
+
if __name__ == '__main__':
@@ -1560,7 +1554,7 @@ def run_script(scriptfile):
parser.add_option("--mav09", action='store_true', default=False, help="Use MAVLink protocol 0.9")
parser.add_option("--nowait", action='store_true', default=False, help="don't wait for HEARTBEAT on startup")
parser.add_option("--continue", dest='continue_mode', action='store_true', default=False, help="continue logs")
-
+
(opts, args) = parser.parse_args()
if opts.mav09:
@@ -1601,7 +1595,7 @@ def run_script(scriptfile):
mpstate.status.target_component = opts.TARGET_COMPONENT
mpstate.mav_master = []
-
+
# open master link
for mdev in opts.master:
if mdev.startswith('tcp:'):
@@ -1635,7 +1629,7 @@ def run_script(scriptfile):
print("Loaded waypoints from %s" % waytxt)
fencetxt = os.path.join(mpstate.status.logdir, 'fence.txt')
if os.path.exists(fencetxt):
- mpstate.status.fenceloader.load(fencetxt)
+ mpstate.status.fenceloader.load(fencetxt)
print("Loaded fence from %s" % fencetxt)
# open any mavlink UDP ports
View
10 modules/lib/mp_elevation.py
@@ -58,24 +58,26 @@ def GetElevation(self, latitude, longitude):
lat = opts.lat
lon = opts.lon
- '''Do a few lat/long pairs to demonstrate the caching'''
+ '''Do a few lat/long pairs to demonstrate the caching
+ Note the +0.000001 to the time. On faster PC's, the two time periods
+ may in fact be equal, so we add a little extra time on the end to account for this'''
t0 = time.time()
alt = EleModel.GetElevation(lat, lon)
- t1 = time.time()
+ t1 = time.time()+.000001
print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
lat = opts.lat+0.001
lon = opts.lon+0.001
t0 = time.time()
alt = EleModel.GetElevation(lat, lon)
- t1 = time.time()
+ t1 = time.time()+.000001
print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
lat = opts.lat-0.001
lon = opts.lon-0.001
t0 = time.time()
alt = EleModel.GetElevation(lat, lon)
- t1 = time.time()
+ t1 = time.time()+.000001
print("Altitude at (%.6f, %.6f) is %u m. Pulled at %.1f FPS" % (lat, lon, alt, 1/(t1-t0)))
View
56 modules/lib/mp_slipmap.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
'''
slipmap based on mp_tile
Andrew Tridgell
@@ -19,7 +19,7 @@ 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
@@ -181,7 +181,7 @@ def __init__(self, key, latlon, img, layer=1, rotation=0,
self.rotation = rotation
self.follow = follow
self.trail = trail
-
+
def img(self):
'''return a cv image for the icon'''
SlipThumbnail.img(self)
@@ -312,7 +312,7 @@ def _resize(self):
xsize = int(xsize*1.2)
self.textctrl.SetSize((xsize, ysize))
self.textctrl.SetMinSize((xsize, ysize))
-
+
def draw(self, parent, box):
'''redraw the text'''
@@ -343,7 +343,7 @@ class SlipEvent:
latlon = (lat,lon) of mouse on map
event = wx event
- objkeys = list of SlipObjectSelection selections
+ objkeys = list of SlipObjectSelection selections
'''
def __init__(self, latlon, event, selected):
self.latlon = latlon
@@ -359,7 +359,7 @@ class SlipKeyEvent(SlipEvent):
'''a key event sent to the parent'''
def __init__(self, latlon, event, selected):
SlipEvent.__init__(self, latlon, event, selected)
-
+
class MPSlipMap():
'''
@@ -411,7 +411,7 @@ def child_task(self):
'''child process - this holds all the GUI elements'''
import wx
state = self
-
+
self.mt = mp_tile.MPTile(download=self.download,
service=self.service,
tile_delay=self.tile_delay,
@@ -420,7 +420,7 @@ def child_task(self):
state.layers = {}
state.info = {}
state.need_redraw = True
-
+
self.app = wx.PySimpleApp()
self.app.frame = MPSlipMapFrame(state=self)
self.app.frame.Show()
@@ -464,12 +464,12 @@ def check_events(self):
event = self.get_event()
for callback in self._callbacks:
callback(event)
-
+
def icon(self, filename):
'''load an icon from the data directory'''
path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..',
'data', filename)
- return cv.LoadImage(path)
+ return cv.LoadImage(path)
import wx
@@ -477,7 +477,7 @@ def icon(self, filename):
class MPSlipMapFrame(wx.Frame):
""" The main frame of the viewer
- """
+ """
def __init__(self, state):
wx.Frame.__init__(self, None, wx.ID_ANY, state.title)
self.state = state
@@ -522,7 +522,7 @@ def follow(self, object):
(lat, lon) = object.latlon
state.panel.re_center(state.width/2, state.height/2, lat, lon)
-
+
def on_idle(self, event):
'''prevent the main loop spinning too fast'''
state = self.state
@@ -582,14 +582,14 @@ def on_idle(self, event):
class MPSlipMapPanel(wx.Panel):
""" The image panel
- """
+ """
def __init__(self, parent, state):
wx.Panel.__init__(self, parent)
self.state = state
self.img = None
self.map_img = None
self.redraw_timer = wx.Timer(self)
- self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
+ self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
self.Bind(wx.EVT_SET_FOCUS, self.on_focus)
self.redraw_timer.Start(200)
self.mouse_pos = None
@@ -607,8 +607,15 @@ def __init__(self, parent, state):
# display for lat/lon/elevation
self.position = wx.TextCtrl(self, style=wx.TE_MULTILINE|wx.TE_READONLY)
- textsize = tuple(self.position.GetFullTextExtent('line 1\nline 2\n')[0:2])
- self.position.SetMinSize(textsize)
+ if os.name == 'nt':
+ self.position.SetValue("line 1\nline 2\n")
+ size = self.position.GetBestSize()
+ self.position.SetMinSize(size)
+ self.position.SetValue("")
+ else:
+ textsize = tuple(self.position.GetFullTextExtent('line 1\nline 2\n')[0:2])
+ self.position.SetMinSize(textsize)
+
self.mainSizer.AddSpacer(2)
self.mainSizer.Add(self.position, flag=wx.LEFT | wx.BOTTOM | wx.GROW, border=0)
self.position.Bind(wx.EVT_SET_FOCUS, self.on_focus)
@@ -717,17 +724,16 @@ def update_position(self):
bearing = mp_util.gps_bearing(self.last_click_pos[0], self.last_click_pos[1],
self.click_pos[0], self.click_pos[1])
newtext += ' Distance: %.1fm Bearing %.1f' % (distance, bearing)
- t1 = unicode(newtext, encoding='ascii', errors="replace")
- if t1 != state.oldtext:
+ if newtext != state.oldtext:
self.position.Clear()
self.position.WriteText(newtext)
- state.oldtext = t1
+ state.oldtext = newtext
def pixel_coords(self, latlon):
'''return pixel coordinates in the map image for a (lat,lon)'''
state = self.state
(lat,lon) = latlon
- return state.mt.coord_to_pixel(state.lat, state.lon, state.width, state.ground_width, lat, lon)
+ return state.mt.coord_to_pixel(state.lat, state.lon, state.width, state.ground_width, lat, lon)
def draw_objects(self, objects, bounds, img):
'''draw objects on the image'''
@@ -782,7 +788,7 @@ def redraw_map(self):
self.last_view = self.current_view()
self.SetFocus()
state.need_redraw = False
-
+
def on_redraw_timer(self, event):
'''the redraw timer ensures we show new map tiles as they
are downloaded'''
@@ -820,7 +826,7 @@ def selected_objects(self, pos):
selected.append(SlipObjectSelection(key, distance))
selected.sort(key=lambda c: c.distance)
return selected
-
+
def on_mouse(self, event):
'''handle mouse events'''
@@ -875,7 +881,7 @@ def on_key_down(self, event):
latlon = self.coordinates(self.mouse_pos.x, self.mouse_pos.y)
selected = self.selected_objects(self.mouse_pos)
state.event_queue.put(SlipKeyEvent(latlon, event, selected))
-
+
c = event.GetUniChar()
if c == ord('+') or (c == ord('=') and event.ShiftDown()):
self.change_zoom(1.0/1.2)
@@ -891,7 +897,7 @@ def on_key_down(self, event):
event.Skip()
-
+
if __name__ == "__main__":
import time
@@ -910,7 +916,7 @@ def on_key_down(self, event):
parser.add_option("--flag", default=[], type='str', action='append', help="flag positions")
parser.add_option("--elevation", action='store_true', default=False, help="show elevation information")
(opts, args) = parser.parse_args()
-
+
sm = MPSlipMap(lat=opts.lat,
lon=opts.lon,
download=not opts.offline,
View
42 modules/lib/mp_tile.py
@@ -9,7 +9,7 @@
released under GNU GPL v3 or later
'''
-import math, cv, sys, os, mp_util, httplib2, threading, time, collections, string, hashlib, errno
+import math, cv, sys, os, mp_util, httplib2, threading, time, collections, string, hashlib, errno, tempfile
class TileException(Exception):
'''tile error class'''
@@ -129,7 +129,7 @@ def url(self, service):
(x,y) = self.tile
tile_info = TileServiceInfo(x, y, self.zoom)
return url.substitute(tile_info)
-
+
class TileInfoScaled(TileInfo):
'''information on a tile with scale information and placement'''
@@ -139,15 +139,23 @@ def __init__(self, tile, zoom, scale, src, dst):
(self.srcx, self.srcy) = src
(self.dstx, self.dsty) = dst
-
+
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):
+
if cache_path is None:
- cache_path = os.path.join(os.environ['HOME'], '.tilecache')
+ try:
+ cache_path = os.path.join(os.environ['HOME'], '.tilecache')
+ except Exception:
+ cache_path = os.path.join(tempfile.gettempdir(), 'MAVtilecache')
+
+ 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 = 1
@@ -206,11 +214,11 @@ def downloader(self):
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)))
@@ -228,7 +236,7 @@ def downloader(self):
if self.debug:
print("non-image response %s" % url)
continue
-
+
# see if its a blank/unavailable tile
md5 = hashlib.md5(img).hexdigest()
@@ -240,7 +248,7 @@ def downloader(self):
continue
mp_util.mkdir_p(os.path.dirname(path))
- h = open(path+'.tmp','w')
+ h = open(path+'.tmp','wb')
h.write(img)
h.close()
os.rename(path+'.tmp', path)
@@ -318,8 +326,8 @@ def load_tile(self, tile):
img = self.load_tile_lowres(tile)
if img is None:
img = cv.LoadImage(self._unavailable)
- return img
-
+ return img
+
path = self.tile_to_path(tile)
try:
@@ -337,7 +345,7 @@ def load_tile(self, tile):
img = self.load_tile_lowres(tile)
if img is None:
img = cv.LoadImage(self._unavailable)
- return img
+ return img
try:
self._download_pending[key].refresh_time()
@@ -349,7 +357,7 @@ def load_tile(self, tile):
if img is None:
img = cv.LoadImage(self._loading)
return img
-
+
def scaled_tile(self, tile):
'''return a scaled tile'''
@@ -379,7 +387,7 @@ def coord_to_pixel(self, lat, lon, width, ground_width, lat2, lon2):
if lat is None or lon is None or lat2 is None or lon2 is None:
return (0,0)
-
+
dx = mp_util.gps_distance(lat, lon, lat, lon2)
if lon2 < lon:
dx = -dx
@@ -390,7 +398,7 @@ def coord_to_pixel(self, lat, lon, width, ground_width, lat2, lon2):
dx /= pixel_width
dy /= pixel_width
return (int(dx), int(dy))
-
+
def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None):
'''return a list of TileInfoScaled objects needed for
@@ -448,7 +456,7 @@ def area_to_tile_list(self, lat, lon, width, height, ground_width, zoom=None):
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
+ '''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
@@ -463,7 +471,7 @@ def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordere
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)
@@ -499,7 +507,7 @@ def area_to_image(self, lat, lon, width, height, ground_width, zoom=None, ordere
lat = opts.lat
lon = opts.lon
ground_width = opts.width
-
+
if opts.boundary:
boundary = mp_util.polygon_load(opts.boundary)
bounds = mp_util.polygon_bounds(boundary)
View
10 modules/lib/mp_util.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
'''common mavproxy utility functions'''
import math, os
@@ -32,7 +32,7 @@ def gps_bearing(lat1, lon1, lat2, lon2):
lon1 = radians(lon1)
lon2 = radians(lon2)
dLat = lat2 - lat1
- dLon = lon2 - lon1
+ dLon = lon2 - lon1
y = sin(dLon) * cos(lat2)
x = cos(lat1)*sin(lat2) - sin(lat1)*cos(lat2)*cos(dLon)
bearing = degrees(atan2(y, x))
@@ -48,7 +48,7 @@ def wrap_valid_longitude(lon):
return (((lon + 180.0) % 360.0) - 180.0)
def gps_newpos(lat, lon, bearing, distance):
- '''extrapolate latitude/longitude given a heading and distance
+ '''extrapolate latitude/longitude given a heading and distance
thanks to http://www.movable-type.co.uk/scripts/latlong.html
'''
from math import sin, asin, cos, atan2, radians, degrees
@@ -60,7 +60,7 @@ def gps_newpos(lat, lon, bearing, distance):
lat2 = asin(sin(lat1)*cos(dr) +
cos(lat1)*sin(dr)*cos(brng))
- lon2 = lon1 + atan2(sin(brng)*sin(dr)*cos(lat1),
+ lon2 = lon1 + atan2(sin(brng)*sin(dr)*cos(lat1),
cos(dr)-sin(lat1)*sin(lat2))
return (degrees(lat2), wrap_valid_longitude(degrees(lon2)))
@@ -152,5 +152,5 @@ def degrees_to_dms(degrees):
deg = int(degrees)
min = int((degrees - deg)*60)
sec = ((degrees - deg) - (min/60.0))*60*60
- return '%u°%02u\'%04.1f"' % (deg, abs(min), abs(sec))
+ return u'%u\u00b0%02u\'%04.1f"' % (deg, abs(min), abs(sec))
View
3  modules/lib/mp_widgets.py
@@ -12,9 +12,10 @@ class ImagePanel(wx.Panel):
'''a resizable panel containing an image'''
def __init__(self, parent, img):
wx.Panel.__init__(self, parent, -1, size=(1, 1))
+ self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.set_image(img)
self.Bind(wx.EVT_PAINT, self.on_paint)
-
+
def on_paint(self, event):
'''repaint the image'''
dc = wx.AutoBufferedPaintDC(self)
View
15 modules/lib/srtm.py
@@ -18,6 +18,7 @@
import math
import multiprocessing
import mp_util
+import tempfile
class NoSuchTileError(Exception):
"""Raised when there is no tile for a region."""
@@ -57,9 +58,15 @@ class SRTMDownloader():
"""Automatically download SRTM tiles."""
def __init__(self, server="dds.cr.usgs.gov",
directory="/srtm/version2_1/SRTM3/",
- cachedir=os.path.join(os.environ['HOME'], '.tilecache/SRTM'),
+ cachedir=None,
offline=0):
+ if cachedir is None:
+ try:
+ cachedir = os.path.join(os.environ['HOME'], '.tilecache/SRTM'),
+ except Exception:
+ cachedir = os.path.join(tempfile.gettempdir(), 'MAVProxySRTM'),
+
self.offline = offline
self.first_failure = False
self.server = server
@@ -72,7 +79,7 @@ def __init__(self, server="dds.cr.usgs.gov",
self.filelist = {}
self.filename_regex = re.compile(
r"([NS])(\d{2})([EW])(\d{3})\.hgt\.zip")
- self.filelist_file = self.cachedir + "/filelist_python"
+ self.filelist_file = os.path.join(self.cachedir, "filelist_python")
self.childFileListDownload = None
self.childTileDownload = None
@@ -290,7 +297,7 @@ def getPixelValue(self, x, y):
if value == -32768:
return -1 # -32768 is a special value for areas with no data
return value
-
+
def getAltitudeFromLatLon(self, lat, lon):
"""Get the altitude of a lat lon pair, using the four neighbouring
@@ -346,7 +353,7 @@ def handle_starttag(self, tag, attrs):
for attr in attrs:
if attr[0]=='href':
self.currHref = attr[1]
-
+
def handle_endtag(self, tag):
#print "Encountered the end of a %s tag" % tag
Please sign in to comment.
Something went wrong with that request. Please try again.