def handleNavRequest(self, path, requestParam): #check if we have something behind the navurl #treat this as a filename and set it ion the request parameter fname = path[(len(self.server.navurl) + 1):] if fname is not None and fname != "": fname = fname.split('?', 1)[0] if fname != "": if requestParam.get('filename') is None: requestParam['filename'] = [fname.encode('utf-8')] requestType = requestParam.get('request') if requestType is None: requestType = 'gps' else: requestType = requestType[0] AVNLog.ld('navrequest', requestParam) try: rtj = None if requestType == 'gps' or requestType == 'self': rtj = self.handleGpsRequest(requestParam) elif requestType == 'nmeaStatus': rtj = self.handleNmeaStatus(requestParam) elif requestType == 'ais': rtj = self.handleAISRequest(requestParam) elif requestType == 'status': rtj = self.handleStatusRequest(requestParam) elif requestType == 'debuglevel' or requestType == 'loglevel': rtj = self.handleDebugLevelRequest(requestParam) elif requestType == 'listdir' or requestType == 'list': rtj = self.handleListDir(requestParam) elif requestType == 'download': #download requests are special # the dow not return json... self.handleDownloadRequest(requestParam) return elif requestType == 'upload': try: rtj = self.handleUploadRequest(requestParam) except Exception as e: AVNLog.error("upload error: %s", unicode(e)) rtj = json.dumps({'status': unicode(e)}) elif requestType == 'delete': rtj = self.handleDeleteRequest(requestParam) elif requestType == 'capabilities': rtj = self.handleCapabilityRequest(requestParam) elif requestType == 'api': #new handling for dedicated requests for some handler type = self.getRequestParam(requestParam, 'type') rtj = self.handleSpecificRequest(requestParam, type) else: #legacy: have the api type as requestType rtj = self.handleSpecificRequest(requestParam, requestType) self.sendNavResponse(rtj, requestParam) except Exception as e: text = unicode(e) rtj = json.dumps( AVNUtil.getReturnData(error=text, stack=traceback.format_exc())) self.sendNavResponse(rtj, requestParam) return
def createOverview(self): zoomlevels = [] zoomLevelBoundings = {} connection = sqlite3.connect(self.filename) if connection is None: raise Exception("unable to open mbtiles file %s" % (self.filename)) AVNLog.info("opening mbtiles file %s", self.filename) cu = None hasAvnavScheme = False try: cu = connection.cursor() for sr in cu.execute("select value from metadata where name=?", ["avnav_scheme"]): v = sr[0] if v is not None: v = v.lower() if v in ['tms', 'xyz']: AVNLog.info("setting scheme for %s to %s", self.filename, v) self.schemeTMS = False if v == "xyz" else True self.schemeInconsistent = False hasAvnavScheme = True #check if there is a schema entry for sr in cu.execute("select value from metadata where name=?", ["scheme"]): v = sr[0] if v is not None: v = v.lower() self.originalScheme = v if not hasAvnavScheme: self.schemeInconsistent = True for zl in cu.execute("select distinct zoom_level from tiles;"): zoomlevels.append(zl[0]) for zl in zoomlevels: el = {} for rowmima in cu.execute( "select min(tile_row),max(tile_row) from tiles where zoom_level=?", [zl]): # names must match getGemfInfo in create_overview if self.schemeTMS: el['ymin'] = self.rowToY(zl, rowmima[1]) el['ymax'] = self.rowToY(zl, rowmima[0]) else: el['ymin'] = self.rowToY(zl, rowmima[0]) el['ymax'] = self.rowToY(zl, rowmima[1]) for colmima in cu.execute( "select min(tile_column),max(tile_column) from tiles where zoom_level=?", [zl]): el['xmin'] = self.colToX(zl, colmima[0]) el['xmax'] = self.colToX(zl, colmima[1]) zoomLevelBoundings[zl] = el except Exception as e: AVNLog.error("error reading base info from %s:%s", self.filename, str(e)) self.zoomlevels = zoomlevels self.zoomLevelBoundings = zoomLevelBoundings if cu is not None: cu.close() connection.close() self.changeCount = AVNUtil.utcnow()
def _stopLoop(self): if self.loop is not None: try: self.loop.quit() except Exception as x: AVNLog.error("unable to stop dbus event loop %s" % str(x)) self.loop = None
def _newService(self, interface, protocol, name, stype, domain, flags): AVNLog.info("detected new service %s.%s at %i.%i", stype, name, interface, protocol) try: self.foundServices.add( FoundService(stype, name, interface, protocol)) except Exception as e: AVNLog.error("unable to add service: %s", e)
def _runInternal(self): self.usedResources=[] AVNLog.info("run started") try: self.run() self.setInfo('main','handler stopped',WorkerStatus.INACTIVE) except Exception as e: self.setInfo('main','handler stopped with %s'%str(e),WorkerStatus.ERROR) AVNLog.error("handler run stopped with exception %s",traceback.format_exc()) self.usedResources=[] self.currentThread=None
def _deregister(self, description: ServiceDescription) -> object: if description.group is None: description.reset() return try: AVNLog.info("deregister") description.reset() description.group.Reset() description.group.Free() description.group = None self.deleteInfo(description.getKey()) except Exception as e: AVNLog.error("unable to deregister: %s", str(e)) self.setInfo(description.getKey(), "error in deregister %s" % str(e), WorkerStatus.ERROR)
def getAvnavXml(self,upzoom=2): if not self.isOpen: return None try: data = self.getSources() options = {} options['upzoom'] = upzoom rt = create_overview.getGemfInfo(data, options) AVNLog.info("created GEMF overview for %s", self.filename) AVNLog.debug("overview for %s:%s", self.filename, rt) return rt except: AVNLog.error("error while trying to get the overview data for %s %s", self.filename, traceback.format_exc()) return None
def fillInfo(self, baseDir): routeFile = os.path.join(baseDir, self.name) try: if os.path.isfile(routeFile): content = "" with open(routeFile, "r", encoding='utf-8') as f: content = f.read() parser = gpxparser.GPXParser(content) gpx = parser.parse() if gpx.routes is None or len(gpx.routes) == 0: AVNLog.error("no routes in %s", routeFile) else: route = gpx.routes[0] self.numpoints = len(route.points) self.length = route.length() / AVNUtil.NM except Exception as e: AVNLog.error("error when parsing route %s: %s", routeFile, str(e))
def resolveService(self, type, name): ''' resove a service (IPv4) @param type: the service type @param name: the service name @return: a tuple (hostname,ip,port) if found or None otherwise ''' if self.server is None: return None try: res = self.server.ResolveService(self.IF_UNSPEC, self.PROTO_INET, name, type, "local", self.PROTO_INET, 0) return (str(res[5]), str(res[7]), int(res[8])) except Exception as e: AVNLog.error("unable to resolve service %s.%s: %s", type, name, str(e)) return None
def onPreRun(self): self.currentLegFileName = os.path.join(self.baseDir, self.currentLegName) if os.path.exists(self.currentLegFileName): f = None try: f = open(self.currentLegFileName, "r", encoding='utf-8') strleg = f.read(self.MAXROUTESIZE + 1000) self.currentLeg = AVNRoutingLeg(json.loads(strleg)) if self.currentLeg.getTo() is not None: distance = AVNUtil.distanceM( self.wpToLatLon(self.currentLeg.getFrom()), self.wpToLatLon(self.currentLeg.getTo())) AVNLog.info( "read current leg, route=%s, from=%s, to=%s, length=%fNM" % (self.currentLeg.getRouteName(), str(self.currentLeg.getFrom()), str(self.currentLeg.getTo()), distance / AVNUtil.NM)) else: AVNLog.info("read current leg, route=%s, from=%s, to=%s" % ( self.currentLeg.getRouteName(), str(self.currentLeg.getFrom()), "NONE", )) self.setCurrentLeg(self.currentLeg) except: AVNLog.error("error parsing current leg %s: %s" % (self.currentLegFileName, traceback.format_exc())) if f is not None: f.close() else: AVNLog.info("no current leg %s found" % (self.currentLegFileName, )) self.setCurrentLeg(AVNRoutingLeg({})) AVNLog.info("router main loop started")
def _publish(self, description: ServiceDescription) -> object: if description.group is not None: try: description.group.Reset() except: pass try: description.group.Free() except: pass try: description.group = None if description.oldKey is not None: self.deleteInfo(description.oldKey) else: self.deleteInfo(description.getKey()) except: pass if description.name is None or description.name == '': return False description.group = dbus.Interface( dbus.SystemBus().get_object(self.DBUS_NAME, self.server.EntryGroupNew()), self.DBUS_INTERFACE_ENTRY_GROUP) timeout = self.getFloatParam('timeout') retries = self.getIntParam('maxRetries') num = 0 retry = True self.setInfo(description.getKey(), "trying to register", WorkerStatus.STARTED) while retry: retry = False AVNLog.info("trying to register %s for %s", description.currentName, str(self.port)) try: description.group.AddService(self.IF_UNSPEC, self.PROTO_INET, dbus.UInt32(0), description.currentName, description.type, self.server.GetDomainName(), self.server.GetHostNameFqdn(), description.port, '') description.group.Commit() except Exception as e: AVNLog.warn("unable to register avahi service %s, error: %s", description.currentName, str(e)) if description.retry(retries): retry = True continue waitTime = timeout * 10 state = description.group.GetState() while state in [ self.ENTRY_GROUP_REGISTERING, self.ENTRY_GROUP_UNCOMMITED ] and waitTime > 0: waitTime -= 1 time.sleep(0.1) state = description.group.GetState() if state == self.ENTRY_GROUP_COLLISION: if not description.retry(retries): AVNLog.error("max retries reached for %s", description.name) else: retry = True continue if state != self.ENTRY_GROUP_ESTABLISHED: try: description.group.Reset() except: pass description.group = None self.setInfo( description.getKey(), "unable to register service, state=%s" % str(state), WorkerStatus.ERROR) return False description.isRegistered = True self.setInfo(description.getKey(), "registered", WorkerStatus.NMEA) self.hostname = self.server.GetHostNameFqdn() return True self.setInfo(description.getKey(), "unable to register service after retries", WorkerStatus.ERROR) return False