Esempio n. 1
0
 def log_message(self, format, *args):
     if self.id is None:
         self.id = AVNLog.getThreadId()
         if self.id is None:
             self.id = "?"
         threading.current_thread().setName("[%s]HTTPHandler" % (self.id))
     AVNLog.debug(format, *args)
Esempio n. 2
0
    def handleDownloadRequest(self, requestParam):
        type = self.getRequestParam(requestParam, "type")
        try:
            handler = self.server.getRequestHandler('download', type)
            if handler is not None:
                AVNLog.debug("found handler %s to handle download %s" %
                             (handler.getConfigName(), type))
                dl = handler.handleApiRequest('download',
                                              type,
                                              requestParam,
                                              handler=self)
                if dl is None:
                    raise Exception("unable to download %s", type)
                if dl.get('mimetype') is None:
                    raise Exception("no mimetype")
                if dl.get('size') is None:
                    raise Exception("no size")
                if dl.get("stream") is None:
                    raise Exception("missing stream")
                self.send_response(200)
                fname = self.getRequestParam(requestParam, "filename")
                if fname is not None and fname != "" and self.getRequestParam(
                        requestParam, 'noattach') is None:
                    self.send_header("Content-Disposition", "attachment")
                self.send_header("Content-type", dl['mimetype'])
                self.send_header("Content-Length", dl['size'])
                self.send_header("Last-Modified", self.date_time_string())
                self.end_headers()
                try:
                    self.writeStream(dl['size'], dl['stream'])
                except:
                    try:
                        dl['stream'].close()
                    except:
                        pass
                return

        except Exception as e:
            if self.getRequestParam(requestParam, 'noattach') is None:
                #send some empty data
                data = StringIO.StringIO("error: %s" % e.message)
                data.seek(0)
                self.send_response(200)
                self.send_header("Content-type", "application/octet-stream")
                try:
                    self.copyfile(data, self.wfile)
                finally:
                    data.close()
            else:
                self.send_error(404, traceback.format_exc(1))
            return
        self.send_error(404, "invalid download request %s" % type)
Esempio n. 3
0
 def periodicRun(self):
     hasLeg = False
     hasRMB = False
     if self.currentLeg and self.currentLeg.isActive():
         hasLeg = True
         if self.currentLeg.getAnchorDistance() is not None:
             routerInfo = "Anchor watch, from %s, (anchor radius %sm)" % (
                 str(self.currentLeg.getFrom()),
                 str(self.currentLeg.getAnchorDistance()))
         else:
             routerInfo = "from %s, to %s, route=%s, activeWp=%s, approach=%s (approach radius %sm)" % (
                 str(self.currentLeg.getFrom()), str(
                     self.currentLeg.getTo()),
                 self.currentLeg.getRouteName(),
                 self.currentLeg.getCurrentTarget(),
                 self.currentLeg.isApproach(),
                 self.currentLeg.getApproachDistance())
         AVNLog.debug(routerInfo)
         self.setInfo("leg", routerInfo, WorkerStatus.RUNNING)
     try:
         if self.currentLeg is not None and self.currentLeg.getAnchorDistance(
         ) is not None:
             self.computeAnchor()
         else:
             self.startStopAlarm(False, self.ALARMS.anchor)
             self.startStopAlarm(False, self.ALARMS.gps)
             computeRMB = self.getBoolParam("computeRMB")
             computeAPB = self.getBoolParam("computeAPB")
             if computeRMB or computeAPB:
                 hasRMB = self.computeRMB(computeRMB, computeAPB)
     except Exception as e:
         AVNLog.warn("exception in computeRMB %s, retrying",
                     traceback.format_exc())
     try:
         self.computeApproach()
     except:
         AVNLog.warn("exception in computeApproach %s, retrying",
                     traceback.format_exc())
     if (not hasLeg):
         self.setInfo("leg", "no leg", WorkerStatus.INACTIVE)
     if (not hasRMB):
         self.setInfo("autopilot", "no autopilot data",
                      WorkerStatus.INACTIVE)
     try:
         lat = self.navdata.getSingleValue(AVNStore.BASE_KEY_GPS + ".lat")
         lon = self.navdata.getSingleValue(AVNStore.BASE_KEY_GPS + ".lon")
         if lat is not None and lon is not None:
             self.startStopAlarm(False, self.ALARMS.gps)
     except:
         pass
     AVNLog.debug("router main loop")
