numwait-=1 self.gpsdproc=None if retcode is None: AVNLog.error("unable to properly stop gpsd process, leave it running") else: AVNLog.info("gpsd stopped, waiting for reader thread") if reader is not None: try: reader.join(10) AVNLog.info("reader thread successfully stopped") except: AVNLog.error("unable to stop gpsd reader thread within 10s") reader=None #end of loop - device available time.sleep(timeout/2) avnav_handlerList.registerHandler(AVNGpsd) #a reader thread for the gpsd reader class GpsdReader(threading.Thread): def __init__(self, navdata,port,name,infoHandler,errorHandler=None): self.navdata=navdata threading.Thread.__init__(self) self.setDaemon(True) self.setName(name) #the status shows if the gpsd reader still has data self.lasttime=time.time() self.status=True self.port=port self.infoHandler=infoHandler self.errorHandler=errorHandler
else: return {} def registerRequestHandler(self, type, command, handler): if self.handlerMap.get(type) is None: self.handlerMap[type] = {} self.handlerMap[type][command] = handler def getRequestHandler(self, type, command): typeMap = self.handlerMap.get(type) if typeMap is None: return None return typeMap.get(command) avnav_handlerList.registerHandler(AVNHTTPServer) class AVNHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def __init__(self, request, client_address, server): #allow write buffering #see https://lautaportti.wordpress.com/2011/04/01/basehttprequesthandler-wastes-tcp-packets/ self.wbufsize = -1 self.id = None self.getRequestParam = AVNUtil.getHttpRequestParam AVNLog.ld("receiver thread started", client_address) SimpleHTTPServer.SimpleHTTPRequestHandler.__init__( self, request, client_address, server) def log_message(self, format, *args): if self.id is None:
AVNLog.info("successfully connected to %s",info) try: errorReported=False timeout=self.getFloatParam('timeout') if timeout != 0: timeout = timeout *5 else: timeout=None if self.P_WRITE_OUT.fromDict(self.param): clientHandler=threading.Thread( target=self._writer, args=(self.socket,), name="%s-writer"%(self.getName()) ) clientHandler.daemon=True clientHandler.start() self.readSocket(self.socket,'main',self.getSourceName(info),self.getParamValue('filter'),timeout=timeout) self.wait(2) except: AVNLog.info("exception while reading from %s %s",info,traceback.format_exc()) class AVNNmea0183ServiceReader(AVNIpServiceReader): @classmethod def getServiceType(cls): return AVNUtil.NMEA_SERVICE avnav_handlerList.registerHandler(AVNNmea0183ServiceReader)
return True def getName(self): return "AVNChartHandler" def run(self): self.setName("[%s]%s"%(AVNLog.getThreadId(),self.getName())) server=self.findHandlerByName("AVNHttpServer") if server is None: AVNLog.error("unable to find AVNHttpServer") return AVNLog.info("charthandler started") while True: try: osdir=server.getChartBaseDir() if osdir is None or not os.path.isdir(osdir): AVNLog.error("unable to find a valid chart directory %s"%(osdir)) else: for cd in os.listdir(osdir): chartdir=os.path.join(osdir,cd) if not os.path.isdir(chartdir): continue args=["","-i",chartdir] rt=create_overview.main(args) if rt == 0: AVNLog.info("created/updated %s in %s",AVNUtil.NAVXML,chartdir) if rt == 1: AVNLog.error("error creating/updating %s in %s",AVNUtil.NAVXML.navxml,chartdir) except: AVNLog.error("error while trying to update charts %s",traceback.format_exc()) time.sleep(self.getIntParam('period') or 10) avnav_handlerList.registerHandler(AVNChartHandler)
if os.path.exists(fname) and handler is not None: return handler.sendJsFile(fname,self.PREFIX) return super(AVNUserHandler, self).getPathFromUrl(path, handler,requestParam) class AVNImagesHandler(AVNDirectoryHandlerBase): PREFIX = "/user/images" @classmethod def getPrefix(cls): return cls.PREFIX def __init__(self,param): AVNDirectoryHandlerBase.__init__(self, param, "images") self.baseDir = AVNHandlerManager.getDirWithDefault(self.param, 'userDir', os.path.join('user', 'images')) class AVNOverlayHandler(AVNDirectoryHandlerBase): PREFIX = "/overlays" ICONPREFIX=PREFIX+"/icons" @classmethod def getPrefix(cls): return cls.PREFIX def __init__(self,param): AVNDirectoryHandlerBase.__init__(self, param, "overlay") self.baseDir = AVNHandlerManager.getDirWithDefault(self.param, 'overlayDir', "overlays") avnav_handlerList.registerHandler(AVNOverlayHandler) avnav_handlerList.registerHandler(AVNUserHandler) avnav_handlerList.registerHandler(AVNImagesHandler)
id = self.getRequestParam(requestparam, 'id') rt = json.dumps(self.removeNetwork(id)) if command == 'connect': param = {} for k in ['ssid', 'psk']: v = self.getRequestParam(requestparam, k) if v is not None and v != "": param[k] = v key = self.getRequestParam(requestparam, "psk") id = self.getRequestParam(requestparam, 'id') if (key is None or key == "") and (id is None or self.safeInt(id) < 0): param['key_mgmt'] = "NONE" else: param['key_mgmt'] = "WPA-PSK" allowAccess = self.getRequestParam(requestparam, 'allowAccess') if allowAccess is not None and allowAccess == 'true': param['id_str'] = self.PRIVATE_NAME else: param['id_str'] = '' rt = json.dumps(self.connect(param)) if rt is None: raise Exception("unknown command %s" % (command)) end = datetime.datetime.utcnow() AVNLog.debug("wpa request %s lasted %d millis", command, (end - start).total_seconds() * 1000) return rt avnav_handlerList.registerHandler(AVNWpaHandler)
if type == "api": command = AVNUtil.getHttpRequestParam(requestparam, "command", True) if (command == "scheme"): url = AVNUtil.getHttpRequestParam(requestparam, "url", True) scheme = AVNUtil.getHttpRequestParam(requestparam, "newScheme", True) if not url.startswith(self.PATH_PREFIX): raise Exception("invalid url") parr = url[1:].split("/") if len(parr) < 2: raise Exception("invalid url") chartName = urllib.unquote(parr[1]) chartEntry = self.chartlist.get(chartName) if chartEntry is None: raise Exception("chart not found") changed = chartEntry['chart'].changeScheme(scheme) if changed: chartEntry['avnav'] = chartEntry['chart'].getAvnavXml( self.getIntParam('upzoom')) return AVNUtil.getReturnData() return AVNUtil.getReturnData(error="Unknown chart request") def registerExternalProvider(self, name, callback): AVNLog.info("registering external chart provider %s", name) self.externalProviders[name] = callback avnav_handlerList.registerHandler(AVNChartHandler)
for path in glob.glob(os.path.join(dir, '[!_]*.py')): name, ext = os.path.splitext(os.path.basename(path)) try: modules[prefix + name] = imp.load_source(prefix + name, path) AVNLog.info("loaded %s as %s", path, prefix + name) except: AVNLog.error("unable to load %s:%s", path, traceback.format_exc()) return modules def getStatusProperties(self): rt={} return rt def getHandledCommands(self): return {} def handleApiRequest(self,type,command,requestparam,**kwargs): ''' handle the URL based requests :param type: ??? :return: the answer ''' rt={} return rt avnav_handlerList.registerHandler(AVNPluginHandler)
if dist >= self.getFloatParam('mindistance'): gpsdata['distance']=dist AVNLog.ld("write track entry",gpsdata) self.writeLine(f,currentTime,gpsdata) self.track.append((currentTime,lat,lon)) lastLat=lat lastLon=lon except Exception as e: AVNLog.error("exception in Trackwriter: %s",traceback.format_exc()); pass initial=False #TODO: compute more exact sleeptime time.sleep(self.getFloatParam("interval")) def getTrack(self): return self.track #delete a track #@param name: the full filename (without any dir) def deleteTrack(self,name): dir=self.getTrackDir() fname=os.path.join(dir,name) if not os.path.isfile(fname): raise Exception("track %s not found "%name) os.unlink(fname) AVNLog.info("deleting track %s",name) if name.endswith(".gpx"): if self.fname == name[:-4]: AVNLog.info("deleting current track!") self.track=[] avnav_handlerList.registerHandler(AVNTrackWriter)
for match in service_matches: port = match["port"] name = match["name"] host = match["host"] found = False if len(filter) > 0: if host in filter: found = True else: AVNLog.debug( "ignoring device %s as it is not in the list #%s#", host, filterstr) else: found = True if found and self.checkAndAddAddr(host): try: AVNLog.info("found new bluetooth device %s", host) handler = threading.Thread(target=self.readBT, args=(host, port)) handler.daemon = True handler.start() #TDOD: what about join??? except Exception as e: AVNLog.warn("unable to start BT handler %s", traceback.format_exc()) self.removeAddr(host) time.sleep(10) avnav_handlerList.registerHandler(AVNBlueToothReader)
def writeData(self,data): self.feederWrite(data) if (self.getIntParam('minTime')): time.sleep(float(self.getIntParam('minTime'))/1000) #thread run method - just try forever def run(self): self.setName("[%s]%s-%s:%d"%(AVNLog.getThreadId(),self.getName(),self.getStringParam('host'),self.getIntParam('port'))) info="%s:%d"%(self.getStringParam('host'),self.getIntParam('port')) while True: try: self.setInfo('main',"trying udp listen at %s"%(info,),AVNWorker.Status.INACTIVE) sock=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((self.getStringParam('host'), self.getIntParam('port'))) self.setInfo('main',"listening at %s"%(info,),AVNWorker.Status.RUNNING) except: AVNLog.info("exception while trying to listen at %s:%d %s",self.getStringParam('host'),self.getIntParam('port'),traceback.format_exc()) self.setInfo('main',"unable to listen at %s"%(info,),AVNWorker.Status.ERROR) time.sleep(2) continue AVNLog.info("successfully listening at %s:%d",self.getStringParam('host'),self.getIntParam('port')) try: self.readSocket(sock,'main',info="UDP: "+info) except: AVNLog.info("exception while reading data from %s:%d %s",self.getStringParam('host'),self.getIntParam('port'),traceback.format_exc()) avnav_handlerList.registerHandler(AVNUdpReader)
def writeData(self,data): self.feederWrite(data) if (self.getIntParam('minTime')): time.sleep(float(self.getIntParam('minTime'))/1000) #thread run method - just try forever def run(self): self.setName("[%s]%s-%s:%d"%(AVNLog.getThreadId(),self.getName(),self.getStringParam('host'),self.getIntParam('port'))) info="%s:%d"%(self.getStringParam('host'),self.getIntParam('port')) while True: try: self.setInfo('main',"trying to connect to %s"%(info,),AVNWorker.Status.INACTIVE) sock=socket.create_connection((self.getStringParam('host'),self.getIntParam('port')), self.getIntParam('timeout')) self.setInfo('main',"connected to %s"%(info,),AVNWorker.Status.RUNNING) except: AVNLog.info("exception while trying to connect to %s:%d %s",self.getStringParam('host'),self.getIntParam('port'),traceback.format_exc()) self.setInfo('main',"unable to connect to %s"%(info,),AVNWorker.Status.ERROR) time.sleep(2) continue AVNLog.info("successfully connected to %s:%d",self.getStringParam('host'),self.getIntParam('port')) try: self.readSocket(sock,'main') time.sleep(2) except: AVNLog.info("exception while reading from %s:%d %s",self.getStringParam('host'),self.getIntParam('port'),traceback.format_exc()) avnav_handlerList.registerHandler(AVNSocketReader)
if not name in status and not 'all' in status : continue running=self.runningAlarms.get(name) rt[name]={'alarm':name,'running':True if running is not None else False} return rt rt={'status':'ok'} mode="start" command=AVNUtil.getHttpRequestParam(requestparam,"start") if command is None: command = AVNUtil.getHttpRequestParam(requestparam, "stop") mode="stop" if command is None: rt={'info':"missing request parameter start or stop",'status':'error'} return rt rt={'status':'ok'} if mode == "start": if not self.startAlarm(command,True): rt['status']='error' rt['info']=self.info.get(command) return rt if not self.stopAlarm(command): rt['status'] = 'error' rt['info'] = self.info.get(command) return rt avnav_handlerList.registerHandler(AVNAlarmHandler)
if self.getBoolParam('writeMda'): """$AVMDA,,,1.00000,B,,,,,,,,,,,,,,,,""" mda = '$AVMDA,,,%.5f,B,,,,,,,,,,,,,,,,' % ( pressure / 1000.) mda += "*" + NMEAParser.nmeaChecksum(mda) + "\r\n" AVNLog.debug("BMP180:MDA %s", mda) self.writeData(mda) """$AVMTA,19.50,C*2B""" mta = 'AVMTA,%.2f,C' % (temperature) mta += "*" + NMEAParser.nmeaChecksum(mta) + "\r\n" AVNLog.debug("BMP180:MTA %s", mta) self.writeData(mta) if self.getBoolParam('writeXdr'): xdr = '$AVXDR,P,%.5f,B,Barometer' % (pressure / 1000.) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("BMP180:XDR %s", xdr) self.writeData(xdr) xdr = '$AVXDR,C,%.2f,C,TempAir' % (temperature) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("BMP180:XDR %s", xdr) self.writeData(xdr) except: AVNLog.info("exception while reading data from BMP180 %s" ,traceback.format_exc()) wt = self.getFloatParam("interval") if not wt: wt = 5.0 time.sleep(wt) avnav_handlerList.registerHandler(AVNBMP180Reader)
def run(self): self.setName("[%s]%s" % (AVNLog.getThreadId(), self.getName())) self.setInfo('main', "reading sense", AVNWorker.Status.NMEA) sense = SenseHat() while True: try: if self.getBoolParam('writeMda'): """$WIMDA,30.2269,I,1.0236,B,17.7,C,,,43.3,,5.0,C,131.5,T,128.6,M,0.8,N,0.4,M""" mda = '$SHMDA,%.4f,I,%.4f,B,%.1f,C,,C,%.1f,,,C,,T,,M,,N,,M' % ( sense.pressure * 29.5301 / 1000, sense.pressure / 1000, sense.temp, sense.humidity) mda += "*" + NMEAParser.nmeaChecksum(mda) + "\r\n" AVNLog.debug("SenseHat:MDA %s", mda) self.writeData(mda) if self.getBoolParam('writeXdr'): xdr = '$SHXDR,P,%.4f,B,SHPRESSURE,C,%.1f,C,SHTEMP,H,%.1f,P,SHHUMI' % ( sense.pressure / 1000., sense.temp, sense.humidity) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("SenseHat:XDR %s", xdr) self.writeData(xdr) except: AVNLog.info("exception while reading data from SenseHat %s", traceback.format_exc()) wt = self.getFloatParam("interval") if not wt: wt = 5.0 time.sleep(wt) avnav_handlerList.registerHandler(AVNSenseHatReader)
try: listener=socket.socket() listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind((self.getStringParam('address'),self.getIntParam('port'))) listener.listen(1) AVNLog.info("listening at port address %s",unicode(listener.getsockname())) self.setInfo('main', "listening at %s"%(unicode(listener.getsockname()),), AVNWorker.Status.RUNNING) while True: outsock,addr=listener.accept() AVNLog.info("connect from %s",unicode(addr)) allowAccept=self.checkAndAddHandler(addr,outsock) if allowAccept: clientHandler=threading.Thread(target=self.client,args=(outsock, addr)) clientHandler.daemon=True clientHandler.start() else: AVNLog.error("connection from %s not allowed", unicode(addr)) try: outsock.close() except: pass except Exception as e: AVNLog.warn("exception on listener, retrying %s",traceback.format_exc()) try: listener.close() except: pass break avnav_handlerList.registerHandler(AVNSocketWriter)
if s.currentName is not None: toremove = (s.type, s.currentName) if toremove in rt: rt.remove(toremove) if stype is None: return list(rt) else: return list(map(lambda a: a[1], rt)) 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 avnav_handlerList.registerHandler(AVNAvahi)
"""$AVMTA,19.50,C*2B""" mta = 'AVMTA,%.2f,C' % (sense.temp) mta += "*" + NMEAParser.nmeaChecksum(mta) + "\r\n" AVNLog.debug("SenseHat:MTA %s", mta) self.writeData(mta) if self.getBoolParam('writeXdr'): xdr = '$AVXDR,P,%.5f,B,Barometer' % (sense.pressure / 1000.) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("SenseHat:XDR %s", xdr) self.writeData(xdr) xdr = '$AVXDR,C,%.2f,C,TempAir' % (sense.temp) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("SenseHat:XDR %s", xdr) self.writeData(xdr) xdr = '$AVXDR,H,%.2f,P,Humidity' % (sense.humidity) xdr += "*" + NMEAParser.nmeaChecksum(xdr) + "\r\n" AVNLog.debug("SenseHat:XDR %s", xdr) self.writeData(xdr) except: AVNLog.info("exception while reading data from SenseHat %s", traceback.format_exc()) wt = self.getFloatParam("interval") if not wt: wt = 5.0 time.sleep(wt) avnav_handlerList.registerHandler(AVNSenseHatReader)
return rt def __init__(self,param): for p in ('port','name','timeout'): if param.get(p) is None: raise Exception("missing "+p+" parameter for serial writer") self.writeData=None AVNWorker.__init__(self, param) def getName(self): return "SerialWriter "+self.param['name'] #make some checks when we have to start #we cannot do this on init as we potentiall have tp find the feeder... def start(self): if self.getBoolParam('useFeeder'): feedername=self.getStringParam('feederName') feeder=self.findFeeder(feedername) if feeder is None: raise Exception("%s: cannot find a suitable feeder (name %s)",self.getName(),feedername or "") self.writeData=feeder.addNMEA AVNWorker.start(self) #thread run method - just try forever def run(self): self.setName("[%s]%s"%(AVNLog.getThreadId(),self.getName())) writer=SerialWriter(self.param,self.navdata if self.writeData is None else None, self.writeData,self) writer.run() avnav_handlerList.registerHandler(AVNSerialWriter)
raise Exception("unable to find an icon file for %s" % icon) idx = self.findChild(name) if idx < 0 and not doAdd: raise Exception("did not find a user app with this name") for k in list(param.keys()): idx = self.changeChildConfig(self.CHILDNAME, idx, k, param[k], True) self.writeConfigChanges() self.fillList() return AVNUtil.getReturnData() raise Exception("unknown command for %s api request: %s" % (self.type, command)) if type == "list": includeInvalid = AVNUtil.getHttpRequestParam( requestparam, "invalid") return self.handleList( kwargs.get('handler'), includeInvalid is not None and includeInvalid.lower() == 'true') if type == 'delete': name = AVNUtil.getHttpRequestParam(requestparam, "name", True) self.handleDelete(name) return AVNUtil.getReturnData() raise Exception("unable to handle user request %s" % (type)) avnav_handlerList.registerHandler(AVNUserAppHandler)
while True: try: listener=socket.socket() listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listener.bind((self.getStringParam('address'),self.getIntParam('port'))) listener.listen(1) AVNLog.info("listening at port address %s",unicode(listener.getsockname())) self.setInfo('main', "listening at %s"%(unicode(listener.getsockname()),), AVNWorker.Status.RUNNING) while True: outsock,addr=listener.accept() AVNLog.info("connect from %s",unicode(addr)) allowAccept=self.checkAndAddHandler(addr,outsock) if allowAccept: clientHandler=threading.Thread(target=self.client,args=(outsock, addr)) clientHandler.daemon=True clientHandler.start() else: try: outsock.close() except: pass except Exception as e: AVNLog.warn("exception on listener, retrying %s",traceback.format_exc()) try: listener.close() except: pass break avnav_handlerList.registerHandler(AVNSocketWriter)
return {'addresses':self.addresslist} else: return {} def registerRequestHandler(self,type,command,handler): if self.handlerMap.get(type) is None: self.handlerMap[type]={} self.handlerMap[type][command]=handler def getRequestHandler(self,type,command): typeMap=self.handlerMap.get(type) if typeMap is None: return None return typeMap.get(command) avnav_handlerList.registerHandler(AVNHTTPServer) class AVNHTTPHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def __init__(self,request,client_address,server): #allow write buffering #see https://lautaportti.wordpress.com/2011/04/01/basehttprequesthandler-wastes-tcp-packets/ self.wbufsize=-1 self.id=None self.getRequestParam=AVNUtil.getHttpRequestParam AVNLog.ld("receiver thread started",client_address) SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, request, client_address, server) def log_message(self, format, *args): if self.id is None: self.id=AVNLog.getThreadId() if self.id is None:
if path.endswith(".nmea"): AVNLog.info("compressing nmea log %s",path) zfname=path+".gz" try: lf=open(path,"rb") zf=gzip.open(zfname,"wb") while True: buf=lf.read(100000) if buf is None or len(buf) == 0: break zf.write(buf) zf.close() lf.close() os.unlink(path) except: AVNLog.error("exception while compressing log file %s: %s",path,traceback.format_exc()) AVNLog.debug("cleanup, found %d files",len(files)) if len(files) > self.maxfiles: files.sort(key=lambda x: os.path.getmtime(x)) todelete=files[0:len(files)-self.maxfiles] for tdel in todelete: AVNLog.info("cleanup, deleting nmea log %s",tdel) try: os.unlink(tdel) except: AVNLog.error("unable to delete file %s: %s",tdel, traceback.format_exc()) avnav_handlerList.registerHandler(AVNNmeaLogger)
return os.path.join(dir,kwargs.get('server').plainUrlToPath(localPath[1],False)) ''' handle the URL based requests :param type: ??? :return: the answer ''' sub=AVNUtil.getHttpRequestParam(requestparam,'command') if atype == "api": if sub=="list": data=[] for k in list(self.pluginDirs.keys()): dir=self.pluginDirs[k] element={'name':k,'dir':dir} if os.path.exists(os.path.join(dir,"plugin.js")): element['js']= URL_PREFIX + "/" + k + "/plugin.js" if os.path.exists(os.path.join(dir,"plugin.css")): element['css']= URL_PREFIX + "/" + k + "/plugin.css" data.append(element) rt={'status':'OK','data':data} return rt return {'status':'request not found %s'%sub} raise Exception("unable to handle routing request of type %s:%s" % (type, command)) avnav_handlerList.registerHandler(AVNPluginHandler)
cfg = SerialWriter.getConfigParam() rt = cfg.copy() return rt @classmethod def createInstance(cls, cfgparam): if not hasSerial: AVNLog.warn( "serial writers configured but serial module not available, ignore them" ) return None rt = AVNSerialWriter(cfgparam) return rt def __init__(self, param): for p in ('port', 'timeout'): if param.get(p) is None: raise Exception("missing " + p + " parameter for serial writer") AVNWorker.__init__(self, param) #thread run method - just try forever def run(self): self.setName(self.getThreadPrefix()) writer = SerialWriter(self.param, self.writeData, self, self.getSourceName(self.getParamValue('port'))) writer.run() avnav_handlerList.registerHandler(AVNSerialWriter)
continue if not name in status and not 'all' in status : continue running=self.findRunningCommandsByName(name) rt[name]={'command':cmd.get('command'),'repeat':cmd.get('repeat'),'running':",".join([ x.getIdStr() for x in running])} return rt mode="start" command=AVNUtil.getHttpRequestParam(requestparam,"start") if command is None: command = AVNUtil.getHttpRequestParam(requestparam, "stop") mode="stop" if command is None: raise Exception("missing request parameter start or stop") rt={'status':'ok'} if mode == "start": if not self.startCommand(command): rt['status']='error' rt['info']=self.info.get(command) return rt if not self.stopCommand(command): rt['status'] = 'error' rt['info'] = self.info.get(command) return rt avnav_handlerList.registerHandler(AVNCommandHandler)
if not name in status and not 'all' in status: continue running = self.findRunningCommandsByName(name) rt[name] = { 'command': cmd.get('command'), 'repeat': cmd.get('repeat'), 'running': ",".join([x.getIdStr() for x in running]) } return rt mode = "start" command = AVNUtil.getHttpRequestParam(requestparam, "start") if command is None: command = AVNUtil.getHttpRequestParam(requestparam, "stop") mode = "stop" if command is None: raise Exception("missing request parameter start or stop") rt = {'status': 'ok'} if mode == "start": if not self.startCommand(command): rt['status'] = 'error' rt['info'] = str(self.status.get(command)) return rt if not self.stopCommand(command): rt['status'] = 'error' rt['info'] = str(self.status.get(command)) return rt avnav_handlerList.registerHandler(AVNCommandHandler)
if feeder is None: raise Exception("%s: cannot find a suitable feeder (name %s)", self.getName(), feedername or "") self.feeder=feeder AVNWorker.start(self) def run(self): self.setName("[%s]%s"%(AVNLog.getThreadId(),self.getName())) while True: cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.getBoolParam('broadcast'): cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) addr=self.getStringParam('host') port=int(self.getIntParam('port')) filterstr=self.getStringParam('filter') filter=None seq=0 AVNLog.info("Sendto %s:%d" % (unicode(addr),port)) if filterstr != "": filter=filterstr.split(",") while True: seq,data=self.feeder.fetchFromHistory(seq,10) if len(data) > 0: for line in data: if NMEAParser.checkFilter(line, filter): cs.sendto(line,(addr,port)) cs.close() avnav_handlerList.registerHandler(AVNUdpWriter)
#we expect a filename parameter... #TODO: should we check that the filename is the same like the route name? def handleRouteUploadRequest(self, requestparam, rfile, flen): fname = self.getRequestParam(requestparam, "filename") AVNLog.debug("route upload request for %s", fname) if flen > self.MAXROUTESIZE: raise Exception("route is to big, max allowed filesize %d: " % self.MAXROUTESIZE) try: data = rfile.read(flen) parser = gpxparser.GPXParser(data) gpx = parser.parse() if gpx.routes is None or len(gpx.routes) == 0: raise "no routes in " + fname route = gpx.routes[0] if route is None: raise Exception("no route found in file") rinfo = self.routeInfos.get(route.name) if rinfo is not None: raise Exception("route with name " + route.name + " already exists") rinfo = AVNRouteInfo.fromRoute(route, AVNUtil.utcnow()) self.routeInfos[route.name] = rinfo self.saveRoute(route) return except Exception as e: raise Exception("exception parsing " + fname + ": " + e.message) avnav_handlerList.registerHandler(AVNRouter)
fname=self.getRequestParam(requestparam,"filename") AVNLog.debug("route upload request for %s",fname) if flen > self.MAXROUTESIZE: raise Exception("route is to big, max allowed filesize %d: "%self.MAXROUTESIZE) try: data=rfile.read(flen) parser = gpxparser.GPXParser(data) gpx = parser.parse() if gpx.routes is None or len(gpx.routes) == 0: raise "no routes in "+fname route=gpx.routes[0] if route is None: raise Exception("no route found in file") rinfo=self.routeInfos.get(route.name) if rinfo is not None: raise Exception("route with name "+route.name+" already exists") rinfo=AVNRouteInfo.fromRoute(route,AVNUtil.utcnow()) self.routeInfos[route.name]=rinfo self.saveRoute(route) return except Exception as e: raise Exception("exception parsing "+fname+": "+e.message) avnav_handlerList.registerHandler(AVNRouter)
5, #how many seconds we allow time to go back before we reset 'settimecmd': '', #if set, use this to set the system time 'systimediff': 5, #how many seconds do we allow the system time to be away from us 'settimeperiod': 3600 #how often do we set the system time } @classmethod def preventMultiInstance(cls): return True def start(self): pass avnav_handlerList.registerHandler(AVNBaseConfig) def sighandler(signal, frame): for handler in AVNWorker.allHandlers: try: handler.stopChildren() except: pass sys.exit(1) def findHandlerByConfig(list, configName): for h in list: if h.getConfigName() == configName: return h
self.getIntParam('port')) while True: try: self.setInfo('main', "trying to connect to %s" % (info, ), AVNWorker.Status.INACTIVE) sock = socket.create_connection( (self.getStringParam('host'), self.getIntParam('port')), self.getIntParam('timeout')) self.setInfo('main', "connected to %s" % (info, ), AVNWorker.Status.RUNNING) except: AVNLog.info("exception while trying to connect to %s:%d %s", self.getStringParam('host'), self.getIntParam('port'), traceback.format_exc()) self.setInfo('main', "unable to connect to %s" % (info, ), AVNWorker.Status.ERROR) time.sleep(2) continue AVNLog.info("successfully connected to %s:%d", self.getStringParam('host'), self.getIntParam('port')) try: self.readSocket(sock, 'main') time.sleep(2) except: AVNLog.info("exception while reading from %s:%d %s", self.getStringParam('host'), self.getIntParam('port'), traceback.format_exc()) avnav_handlerList.registerHandler(AVNSocketReader)
continue AVNLog.ld("found bluetooth devices",service_matches) filter=[] filterstr=self.getStringParam('devicelist') if not filterstr is None and not filterstr=='': filter=filterstr.split(',') for match in service_matches: port = match["port"] name = match["name"] host = match["host"] found=False if len(filter) > 0: if host in filter: found=True else: AVNLog.debug("ignoring device %s as it is not in the list #%s#",host,filterstr) else: found=True if found and self.checkAndAddAddr(host): try: AVNLog.info("found new bluetooth device %s",host) handler=threading.Thread(target=self.readBT,args=(host,port)) handler.daemon=True handler.start() #TDOD: what about join??? except Exception as e: AVNLog.warn("unable to start BT handler %s",traceback.format_exc()) self.removeAddr(host) time.sleep(10) avnav_handlerList.registerHandler(AVNBlueToothReader)
info = "%s:%d" % (self.getStringParam('host'), self.getIntParam('port')) while True: try: self.setInfo('main', "trying udp listen at %s" % (info, ), AVNWorker.Status.INACTIVE) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind( (self.getStringParam('host'), self.getIntParam('port'))) self.setInfo('main', "listening at %s" % (info, ), AVNWorker.Status.RUNNING) except: AVNLog.info("exception while trying to listen at %s:%d %s", self.getStringParam('host'), self.getIntParam('port'), traceback.format_exc()) self.setInfo('main', "unable to listen at %s" % (info, ), AVNWorker.Status.ERROR) time.sleep(2) continue AVNLog.info("successfully listening at %s:%d", self.getStringParam('host'), self.getIntParam('port')) try: self.readSocket(sock, 'main', info="UDP: " + info) except: AVNLog.info("exception while reading data from %s:%d %s", self.getStringParam('host'), self.getIntParam('port'), traceback.format_exc()) avnav_handlerList.registerHandler(AVNUdpReader)
return rt def __init__(self,param): for p in ('port','name','timeout'): if param.get(p) is None: raise Exception("missing "+p+" parameter for serial reader") self.writeData=None AVNWorker.__init__(self, param) def getName(self): return "SerialReader "+self.param['name'] #make some checks when we have to start #we cannot do this on init as we potentiall have tp find the feeder... def start(self): if self.getBoolParam('useFeeder'): feedername=self.getStringParam('feederName') feeder=self.findFeeder(feedername) if feeder is None: raise Exception("%s: cannot find a suitable feeder (name %s)",self.getName(),feedername or "") self.writeData=feeder.addNMEA AVNWorker.start(self) #thread run method - just try forever def run(self): self.setName("[%s]%s"%(AVNLog.getThreadId(),self.getName())) reader=SerialReader(self.param, self.navdata if self.writeData is None else None, self.writeData,self) reader.run() avnav_handlerList.registerHandler(AVNSerialReader)
'expiryTime': 30, 'aisExpiryTime': 1200, 'ownMMSI':'', #if set - do not store AIS messages with this MMSI 'debugToLog': 'false', 'maxtimeback':5, #how many seconds we allow time to go back before we reset 'settimecmd': '', #if set, use this to set the system time 'systimediff':5, #how many seconds do we allow the system time to be away from us 'settimeperiod': 3600 #how often do we set the system time } @classmethod def preventMultiInstance(cls): return True def start(self): pass avnav_handlerList.registerHandler(AVNBaseConfig) def sighandler(signal,frame): for handler in AVNWorker.allHandlers: try: handler.stopChildren() except: pass sys.exit(1) def findHandlerByConfig(list,configName): for h in list: if h.getConfigName()==configName: return h return None
AVNLog.info("deleting import file %s",fullname) try: os.unlink(fullname) except: AVNLog.error("error deleting file %s:%s",fullname,traceback.format_exc()) def runConverter(self,name,args): logdir=AVNLog.getLogDir() rt=None try: logfile=None if logdir is not None: logfilename=os.path.join(logdir,"convert-"+name+".log") try: logfile=open(logfilename,"w") except: AVNLog.error("unable to open logile %s: %s",logfilename,traceback.format_exc()) if logfile is not None: AVNLog.info("starting converter for %s with args %s, logfile=%s",name," ".join(args),logfilename) rt=subprocess.Popen(args,stdin=None,stdout=logfile,stderr=subprocess.STDOUT) else: AVNLog.info("starting converter for %s with args %s",name," ".join(args)) rt=subprocess.Popen(args) return rt except: AVNLog.error("unable to start converter for %s:%s",name,traceback.format_exc()) avnav_handlerList.registerHandler(AVNImporter)
self.track.append((currentTime, lat, lon)) lastLat = lat lastLon = lon except Exception as e: AVNLog.error("exception in Trackwriter: %s", traceback.format_exc()) pass initial = False #TODO: compute more exact sleeptime time.sleep(self.getFloatParam("interval")) def getTrack(self): return self.track #delete a track #@param name: the full filename (without any dir) def deleteTrack(self, name): dir = self.getTrackDir() fname = os.path.join(dir, name) if not os.path.isfile(fname): raise Exception("track %s not found " % name) os.unlink(fname) AVNLog.info("deleting track %s", name) if name.endswith(".gpx"): if self.fname == name[:-4]: AVNLog.info("deleting current track!") self.track = [] avnav_handlerList.registerHandler(AVNTrackWriter)
id=self.getRequestParam(requestparam,'id') rt=json.dumps(self.disableNetwork(id)) if command == 'remove': id=self.getRequestParam(requestparam,'id') rt=json.dumps(self.removeNetwork(id)) if command == 'connect': param={} for k in ['ssid','psk']: v=self.getRequestParam(requestparam,k) if v is not None and v != "": param[k]=v key=self.getRequestParam(requestparam,"psk") id = self.getRequestParam(requestparam, 'id') if ( key is None or key == "" ) and id is None: param['key_mgmt'] = "NONE" else: param['key_mgmt'] = "WPA-PSK" allowAccess=self.getRequestParam(requestparam,'allowAccess') if allowAccess is not None and allowAccess == 'true': param['id_str']=self.PRIVATE_NAME else: param['id_str'] = '' rt=json.dumps(self.connect(param)) if rt is None: raise Exception("unknown command %s"%(command)) end=datetime.datetime.utcnow() AVNLog.debug("wpa request %s lasted %d millis",command,(end-start).total_seconds()*1000) return rt avnav_handlerList.registerHandler(AVNWpaHandler)
usbid = cfg.get('usbid') if usbid is not None and not usbid in currentDevices: currentDevices[usbid] = None self.checkDevices(currentDevices) if init: monitorThread = threading.Thread( target=self.monitorDevices, args=(context, ), name="%s-monitor" % (self.getName())) monitorThread.daemon = True monitorThread.start() init = False except Exception as e: AVNLog.debug( "exception when querying usb serial devices %s, retrying after 10s", traceback.format_exc()) context = None time.sleep(10) def _stopHandlers(self): usbids = [] + list(self.addrmap.keys()) for id in usbids: self.stopHandler(id) def stop(self): super().stop() self._stopHandlers() avnav_handlerList.registerHandler(AVNUsbSerialReader)
AVNLog.info("compressing nmea log %s", path) zfname = path + ".gz" try: lf = open(path, "rb") zf = gzip.open(zfname, "wb") while True: buf = lf.read(100000) if buf is None or len(buf) == 0: break zf.write(buf) zf.close() lf.close() os.unlink(path) except: AVNLog.error("exception while compressing log file %s: %s", path, traceback.format_exc()) AVNLog.debug("cleanup, found %d files", len(files)) if len(files) > self.maxfiles: files.sort(key=lambda x: os.path.getmtime(x)) todelete = files[0:len(files) - self.maxfiles] for tdel in todelete: AVNLog.info("cleanup, deleting nmea log %s", tdel) try: os.unlink(tdel) except: AVNLog.error("unable to delete file %s: %s", tdel, traceback.format_exc()) avnav_handlerList.registerHandler(AVNNmeaLogger)
AVNLog.info("gpsd stopped, waiting for reader thread") if reader is not None: try: reader.join(10) AVNLog.info( "reader thread successfully stopped") except: AVNLog.error( "unable to stop gpsd reader thread within 10s" ) reader = None #end of loop - device available time.sleep(timeout / 2) avnav_handlerList.registerHandler(AVNGpsd) #a reader thread for the gpsd reader class GpsdReader(threading.Thread): def __init__(self, navdata, port, name, infoHandler, errorHandler=None): self.navdata = navdata threading.Thread.__init__(self) self.setDaemon(True) self.setName(name) #the status shows if the gpsd reader still has data self.lasttime = time.time() self.status = True self.port = port self.infoHandler = infoHandler self.errorHandler = errorHandler
try: temperature, pressure = readBmp180(addr) if self.getBoolParam('writeMda'): """$AVMDA,,,1.00000,B,,,,,,,,,,,,,,,,""" mda = '$AVMDA,,,%.5f,B,,,,,,,,,,,,,,,,' % (pressure / 1000.) AVNLog.debug("BMP180:MDA %s", mda) self.writeData(mda, source, addCheckSum=True) """$AVMTA,19.50,C*2B""" mta = 'AVMTA,%.2f,C' % (temperature) AVNLog.debug("BMP180:MTA %s", mta) self.writeData(mta, source, addCheckSum=True) if self.getBoolParam('writeXdr'): xdr = '$AVXDR,P,%.5f,B,Barometer' % (pressure / 1000.) AVNLog.debug("BMP180:XDR %s", xdr) self.writeData(xdr, source, addCheckSum=True) xdr = '$AVXDR,C,%.2f,C,TempAir' % (temperature) AVNLog.debug("BMP180:XDR %s", xdr) self.writeData(xdr, source, addCheckSum=True) except: AVNLog.info("exception while reading data from BMP180 %s", traceback.format_exc()) wt = self.getFloatParam("interval") if not wt: wt = 5.0 time.sleep(wt) avnav_handlerList.registerHandler(AVNBMP180Reader)
'alarm': name, 'running': True if running is not None else False, 'repeat': config.get('repeat') } return {"status": "OK", "data": rt} rt = {'status': 'ok'} mode = "start" command = AVNUtil.getHttpRequestParam(requestparam, "start") if command is None: command = AVNUtil.getHttpRequestParam(requestparam, "stop") mode = "stop" if command is None: rt = { 'info': "missing request parameter start or stop", 'status': 'error' } return rt rt = {'status': 'ok'} if mode == "start": if not self.startAlarm(command, True): rt['status'] = 'error' rt['info'] = self.info.get(command) return rt if not self.stopAlarm(command): rt['status'] = 'error' rt['info'] = self.info.get(command) return rt avnav_handlerList.registerHandler(AVNAlarmHandler)
fname = info.filename if fname is None: raise Exception("no layout file") len = os.path.getsize(fname) stream = open(fname, "rb") rt = { 'size': len, 'mimetype': 'application/json', 'stream': stream } if noAttach is not None: rt['noattach'] = True return rt if type == 'delete': name = AVNUtil.getHttpRequestParam(requestparam, 'name') if name is None: raise Exception("missing parameter name") info = self.layouts.get(name) if info is None: raise Exception("layout %s not found" % name) if not info.canDelete: raise Exception("cannot delete this layout") fname = info.filename if fname is None: raise Exception("no layout file") os.unlink(fname) self.updateAllLayouts() avnav_handlerList.registerHandler(AVNLayoutHandler)
(self.getThreadPrefix(), self.param['host'], self.param['port'])) while True: cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) cs.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if self.getBoolParam('broadcast'): cs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) addr = self.getStringParam('host') port = int(self.getIntParam('port')) filterstr = self.getStringParam('filter') filter = None seq = 0 AVNLog.info("Sendto %s:%d" % (unicode(addr), port)) if filterstr != "": filter = filterstr.split(",") while True: seq, data = self.feeder.fetchFromHistory(seq, 10, nmeafilter=filter, includeSource=True) if len(data) > 0: for line in data: if line.source in self.blackList: AVNLog.debug("ignore line %s:%s due to blacklist", line.source, line.data) else: cs.sendto(line.data, (addr, port)) cs.close() avnav_handlerList.registerHandler(AVNUdpWriter)