Esempio n. 4
0
 def getTileData(self, tile, source):
     if not self.isOpen:
         raise Exception("not open")
     request = QueueEntry(tile)
     self.cond.acquire()
     try:
         self.requestQueue.append(request)
         self.cond.notify_all()
     except:
         pass
     self.cond.release()
     AVNLog.debug("waiting for tile")
     data = request.waitAndGet()
     AVNLog.debug("tile received")
     return data
Esempio n. 5
0
 def handleDeleteRequest(self, requestParam):
     type = self.getRequestParam(requestParam, "type")
     if type is None:
         raise Exception("no type for delete")
     handler = self.server.getRequestHandler('delete', type)
     rt = {'status': 'OK'}
     if handler is not None:
         AVNLog.debug("found handler for delete request %s:%s" %
                      (type, handler.getConfigName()))
         handler.handleApiRequest('delete',
                                  type,
                                  requestParam,
                                  handler=self)
         return json.dumps(rt)
     raise Exception("invalid type %s" % type)
Esempio n. 6
0
  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
Esempio n. 7
0
 def handleGemfRequest(self, path, query):
     try:
         path = path.replace("/gemf/", "", 1)
         parr = path.split("/")
         gemfname = parr[0] + ".gemf"
         for g in self.server.gemflist.values():
             if g['name'] == gemfname:
                 AVNLog.debug("gemf file %s, request %s, lend=%d", gemfname,
                              path, len(parr))
                 #found file
                 #basically we can today handle 2 types of requests:
                 #get the overview /gemf/<name>/avnav.xml
                 #get a tile /gemf/<name>/<srcname>/z/x/y.png
                 if parr[1] == self.server.navxml:
                     AVNLog.debug("avnav request for GEMF %s", gemfname)
                     data = g['avnav']
                     self.send_response(200)
                     self.send_header("Content-type", "text/xml")
                     self.send_header("Content-Length", len(data))
                     self.send_header("Last-Modified",
                                      self.date_time_string())
                     self.end_headers()
                     self.wfile.write(data)
                     return None
                 if len(parr) != 5:
                     raise Exception("invalid request to GEMF file %s: %s" %
                                     (gemfname, path))
                 data = g['gemf'].getTileData((int(parr[2]), int(
                     parr[3]), int(parr[4].replace(".png", ""))), parr[1])
                 if data is None:
                     empty = self.server.emptytile
                     if empty is not None:
                         data = empty
                 if data is None:
                     self.send_error(404, "File %s not found" % (path))
                     return None
                 self.send_response(200)
                 self.send_header("Content-type", "image/png")
                 self.send_header("Content-Length", len(data))
                 self.send_header("Last-Modified", self.date_time_string())
                 self.end_headers()
                 self.wfile.write(data)
                 return None
         raise Exception("gemf file %s not found" % (gemfname))
     except:
         self.send_error(500, "Error: %s" % (traceback.format_exc()))
         return
Esempio n. 8
0
    def handleListDir(self, requestParam):
        type = self.getRequestParam(requestParam, "type")
        if type is None:
            raise Exception("no type for listdir")
        handler = self.server.getRequestHandler('list', type)
        if handler is not None:
            AVNLog.debug("found handler for list request %s:%s" %
                         (type, handler.getConfigName()))
            rt = handler.handleApiRequest('list',
                                          type,
                                          requestParam,
                                          handler=self)
            if rt is None:
                raise Exception("invalid list response")
            return json.dumps(rt)

        raise Exception("invalid type %s" % type)
Esempio n. 9
0
 def computeAnchor(self):
     curGps = self.navdata.getDataByPrefix(AVNStore.BASE_KEY_GPS, 1)
     lat = curGps.get('lat')
     lon = curGps.get('lon')
     if lat is None or lon is None:
         self.startStopAlarm(False, self.ALARMS.anchor)
         if self.activatedAlarms.get(self.ALARMS.gps) is None:
             self.startStopAlarm(True, self.ALARMS.gps)
         return
     self.startStopAlarm(False, self.ALARMS.gps)
     anchorDistance = AVNUtil.distanceM(
         (lat, lon), self.wpToLatLon(self.currentLeg.getFrom()))
     AVNLog.debug("Anchor distance %d, allowed %d", anchorDistance,
                  self.currentLeg.getAnchorDistance())
     if anchorDistance > self.currentLeg.getAnchorDistance():
         self.startStopAlarm(True, self.ALARMS.anchor)
     return
Esempio n. 10
0
 def handleUploadRequest(self, requestParam):
     rlen = None
     try:
         rlen = self.headers.get("Content-Length")
         if rlen is None:
             raise Exception("Content-Length not set in upload request")
         self.connection.settimeout(30)
         type = self.getRequestParam(requestParam, "type")
         handler = self.server.getRequestHandler("upload", type)
         if handler is not None:
             AVNLog.debug("found handler for upload request %s:%s" %
                          (type, handler.getConfigName()))
             rt = handler.handleApiRequest("upload",
                                           type,
                                           requestParam,
                                           rfile=self.rfile,
                                           flen=rlen,
                                           handler=self)
             return json.dumps(rt)
         else:
             raise Exception("invalid request %s", type)
     except Exception as e:
         return json.dumps({'status': unicode(e)})
Esempio n. 11
0
 def handleAISRequest(self, requestParam):
     rt = self.server.navdata.getAisData()
     lat = None
     lon = None
     dist = None
     try:
         lat = float(self.getRequestParam(requestParam, 'lat'))
         lon = float(self.getRequestParam(requestParam, 'lon'))
         dist = float(self.getRequestParam(requestParam,
                                           'distance'))  #distance in NM
     except:
         pass
     frt = []
     if not lat is None and not lon is None and not dist is None:
         dest = (lat, lon)
         AVNLog.debug("limiting AIS to lat=%f,lon=%f,dist=%f", lat, lon,
                      dist)
         for entry in rt:
             try:
                 fentry = AVNUtil.convertAIS(entry)
                 mdist = AVNUtil.distance(
                     (fentry.get('lat'), fentry.get('lon')), dest)
                 if mdist <= dist:
                     fentry[
                         'distance'] = mdist * AVNUtil.NM  #have this in m
                     frt.append(fentry)
                 else:
                     AVNLog.debug("filtering out %s due to distance %f",
                                  str(fentry['mmsi']), mdist)
             except:
                 AVNLog.debug("unable to convert ais data: %s",
                              traceback.format_exc())
     else:
         for entry in rt:
             try:
                 frt.append(AVNUtil.convertAIS(entry))
             except Exception as e:
                 AVNLog.debug("unable to convert ais data: %s",
                              traceback.format_exc())
     return json.dumps(frt, cls=Encoder)
Esempio n. 12
0
    def computeRMB(self, computeRMB, computeAPB):
        hasRMB = False
        #do the computation of some route data
        nmeaData = "$GPRMB,A,,,,,,,,,,,,V,D*19\r\n"
        if self.currentLeg is not None and self.currentLeg.isActive():
            if self.startWp != self.currentLeg.getFrom(
            ) or self.endWp != self.currentLeg.getTo():
                self.startWp = self.currentLeg.getFrom()
                self.endWp = self.currentLeg.getTo()
                self.WpNr += 1

            if self.startWp is not None and self.endWp is not None:
                curGps = self.navdata.getDataByPrefix(AVNStore.BASE_KEY_GPS, 1)
                lat = curGps.get('lat')
                lon = curGps.get('lon')
                kn = curGps.get('speed')
                if kn is None:
                    kn = 0
                else:
                    kn = kn * 3600 / AVNUtil.NM
                #we could have speed(kn) or course(deg) in curTPV
                #they are basically as decoded by gpsd
                if lat is not None and lon is not None:
                    AVNLog.debug("compute route data from %s to %s",
                                 str(self.startWp), str(self.endWp))
                    XTE = AVNUtil.calcXTE(
                        (lat, lon), self.wpToLatLon(self.startWp),
                        self.wpToLatLon(self.endWp)) / float(AVNUtil.NM)
                    if XTE > 0:
                        LR = "L"
                    else:
                        LR = "R"
                    XTE = abs(XTE)
                    if XTE > 9.99:
                        XTE = 9.99
                    destDis = AVNUtil.distance((lat, lon),
                                               self.wpToLatLon(self.endWp))
                    if destDis > 999.9:
                        destDis = 999.9
                    if self.currentLeg.isApproach():
                        arrival = "A"
                    else:
                        arrival = "V"
                    wplat = NMEAParser.nmeaFloatToPos(self.endWp['lat'], True)
                    wplon = NMEAParser.nmeaFloatToPos(self.endWp['lon'], False)
                    destBearing = AVNUtil.calcBearing(
                        (lat, lon), self.wpToLatLon(self.endWp))
                    brg = AVNUtil.calcBearing(self.wpToLatLon(self.startWp),
                                              self.wpToLatLon(self.endWp))
                    self.setInfo(
                        "autopilot",
                        "RMB=%s,APB=%s:WpNr=%d,XTE=%s%s,DST=%s,BRG=%s,ARR=%s" %
                        (computeRMB, computeAPB, self.WpNr, XTE, LR, destDis,
                         destBearing, arrival), WorkerStatus.NMEA)
                    hasRMB = True
                    if computeRMB:
                        nmeaData = "GPRMB,A,%.2f,%s,%s,%s,%s,%s,%s,%s,%.1f,%.1f,%.1f,%s,A" % (
                            XTE, LR, self.WpNr, self.WpNr + 1, wplat[0],
                            wplat[1], wplon[0], wplon[1], destDis, destBearing,
                            kn, arrival)
                        nmeaData = "$" + nmeaData + "*" + NMEAParser.nmeaChecksum(
                            nmeaData) + "\r\n"
                        AVNLog.debug("adding NMEA %s", nmeaData)
                        self.feeder.addNMEA(nmeaData, source="router")
                    if computeAPB:
                        nmeaData = "GPAPB,A,A,%.2f,%s,N,%s,,%.1f,M,%s,%.1f,M,%.1f,M" % (
                            XTE, LR, arrival, brg, self.WpNr + 1, destBearing,
                            destBearing)
                        nmeaData = "$" + nmeaData + "*" + NMEAParser.nmeaChecksum(
                            nmeaData) + "\r\n"
                        AVNLog.debug(
                            "adding NMEA %s",
                            nmeaData,
                        )
                        self.feeder.addNMEA(nmeaData, source="router")
        return hasRMB
Esempio n. 13
0
 def computeApproach(self):
     if self.currentLeg is None:
         AVNLog.debug("currentLeg is None")
         self.startStopAlarm(False, self.ALARMS.waypoint)
         self.startStopAlarm(False, self.ALARMS.mob)
         return
     if not self.currentLeg.isActive():
         AVNLog.debug("currentLeg inactive")
         self.startStopAlarm(False, self.ALARMS.waypoint)
         self.startStopAlarm(False, self.ALARMS.mob)
         return
     if self.currentLeg.isMob():
         AVNLog.debug("currentLeg MOB")
         self.startStopAlarm(False, self.ALARMS.waypoint)
         if self.activatedAlarms.get(self.ALARMS.mob) is None:
             self.startStopAlarm(True, self.ALARMS.mob)
         return
     self.startStopAlarm(False, self.ALARMS.mob)
     curGps = self.navdata.getDataByPrefix(AVNStore.BASE_KEY_GPS, 1)
     lat = curGps.get('lat')
     lon = curGps.get('lon')
     if lat is None or lon is None:
         self.startStopAlarm(False, self.ALARMS.waypoint)
         return
     currentLocation = (lat, lon)
     dst = AVNUtil.distanceM(currentLocation,
                             self.wpToLatLon(self.currentLeg.getTo()))
     AVNLog.debug("approach current distance=%f", float(dst))
     if (dst > self.currentLeg.getApproachDistance()):
         old = self.currentLeg.isApproach()
         self.currentLeg.setApproach(False)
         self.startStopAlarm(False, self.ALARMS.waypoint)
         if old:
             #save leg
             self.setCurrentLeg(self.currentLeg)
         self.lastDistanceToCurrent = None
         self.lastDistanceToNext = None
         return
     if self.activatedAlarms.get(self.ALARMS.waypoint) is None:
         self.startStopAlarm(True, self.ALARMS.waypoint)
     if not self.currentLeg.isApproach():
         self.currentLeg.setApproach(True)
         #save the leg
         self.setCurrentLeg(self.currentLeg)
     AVNLog.info("Route: approaching wp %d (%s) currentDistance=%f",
                 self.currentLeg.currentTarget, str(self.currentLeg.toWP),
                 float(dst))
     route = self.currentLeg.getCurrentRoute()
     if route is None or route.get('points') is None:
         AVNLog.debug("Approach: no route active")
         #TODO: stop routing?
         return
     currentTarget = self.currentLeg.getCurrentTarget()
     hasNextWp = True
     nextWpNum = 0
     if currentTarget is None:
         hasNextWp = False
     else:
         nextWpNum = currentTarget + 1
         nextDistance = 0
         if nextWpNum >= len(route['points']):
             AVNLog.debug("already at last WP of route %d", (nextWpNum - 1))
             hasNextWp = False
     if hasNextWp:
         nextWp = route['points'][nextWpNum]
         nextDistance = AVNUtil.distanceM(currentLocation,
                                          self.wpToLatLon(nextWp))
         if self.lastDistanceToNext is None or self.lastDistanceToNext is None:
             #first time in approach
             self.lastDistanceToNext = nextDistance
             self.lastDistanceToCurrent = dst
             return
         #check if the distance to own wp increases and to the next decreases
         diffcurrent = dst - self.lastDistanceToCurrent
         if (diffcurrent <= 0):
             #still decreasing
             self.lastDistanceToCurrent = dst
             self.lastDistanceToNext = nextDistance
             return
         diffnext = nextDistance - self.lastDistanceToNext
         if (diffnext > 0):
             #increases to next
             self.lastDistanceToCurrent = dst
             self.lastDistanceToNext = nextDistance
             return
     else:
         AVNLog.info("last WP of route reached, switch of routing")
         self.currentLeg.setActive(False)
         self.setCurrentLeg(self.currentLeg)
         self.lastDistanceToCurrent = None
         self.lastDistanceToNext = None
         return
     #should we wait for some time???
     AVNLog.info("switching to next WP num=%d, wp=%s", nextWpNum,
                 str(nextWp))
     self.currentLeg.setNewLeg(nextWpNum, self.currentLeg.getTo(), nextWp)
     self.lastDistanceToCurrent = None
     self.lastDistanceToNext = None
     self.setCurrentLeg(self.currentLeg)
Esempio n. 14
0
 def log_message(self, format, *args):
     AVNLog.debug(format, *args)