def enroutenotams(self): c.techroute, c.route = get_route(tripuser(), session['current_trip']) c.tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() if len(c.route) == 0 or len(c.techroute) == 0: redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) return c.trip = c.tripobj.trip for rt in c.route: rt.notampoints = dict() rt.notampoints.update( dict([(info['item']['notam'], info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos), 5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos), mapper.from_str(rt.b.pos)): rt.notampoints[space['name']] = space c.thislink = h.url_for(controller='flightplan', action="enroutenotams") return render('/enroutenotams.mako')
def select_aircraft(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview', action="index")) if not tripsharing.sharing_active(): tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() tripobj.aircraft = request.params['change_aircraft'] if tripobj.aircraft.strip() == "--------": tripobj.aircraft = None else: for route in meta.Session.query(Route).filter( sa.and_( Route.user == tripuser(), Route.trip == session['current_trip'])).order_by( Route.waypoint1).all(): acobj, = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.aircraft == tripobj.aircraft, Aircraft.user == session['user'])).all() route.tas = acobj.cruise_speed meta.Session.flush() meta.Session.commit() redirect( h.url_for(controller='flightplan', action=request.params.get('prevaction', 'fuel')))
def save(self): #print "Saving tripname:",request.params if not self.validate(exception=False, tripname=request.params.get('tripname', False)): return "" try: waypoints = meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all() #print "REquest:",request.params c.userobj.realname = request.params.get('realname', c.userobj.realname) for idx, way in enumerate(waypoints): dof_s = "date_of_flight_%d" % (way.id, ) dep_s = "departure_time_%d" % (way.id, ) fuel_s = "fuel_%d" % (way.id, ) persons_s = "persons_%d" % (way.id, ) name_s = "name%d" % (way.id, ) way.waypoint = request.params.get(name_s, way.waypoint) if dof_s in request.params: #possibly add new stay if not way.stay: #print "Adding stay: ord/id",way.ordering,way.id way.stay = Stay(tripuser(), c.trip.trip, way.id) if re.match(ur"\d{4}-?\d{2}\-?\d{2}", request.params.get(dof_s, '')): way.stay.date_of_flight = request.params.get(dof_s, '') else: way.stay.date_of_flight = '' if re.match(ur"\d{2}:?\d{2}", request.params.get(dep_s, '')): way.stay.departure_time = request.params.get(dep_s, '') else: way.stay.departure_time = '' try: way.stay.nr_persons = int(request.params[persons_s]) except Exception: way.stay.nr_persons = None way.stay.fuel = None way.stay.fueladjust = None try: fuelstr = request.params.get(fuel_s, '').strip() if fuelstr.startswith("+") or fuelstr.startswith("-"): way.stay.fueladjust = float(fuelstr) else: way.stay.fuel = float(fuelstr) except Exception: pass way.altitude = unicode( int( get_terrain_elev.get_terrain_elev( mapper.from_str(way.pos)))) else:
def upload_track(self): print "In upload", request.params.get("gpstrack", None) if 'asplan' in request.params: t = request.params.get("gpstrack", None) orderint = 0 curid = 100 tripsharing.cancel() tripname, waypoints = parse_gpx_fplan(t.value) tripname = self.get_free_tripname(tripname) trip = Trip(tripuser(), tripname) meta.Session.add(trip) meta.Session.flush() out = [] for waypoint in waypoints: name = waypoint['name'] pos = waypoint['pos'] alt = waypoint['alt'] waypoint = Waypoint(tripuser(), trip.trip, pos, curid, orderint, name, alt) meta.Session.add(waypoint) out.append(waypoint) orderint += 1 curid += 1 for w1, w2 in zip(out, out[1:]): r = Route(tripuser(), trip.trip, w1.id, w2.id, altitude=str(w2.altitude)) meta.Session.add(r) acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser())).all() if len(acs): trip.aircraft = acs[0].aircraft session['current_trip'] = tripname session.save() meta.Session.commit() redirect( h.url_for(controller='mapview', action="zoom", zoom='auto')) return t = request.params.get("gpstrack", None) if t != None: if len(t.value) > 30000000: redirect( h.url_for(controller='error', action="document", message="GPX file is too large.")) session['showtrack'] = parse_gpx(t.value, request.params.get('start'), request.params.get('end')) session['showarea'] = '' session['showarea_id'] = '' session.save() redirect(h.url_for(controller='mapview', action="zoom", zoom='auto'))
def standard_prep(self, c): if not 'current_trip' in session: redirect(h.url_for(controller='mapview', action="index")) tripobjs = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).all() if len(tripobjs) != 1: redirect(h.url_for(controller='mapview', action="index")) c.tripobj, = tripobjs c.trip = c.tripobj.trip c.techroute, c.route = get_route(tripuser(), session['current_trip']) #c.route=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) c.user = meta.Session.query(User).filter( User.user == session['user']).one() c.all_aircraft = list( meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == session['user'])).order_by( Aircraft.aircraft).all()) if len(c.route) == 0 or len(c.techroute) == 0: redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) return c.startfuel = 0 if len(c.route) > 0: try: c.startfuel = c.route[0].a.stay.fuel except Exception: pass if c.startfuel == None: c.startfuel = 0 #c.tripobj.startfuel c.acobjs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser(), Aircraft.aircraft == c.tripobj.aircraft)).order_by( Aircraft.aircraft).all() c.ac = None if len(c.acobjs) > 0: c.ac = c.acobjs[0] c.reserve_endurance = "Unknown" if c.ac and c.ac.cruise_burn > 1e-9 and len(c.techroute): minfuelintrip = min(t.accum_fuel_left for t in c.techroute) if minfuelintrip != None: c.reserve_endurance_hours = minfuelintrip / c.ac.cruise_burn mins = int(60.0 * c.reserve_endurance_hours) if mins >= 0: c.reserve_endurance = "%dh%02dm" % (mins / 60, mins % 60) c.departure = c.route[0].a.waypoint c.arrival = c.route[-1].b.waypoint c.fillable = c.user.fillable
def save(self): #print "Saving tripname:",request.params if not self.validate(exception=False,tripname=request.params.get('tripname',False)): return "" try: waypoints=meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(), Waypoint.trip==c.trip.trip)).order_by(Waypoint.ordering).all() #print "REquest:",request.params c.userobj.realname=request.params.get('realname',c.userobj.realname) for idx,way in enumerate(waypoints): dof_s="date_of_flight_%d"%(way.id,) dep_s="departure_time_%d"%(way.id,) fuel_s="fuel_%d"%(way.id,) persons_s="persons_%d"%(way.id,) name_s="name%d"%(way.id,) way.waypoint=request.params.get(name_s,way.waypoint) if dof_s in request.params: #possibly add new stay if not way.stay: #print "Adding stay: ord/id",way.ordering,way.id way.stay=Stay(tripuser(),c.trip.trip,way.id) if re.match(ur"\d{4}-?\d{2}\-?\d{2}",request.params.get(dof_s,'')): way.stay.date_of_flight=request.params.get(dof_s,'') else: way.stay.date_of_flight='' if re.match(ur"\d{2}:?\d{2}",request.params.get(dep_s,'')): way.stay.departure_time=request.params.get(dep_s,'') else: way.stay.departure_time='' try: way.stay.nr_persons=int(request.params[persons_s]) except Exception: way.stay.nr_persons=None way.stay.fuel=None way.stay.fueladjust=None try: fuelstr=request.params.get(fuel_s,'').strip() if fuelstr.startswith("+") or fuelstr.startswith("-"): way.stay.fueladjust=float(fuelstr) else: way.stay.fuel=float(fuelstr) except Exception: pass way.altitude=unicode(int(get_terrain_elev.get_terrain_elev(mapper.from_str(way.pos)))) else:
def standard_prep(self,c): if not 'current_trip' in session: redirect(h.url_for(controller='mapview',action="index")) tripobjs=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).all() if len(tripobjs)!=1: redirect(h.url_for(controller='mapview',action="index")) c.tripobj,=tripobjs c.trip=c.tripobj.trip c.techroute,c.route=get_route(tripuser(),session['current_trip']) #c.route=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all()) c.user=meta.Session.query(User).filter( User.user==session['user']).one() c.all_aircraft=list(meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==session['user'])).order_by(Aircraft.aircraft).all()) if len(c.route)==0 or len(c.techroute)==0: redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) return c.startfuel=0 if len(c.route)>0: try: c.startfuel=c.route[0].a.stay.fuel except Exception: pass if c.startfuel==None: c.startfuel=0 #c.tripobj.startfuel c.acobjs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser(),Aircraft.aircraft==c.tripobj.aircraft)).order_by(Aircraft.aircraft).all() c.ac=None if len(c.acobjs)>0: c.ac=c.acobjs[0] c.reserve_endurance="Unknown" if c.ac and c.ac.cruise_burn>1e-9 and len(c.techroute): minfuelintrip=min(t.accum_fuel_left for t in c.techroute) if minfuelintrip!=None: c.reserve_endurance_hours=minfuelintrip/c.ac.cruise_burn mins=int(60.0*c.reserve_endurance_hours) if mins>=0: c.reserve_endurance="%dh%02dm"%(mins/60,mins%60) c.departure=c.route[0].a.waypoint c.arrival=c.route[-1].b.waypoint c.fillable=c.user.fillable
def weather(self): dummy,routes=get_route(tripuser(),request.params['tripname']) ret=[] alts=request.params.get('alts','') if alts==None: altvec=[] else: altvec=alts.split(",") for route,altitude in zip(routes,altvec): #print("Looking for waypoint: %s"%(way.pos,)) try: mapper.parse_elev(altitude) except mapper.NotAnAltitude,cause: ret.append(['','']) continue #skip this alt #N+1 selects.... merc1=mapper.latlon2merc(mapper.from_str(route.a.pos),14) merc2=mapper.latlon2merc(mapper.from_str(route.a.pos),14) center=(0.5*(merc1[0]+merc2[0]),0.5*(merc1[1]+merc2[1])) lat,lon=mapper.merc2latlon(center,14) #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude) when=route.depart_dt+(route.arrive_dt-route.depart_dt)/2 dummy1,dummy2,we=gfs_weather.get_prognosis(when) if we==None: return ""; #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey. else: try: wi=we.get_wind(lat,lon,mapper.parse_elev(altitude)) except: print traceback.format_exc() return "" #print "Got winds:",wi ret.append([wi['direction'],wi['knots']])
def weather(self): dummy, routes = get_route(tripuser(), request.params['tripname']) ret = [] alts = request.params.get('alts', '') if alts == None: altvec = [] else: altvec = alts.split(",") for route, altitude in zip(routes, altvec): #print("Looking for waypoint: %s"%(way.pos,)) try: mapper.parse_elev(altitude) except mapper.NotAnAltitude, cause: ret.append(['', '']) continue #skip this alt #N+1 selects.... merc1 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14) merc2 = mapper.latlon2merc(mapper.from_str(route.a.pos), 14) center = (0.5 * (merc1[0] + merc2[0]), 0.5 * (merc1[1] + merc2[1])) lat, lon = mapper.merc2latlon(center, 14) #print "Fetching weather for %s,%s, %s"%(lat,lon,route.altitude) when = route.depart_dt + (route.arrive_dt - route.depart_dt) / 2 dummy1, dummy2, we = gfs_weather.get_prognosis(when) if we == None: return "" #Fail completely we don't have the weather here. We only succeed if we have weather for all parts of the journey. else: try: wi = we.get_wind(lat, lon, mapper.parse_elev(altitude)) except: print traceback.format_exc() return "" #print "Got winds:",wi ret.append([wi['direction'], wi['knots']])
def gpx(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname', None), exception=False): return "Internal error. Missing trip-name or user-session." waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all()) if len(waypoints) == 0: return redirect( h.url_for(controller='flightplan', action="index", flash=u"Must have at least two waypoints in trip!")) c.waypoints = [] for wp in waypoints: lat, lon = mapper.from_str(wp.pos) c.waypoints.append(dict(lat=lat, lon=lon, name=wp.waypoint)) #response.headers['Content-Type'] = 'application/xml' response.content_type = 'application/octet-stream' response.charset = "utf8" return render('/gpx.mako')
def upload_track(self): print "In upload",request.params.get("gpstrack",None) if 'asplan' in request.params: t=request.params.get("gpstrack",None) orderint=0 curid=100 tripsharing.cancel() tripname,waypoints=parse_gpx_fplan(t.value) tripname=self.get_free_tripname(tripname) trip=Trip(tripuser(), tripname) meta.Session.add(trip) meta.Session.flush() out=[] for waypoint in waypoints: name=waypoint['name'] pos=waypoint['pos'] alt=waypoint['alt'] waypoint=Waypoint(tripuser(),trip.trip,pos,curid,orderint,name,alt) meta.Session.add(waypoint) out.append(waypoint) orderint+=1 curid+=1 for w1,w2 in zip(out,out[1:]): r=Route(tripuser(),trip.trip, w1.id,w2.id,altitude=str(w2.altitude)) meta.Session.add(r) acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser())).all() if len(acs): trip.aircraft=acs[0].aircraft session['current_trip']=tripname session.save() meta.Session.commit() redirect(h.url_for(controller='mapview',action="zoom",zoom='auto')) return t=request.params.get("gpstrack",None) if t!=None: if len(t.value)>30000000: redirect(h.url_for(controller='error',action="document",message="GPX file is too large.")) session['showtrack']=parse_gpx(t.value,request.params.get('start'),request.params.get('end')) session['showarea']='' session['showarea_id']='' session.save() redirect(h.url_for(controller='mapview',action="zoom",zoom='auto'))
def enroutenotams(self): c.techroute,c.route=get_route(tripuser(),session['current_trip']) c.tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() if len(c.route)==0 or len(c.techroute)==0: redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) return c.trip=c.tripobj.trip for rt in c.route: rt.notampoints=dict() rt.notampoints.update(dict([(info['item']['notam'],info['item']) for info in get_notampoints_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos),5)])) for rt in c.route: for space in get_notam_areas_on_line(mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)): rt.notampoints[space['name']]=space c.thislink=h.url_for(controller='flightplan',action="enroutenotams") return render('/enroutenotams.mako')
def validate(self,exception=True,tripname=None): try: if tripname==None: tripname=session['current_trip'] c.trip=meta.Session.query(Trip).filter(sa.and_(Trip.user==tripuser(), Trip.trip==tripname)).one() c.userobj=meta.Session.query(User).filter(User.user==session['user']).one() except Exception,cause: log.warning("Access flightplan without session or trip: %s"%(cause,)) if not exception: return False else: raise
def select_aircraft(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview',action="index")) if not tripsharing.sharing_active(): tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() tripobj.aircraft=request.params['change_aircraft'] if tripobj.aircraft.strip()=="--------": tripobj.aircraft=None else: for route in meta.Session.query(Route).filter(sa.and_( Route.user==tripuser(),Route.trip==session['current_trip'])).order_by(Route.waypoint1).all(): acobj,=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.aircraft==tripobj.aircraft,Aircraft.user==session['user'])).all() route.tas=acobj.cruise_speed meta.Session.flush() meta.Session.commit() redirect(h.url_for(controller='flightplan',action=request.params.get('prevaction','fuel')))
def validate(self, exception=True, tripname=None): try: if tripname == None: tripname = session['current_trip'] c.trip = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == tripname)).one() c.userobj = meta.Session.query(User).filter( User.user == session['user']).one() except Exception, cause: log.warning("Access flightplan without session or trip: %s" % (cause, )) if not exception: return False else: raise
def optimize(self): if not self.validate(exception=False,tripname=request.params.get('tripname',False)): return "" #for rt in c.route: # rt.maxobstelev=get_obstacle_free_height_on_line( ## mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)) # # print "Max obst elev",rt.maxobstelev strat=request.params.get('strategy','time') print "Strategy",strat resultcode,routes=calc_route_info.get_optimized(tripuser(),c.trip.trip, strat) if resultcode==False: return "" out=[] for rt in routes: out.append([rt.winddir,rt.windvel,rt.altitude]) s=json.dumps(out) print "Optimized output",s return s
def optimize(self): if not self.validate(exception=False, tripname=request.params.get('tripname', False)): return "" #for rt in c.route: # rt.maxobstelev=get_obstacle_free_height_on_line( ## mapper.from_str(rt.a.pos),mapper.from_str(rt.b.pos)) # # print "Max obst elev",rt.maxobstelev strat = request.params.get('strategy', 'time') print "Strategy", strat resultcode, routes = calc_route_info.get_optimized( tripuser(), c.trip.trip, strat) if resultcode == False: return "" out = [] for rt in routes: out.append([rt.winddir, rt.windvel, rt.altitude]) s = json.dumps(out) print "Optimized output", s return s
def gpx(self): # Return a rendered template #return render('/flightplan.mako') # or, return a response if not self.validate(tripname=request.params.get('tripname',None),exception=False): return "Internal error. Missing trip-name or user-session." waypoints=list(meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==c.trip.trip)).order_by(Waypoint.ordering).all()) if len(waypoints)==0: return redirect(h.url_for(controller='flightplan',action="index",flash=u"Must have at least two waypoints in trip!")) c.waypoints=[] for wp in waypoints: lat,lon=mapper.from_str(wp.pos) c.waypoints.append(dict( lat=lat, lon=lon, name=wp.waypoint )) #response.headers['Content-Type'] = 'application/xml' response.content_type = 'application/octet-stream' response.charset="utf8" return render('/gpx.mako')
def save(self): try: if 'pos' in request.params and 'zoomlevel' in request.params: save_merc_x,save_merc_y=[int(x) for x in request.params['pos'].split(",")] save_zoom=int(request.params['zoomlevel']) pos=mapper.merc2latlon((save_merc_x,save_merc_y),save_zoom) self.set_pos_zoom(pos,save_zoom) wps=self.get_waypoints(request.params) oldname=request.params.get('oldtripname','') tripname=request.params.get('tripname','') if tripsharing.sharing_active(): #Can't rename trips while tripsharing is active! tripname=session['current_trip'] if oldname!=session['current_trip']: #In some strange way a non-tripsharing oldname appeared in the post. This #means that something has gone awry. Don't save! print "Bad trip oldname while tripsharing active!" return "notok" if 'showarea' in request.params and request.params['showarea']: sha=request.params['showarea'] if (sha=='.'): session['showarea']='' session['showarea_id']='' session['showtrack']=None else: session['showarea']=sha session['showarea_id']=md5(sha.encode('utf8')).hexdigest() session['showtrack']=None session['mapvariant']=request.params.get('mapvariant','airspace') #print "Req:",request.params oldtrip=None if not oldname.strip(): oldname=tripname oldtrips=meta.Session.query(Trip).filter(sa.and_(Trip.user==tripuser(),Trip.trip==oldname)).all() if len(oldtrips)==1: oldtrip=oldtrips[0] if oldtrip: trip=oldtrip if trip.trip!=tripname: if tripsharing.sharing_active(): #attempt to rename someone elses trip! Can't be allowed! set tripname to old name print "Attempt to rename trip while viewing shared trip (tripsharing)" return "notok" else: trip.trip=self.get_free_tripname(tripname) if session['current_trip']!=trip.trip and tripsharing.sharing_active(): #internal error if we get here - the earlier test for current_trip not changing failed. print "Unexpected tripsharing error #2" return "notok" session['current_trip']=trip.trip else: if tripsharing.sharing_active(): #we use sharing, but the shared trip can't be found! print "Tripsharing active, but named trip didn't exist (deleted, probably)" return "notok" tripname=self.get_free_tripname(tripname) trip = Trip(tripuser(), tripname) acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser())).all() if len(acs): trip.aircraft=acs[0].aircraft meta.Session.add(trip) session['current_trip']=tripname oldwps=set([(wp.id) for wp in meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==trip.trip)).all()]) newwps=set(wps.keys()) #print "NEW WPS",wps removed=oldwps.difference(newwps) added=newwps.difference(oldwps) updated=newwps.intersection(oldwps) print "Removed: ",removed addedwps=added removedwps=removed updatedwps=updated ordering2wpid=dict() for remord in removed: meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user==tripuser(),Waypoint.trip==trip.trip, Waypoint.id==remord)).delete() #print "\n\n====DELETING!=====\n%s\n\n"%(rem,) resultant_by_order=dict() resultant_id2order=dict() waypointlink=dict() for add in added: wp=wps[add] waypoint=Waypoint(tripuser(),trip.trip,wp['pos'],int(wp['id']),int(wp['ordering']),wp['name'],wp['altitude']) resultant_by_order[int(wp['ordering'])]=waypoint resultant_id2order[int(wp['id'])]=wp['ordering'] #print "\n\n====ADDING!=====\n%s %s %s\n\n"%(waypoint.id,waypoint.pos,waypoint.waypoint) meta.Session.add(waypoint) for upd in updated: wp=wps[upd] us=meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user==tripuser(),Waypoint.trip==trip.trip, Waypoint.id==upd)).all() if len(us)>0: u=us[0] prevpos=mapper.from_str(u.pos) newpos=mapper.from_str(wp['pos']) approxdist=(prevpos[0]-newpos[0])**2+(prevpos[1]-newpos[1])**2 if approxdist>(1.0/36000.0)**2: #if moved more than 0.1 arc-second, otherwise leave be. u.pos=wp['pos'] print "Waypoint %d moved! (%f deg)"%(u.id,math.sqrt(approxdist)) else: print "Waypoint %d has only moved a little (%f deg)"%(u.id,math.sqrt(approxdist)) u.waypoint=wp['name'] assert u.id==int(wp['id']) u.ordering=wp['ordering'] u.altitude=wp['altitude'] resultant_by_order[int(wp['ordering'])]=u resultant_id2order[int(wp['id'])]=wp['ordering'] #print "\n\n====UPDATING!=====\n%s %s %s\n\n"%(u.id,u.pos,u.waypoint) #print "Resultant by ordering: %s"%(resultant_by_order,) seq=list(sorted(resultant_by_order.items())) newroutes=set() for (ord1,waypoint1),(ord2,waypoint2) in zip(seq[:-1],seq[1:]): if not int(ord1)+1==int(ord2): print "Waypoints %s and %s not consecutive (#%d, #%d)"%(waypoint1,waypoint2,int(ord1),int(ord2)) assert int(ord1)+1==int(ord2) newroutes.add((waypoint1.id,waypoint2.id)) oldrouteobjs=list(meta.Session.query(Route).filter(sa.and_( Route.user==tripuser(),Route.trip==trip.trip)).all()) oldroutes=set([(route.waypoint1,route.waypoint2) for route in oldrouteobjs]) prevalts=dict() for rt in oldrouteobjs: prevalts[(rt.a.id,+1)]=rt.altitude prevalts[(rt.b.id,-1)]=rt.altitude #Routes: removed=oldroutes.difference(newroutes) added=newroutes.difference(oldroutes) updated=newroutes.intersection(oldroutes) print "Removed routes:",removed print "Added routes:",added print "Kept routes: ",updated for rem1,rem2 in removed: meta.Session.query(Route).filter( sa.and_(Route.user==tripuser(),Route.trip==trip.trip, Route.waypoint1==rem1,Route.waypoint2==rem2)).delete() sel_acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.aircraft==trip.aircraft,Aircraft.user==tripuser())).all() if len(sel_acs): tas=sel_acs[0].cruise_speed else: tas=75 for a1,a2 in added: cruisealt="" a=None if a1 in addedwps: startord=resultant_id2order.get(int(a1),0) elif a2 in addedwps: startord=resultant_id2order.get(int(a2),0) else: startord=resultant_id2order.get(int(a1),0) print "Ordering of new wp: %d is %d"%(a1,startord) num_waypoints=len(resultant_by_order) def searchpattern(begin,num): assert begin>=0 and begin<num down=begin-1 up=begin+1 while True: work=False if down>=0: yield down down-=1 work=True if up<num: yield up up+=1 work=True if not work: break for wpord in searchpattern(startord,num_waypoints): wp=resultant_by_order.get(wpord,None) print "Searchpattern visiting order: %d"%(wpord,) if wp: if wpord<startord: cruisealt=prevalts.get((wp.id,+1),'') print "Looking for alt previously after wp %d, got: %s"%(wp.id,cruisealt) else: cruisealt=prevalts.get((wp.id,-1),'') print "Looking for alt previously before wp %d, got: %s"%(wp.id,cruisealt) if cruisealt!="": break if cruisealt=="": cruisealt="1500" r=Route(tripuser(),trip.trip, a1,a2,0,0,tas,None,cruisealt) meta.Session.add(r) session.save() meta.Session.flush() meta.Session.commit(); ret=json.dumps([tripname]) print "mapview returning json:",ret return ret except Exception,cause: #print line number and stuff as well print cause #TODO: ONLY FOR TESTING!!!! raise return "notok"
way.stay.fueladjust=float(fuelstr) else: way.stay.fuel=float(fuelstr) except Exception: pass way.altitude=unicode(int(get_terrain_elev.get_terrain_elev(mapper.from_str(way.pos)))) else: #remove any stay meta.Session.query(Stay).filter(sa.and_( Stay.user==way.user,Stay.trip==way.trip,Stay.waypoint_id==way.id)).delete() way.altitude=u'' for idx,way in enumerate(waypoints[:-1]): #print "Found waypoint #%d"%(idx,) route=meta.Session.query(Route).filter(sa.and_( Route.user==tripuser(), Route.trip==c.trip.trip, Route.waypoint1==way.id, )).one() for col,att in [ ('W','winddir'), ('V','windvel'), ('TAS','tas'), ('Alt','altitude'), ('Dev','deviation') ]: key="%s_%d"%(col,way.id) if col=='TAS' and not key in request.params: #TAS is not present if ac.advanced_model==false continue
def index(self): print "Index called", session.get('zoom', -1) #print "index called",request.params #user=meta.Session.query(User).filter( # User.user==tripuser()).one() user = meta.Session.query(User).filter( User.user == session['user']).one() ua = request.headers.get('User-Agent', '').lower() c.ie = False if ua.count("msie") and not (ua.count("firefox") or ua.count("chrom") or ua.count("safari")): c.ie = True #print "IE mode:",c.ie c.all_trips = list( meta.Session.query(Trip).filter( Trip.user == session['user']).all()) print "current trip:", session.get('current_trip', None) if not ('current_trip' in session) or session['current_trip'] == None: if user.lasttrip != None: print "Reusing lasttrip:", user.lasttrip session['current_trip'] = user.lasttrip if 'current_trip' in session and meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).count() == 0: session['current_trip'] = None if not 'current_trip' in session or session['current_trip'] == None: trips = meta.Session.query(Trip).filter( Trip.user == tripuser()).all() if len(trips) == 0: trip = Trip(tripuser(), "Default Trip") meta.Session.add(trip) meta.Session.flush() meta.Session.commit() else: trip = min( trips, key=lambda x: x.trip ) #Select first trip, alphabetically - we have no better idea. session['current_trip'] = trip.trip session.save() trip = None if session.get('current_trip', None) != user.lasttrip: user.lasttrip = session.get('current_trip', None) print "Storing lasttrip=", user.lasttrip meta.Session.flush() meta.Session.commit() c.mapvariant = session.get('mapvariant', "airspace") self.set_pos_zoom() zoomlevel = session['zoom'] if c.mapvariant == "elev": if zoomlevel > 8: session['zoom'] = 8 session.save() try: session['last_pos'] = mapper.latlon2merc( mapper.merc2latlon(session['last_pos'], zoomlevel), 8) except Exception: session['last_pos'] = mapper.latlon2merc((59, 18), 8) print "Setting session last pos to 59,18", session[ 'last_pos'] zoomlevel = 8 print "Last pos is:", mapper.merc2latlon(session['last_pos'], zoomlevel) c.merc_x, c.merc_y = session['last_pos'] c.merc5_limx1, c.merc5_limy1, c.merc5_limx2, c.merc5_limy2 = merc_limits( 5, conservative=False, hd=True) c.waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == session['current_trip'])).order_by( Waypoint.ordering).all()) c.tripname = session['current_trip'] c.showarea = session.get('showarea', '') c.showtrack = session.get('showtrack', None) != None c.fastmap = user.fastmap #print "Zoomlevel active: ",zoomlevel c.zoomlevel = zoomlevel c.dynamic_id = '' c.sharing = tripsharing.sharing_active() c.mtime = maptilereader.get_mtime() for way in c.waypoints: print "Name:", way.waypoint if len(c.waypoints): c.next_waypoint_id = max([way.id for way in c.waypoints]) + 1 else: c.next_waypoint_id = 100 assert type(c.next_waypoint_id) == int if c.sharing: c.shared_by = tripuser() if session.get('showarea', ''): c.dynamic_id = session.get('showarea_id', '') if session.get('showtrack', ''): if hasattr(session['showtrack'], 'dynamic_id'): c.dynamic_id = session['showtrack'].dynamic_id return render('/mapview.mako')
def trip_actions(self): #print "trip actions:",request.params if request.params.get('addtripname', None): tripsharing.cancel() tripname = self.get_free_tripname(request.params['addtripname']) trip = Trip(tripuser(), tripname) acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser())).all() if len(acs): trip.aircraft = acs[0].aircraft print "Adding trip:", trip meta.Session.add(trip) session['current_trip'] = tripname session.save() if request.params.get('opentripname', None): tripsharing.cancel() tripname = request.params['opentripname'] if meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == tripname)).count(): session['current_trip'] = tripname session.save() if request.params.get('reversetripname', None): tripsharing.cancel() username = tripuser() print "Reversing" tripname = request.params['reversetripname'] wps = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == username, Waypoint.trip == tripname)).order_by( Waypoint.ordering).all()) if len(wps): maxord = max([wp.ordering for wp in wps]) for wp in wps: wp.ordering = maxord + 1 - wp.ordering print "Reversed order of", wp.waypoint, " = ", wp.ordering meta.Session.add(wp) firststays = meta.Session.query(Stay).filter( sa.and_(Stay.user == username, Stay.trip == tripname, Stay.waypoint_id == wps[0].id)).all() if len(firststays) == 1: stay, = firststays stay.waypoint_id = wps[-1].id if request.params.get('copytripname', None): tripsharing.cancel() tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == request.params['copytripname'])).first() newtripname = self.get_free_tripname(tripobj.trip + "(copy)") trip = Trip(tripuser(), newtripname) meta.Session.add(trip) acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser(), Aircraft.aircraft == tripobj.aircraft)).all() if len(acs): trip.aircraft = acs[0].aircraft for origwp in meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == tripobj.trip)).all(): wp = Waypoint(user=origwp.user, trip=newtripname, pos=origwp.pos, id_=origwp.id, ordering=origwp.ordering, waypoint=origwp.waypoint, altitude=origwp.altitude) meta.Session.add(wp) for origrt in meta.Session.query(Route).filter( sa.and_(Route.user == tripuser(), Route.trip == tripobj.trip)).all(): rt = Route(user=origrt.user, trip=newtripname, waypoint1=origrt.waypoint1, waypoint2=origrt.waypoint2, tas=origrt.tas, winddir=origrt.winddir, windvel=origrt.windvel, variation=origrt.variation) meta.Session.add(rt) for origstay in meta.Session.query(Stay).filter( sa.and_(Stay.user == tripuser(), Stay.trip == tripobj.trip)).all(): stay = Stay(user=origstay.user, trip=newtripname, waypoint_id=origstay.waypoint_id, fuel=origstay.fuel, date_of_flight=origstay.date_of_flight, departure_time=origstay.departure_time, nr_persons=origstay.nr_persons, fueladjust=origstay.fueladjust) meta.Session.add(stay) print "Adding trip:", trip session['current_trip'] = newtripname session.save() if request.params.get('deletetripname', None) and not tripsharing.sharing_active(): meta.Session.query(Trip).filter( sa.and_( Trip.user == tripuser(), Trip.trip == request.params['deletetripname'])).delete() del session['current_trip'] session.save() meta.Session.flush() meta.Session.commit() redirect(h.url_for(controller='mapview', action="index"))
def trip_actions(self): #print "trip actions:",request.params if request.params.get('addtripname',None): tripsharing.cancel() tripname=self.get_free_tripname(request.params['addtripname']) trip = Trip(tripuser(), tripname) acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser())).all() if len(acs): trip.aircraft=acs[0].aircraft print "Adding trip:",trip meta.Session.add(trip) session['current_trip']=tripname session.save() if request.params.get('opentripname',None): tripsharing.cancel() tripname=request.params['opentripname'] if meta.Session.query(Trip).filter(sa.and_(Trip.user==tripuser(), Trip.trip==tripname)).count(): session['current_trip']=tripname session.save() if request.params.get('reversetripname',None): tripsharing.cancel() username=tripuser() print "Reversing" tripname=request.params['reversetripname'] wps=list(meta.Session.query(Waypoint).filter(sa.and_(Waypoint.user==username,Waypoint.trip==tripname)).order_by(Waypoint.ordering).all()) if len(wps): maxord=max([wp.ordering for wp in wps]) for wp in wps: wp.ordering=maxord+1-wp.ordering print "Reversed order of",wp.waypoint," = ",wp.ordering meta.Session.add(wp) firststays=meta.Session.query(Stay).filter(sa.and_(Stay.user==username,Stay.trip==tripname,Stay.waypoint_id==wps[0].id)).all() if len(firststays)==1: stay,=firststays stay.waypoint_id=wps[-1].id if request.params.get('copytripname',None): tripsharing.cancel() tripobj=meta.Session.query(Trip).filter(sa.and_(Trip.user==tripuser(), Trip.trip==request.params['copytripname'])).first() newtripname=self.get_free_tripname(tripobj.trip+"(copy)") trip = Trip(tripuser(), newtripname) meta.Session.add(trip) acs=meta.Session.query(Aircraft).filter(sa.and_( Aircraft.user==tripuser(),Aircraft.aircraft==tripobj.aircraft)).all() if len(acs): trip.aircraft=acs[0].aircraft for origwp in meta.Session.query(Waypoint).filter(sa.and_(Waypoint.user==tripuser(),Waypoint.trip==tripobj.trip)).all(): wp=Waypoint(user=origwp.user,trip=newtripname,pos=origwp.pos,id_=origwp.id, ordering=origwp.ordering,waypoint=origwp.waypoint,altitude=origwp.altitude) meta.Session.add(wp) for origrt in meta.Session.query(Route).filter(sa.and_(Route.user==tripuser(),Route.trip==tripobj.trip)).all(): rt=Route(user=origrt.user,trip=newtripname,waypoint1=origrt.waypoint1,waypoint2=origrt.waypoint2,tas=origrt.tas, winddir=origrt.winddir,windvel=origrt.windvel,variation=origrt.variation) meta.Session.add(rt) for origstay in meta.Session.query(Stay).filter(sa.and_(Stay.user==tripuser(),Stay.trip==tripobj.trip)).all(): stay=Stay(user=origstay.user,trip=newtripname,waypoint_id=origstay.waypoint_id, fuel=origstay.fuel,date_of_flight=origstay.date_of_flight, departure_time=origstay.departure_time, nr_persons=origstay.nr_persons,fueladjust=origstay.fueladjust) meta.Session.add(stay) print "Adding trip:",trip session['current_trip']=newtripname session.save() if request.params.get('deletetripname',None) and not tripsharing.sharing_active(): meta.Session.query(Trip).filter(sa.and_(Trip.user==tripuser(), Trip.trip==request.params['deletetripname'])).delete() del session['current_trip'] session.save() meta.Session.flush() meta.Session.commit(); redirect(h.url_for(controller='mapview',action="index"))
def obstacles(self): routes,baseroute=get_route(tripuser(),session['current_trip']) tripobj=meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(),Trip.trip==session['current_trip'])).one() c.trip=tripobj.trip id2order=dict([(rt.a.id,rt.a.ordering) for rt in baseroute]) byidsorted=sorted(self.get_obstacles(routes).items(),key=lambda x:id2order.get(x[0],0)) out=[] def classify(item): #print item vertlimit=1000 if item.get('kind',None)=='lowsun': return "#ffffb0" if item.get('kind',None)=='terrain': vertlimit=500 try: margin=item['closestalt']-mapper.parse_elev(item['elev']) except Exception: return "#0000ff" #Unknown margin, unknown height if item['dist']>0.6/1.852: return None #Not really too close anyway if margin<0: return "#ff3030" if margin<vertlimit: return "#ffb0b0" return None dupecheck=dict() for idx,items in byidsorted: for item in items: ident=(item['name'],item['pos'],item.get('elev',None)) dupecheck.setdefault(ident,[]).append(item) bestdupe=dict() for ident,dupes in dupecheck.items(): best=min(dupes,key=lambda x:x['dist']) bestdupe[ident]=best for idx,items in byidsorted: cur=[] for item in items: dist_from_a=item['dist_from_a'] dist_from_b=item['dist_from_b'] if abs(dist_from_a)<0.5: descr="Near %s"%(item['a'].waypoint,) elif abs(dist_from_b)<0.5: descr="Near %s"%(item['b'].waypoint,) elif dist_from_a<dist_from_b: descr="%.0fNM %s of %s"%(dist_from_a,item['dir_from_a'],item['a'].waypoint) else: descr="%.0fNM %s of %s"%(dist_from_b,item['dir_from_b'],item['b'].waypoint) ident=(item['name'],item['pos'],item.get('elev',None)) best=bestdupe[ident] if not (best is item): continue #if ident in seen: continue #seen.add(ident) cur.append(dict( routepointdescr=descr, #dir_from_a=item['dir_from_a'], #fromwhat=fromwhat, kind=item.get('kind',None), bearing=item.get('bearing',None), along_nm=dist_from_a, dist=item['dist'], name=item['name'], closestalt=item['closestalt'], elev=item.get('elev',None))) cur[-1]['color']=classify(cur[-1]) out.append((items[0]['a'].waypoint,sorted(cur,key=lambda x:x['along_nm']))) c.items=out return render('/obstacles.mako')
def index(self): print "Index called", session.get('zoom',-1) #print "index called",request.params #user=meta.Session.query(User).filter( # User.user==tripuser()).one() user=meta.Session.query(User).filter( User.user==session['user']).one() ua=request.headers.get('User-Agent','').lower() c.ie=False if ua.count("msie") and not (ua.count("firefox") or ua.count("chrom") or ua.count("safari")): c.ie=True #print "IE mode:",c.ie c.all_trips=list(meta.Session.query(Trip).filter(Trip.user==session['user']).all()) print "current trip:",session.get('current_trip',None) if not ('current_trip' in session) or session['current_trip']==None: if user.lasttrip!=None: print "Reusing lasttrip:",user.lasttrip session['current_trip']=user.lasttrip if 'current_trip' in session and meta.Session.query(Trip).filter(sa.and_( Trip.user==tripuser(), Trip.trip==session['current_trip'] )).count()==0: session['current_trip']=None if not 'current_trip' in session or session['current_trip']==None: trips=meta.Session.query(Trip).filter( Trip.user==tripuser()).all() if len(trips)==0: trip = Trip(tripuser(), "Default Trip") meta.Session.add(trip) meta.Session.flush() meta.Session.commit() else: trip=min(trips,key=lambda x:x.trip) #Select first trip, alphabetically - we have no better idea. session['current_trip']=trip.trip session.save() trip=None if session.get('current_trip',None)!=user.lasttrip: user.lasttrip=session.get('current_trip',None) print "Storing lasttrip=",user.lasttrip meta.Session.flush() meta.Session.commit() c.mapvariant=session.get('mapvariant',"airspace") self.set_pos_zoom() zoomlevel=session['zoom'] if c.mapvariant=="elev": if zoomlevel>8: session['zoom']=8 session.save() try: session['last_pos']=mapper.latlon2merc(mapper.merc2latlon(session['last_pos'],zoomlevel),8) except Exception: session['last_pos']=mapper.latlon2merc((59,18),8) print "Setting session last pos to 59,18",session['last_pos'] zoomlevel=8 print "Last pos is:",mapper.merc2latlon(session['last_pos'],zoomlevel) c.merc_x,c.merc_y=session['last_pos'] c.merc5_limx1,c.merc5_limy1,c.merc5_limx2,c.merc5_limy2=merc_limits(5,conservative=False,hd=True) c.waypoints=list(meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==session['current_trip'])).order_by(Waypoint.ordering).all()) c.tripname=session['current_trip'] c.showarea=session.get('showarea','') c.showtrack=session.get('showtrack',None)!=None c.fastmap=user.fastmap; #print "Zoomlevel active: ",zoomlevel c.zoomlevel=zoomlevel c.dynamic_id='' c.sharing=tripsharing.sharing_active() c.mtime=maptilereader.get_mtime() for way in c.waypoints: print "Name:",way.waypoint if len(c.waypoints): c.next_waypoint_id=max([way.id for way in c.waypoints])+1 else: c.next_waypoint_id=100 assert type(c.next_waypoint_id)==int if c.sharing: c.shared_by=tripuser() if session.get('showarea',''): c.dynamic_id=session.get('showarea_id','') if session.get('showtrack',''): if hasattr(session['showtrack'],'dynamic_id'): c.dynamic_id=session['showtrack'].dynamic_id return render('/mapview.mako')
way.altitude = unicode( int( get_terrain_elev.get_terrain_elev( mapper.from_str(way.pos)))) else: #remove any stay meta.Session.query(Stay).filter( sa.and_(Stay.user == way.user, Stay.trip == way.trip, Stay.waypoint_id == way.id)).delete() way.altitude = u'' for idx, way in enumerate(waypoints[:-1]): #print "Found waypoint #%d"%(idx,) route = meta.Session.query(Route).filter( sa.and_( Route.user == tripuser(), Route.trip == c.trip.trip, Route.waypoint1 == way.id, )).one() for col, att in [('W', 'winddir'), ('V', 'windvel'), ('TAS', 'tas'), ('Alt', 'altitude'), ('Dev', 'deviation')]: key = "%s_%d" % (col, way.id) if col == 'TAS' and not key in request.params: #TAS is not present if ac.advanced_model==false continue val = request.params[key] #print "Value of key %s: %s"%(key,val) if col == "Alt": setattr(route, att, val[0:6])
def index(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview', action="index")) c.flash = request.params.get('flash', None) c.waypoints = list( meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == c.trip.trip)).order_by( Waypoint.ordering).all()) if len(c.waypoints): wp0 = c.waypoints[0] if wp0.stay != None: c.stay = wp0.stay else: #print "No 'Stay', adding" c.stay = Stay(c.trip.user, c.trip.trip, wp0.id) meta.Session.add(c.stay) meta.Session.flush() meta.Session.commit() else: c.stay = None c.realname = c.userobj.realname dummy, routes = get_route(tripuser(), c.trip.trip) c.derived_data = self.get_json_routeinfo(routes) c.totdist = 0.0 if len(routes) > 0: c.totdist = routes[-1].accum_dist wp2route = dict() for rt in routes: wp2route[(rt.waypoint1, rt.waypoint2)] = rt def get(what, a, b): #print "A:<%s>"%(what,),a.pos,b.pos route = wp2route.get((a.id, b.id), None) if route: if what in ['TT', 'D', 'Var']: bear, dist = route.tt, route.d #mapper.bearing_and_distance(a.pos,b.pos) #print "Bear,dist:",bear,dist if what == 'TT': return "%03.0f" % (bear, ) elif what == 'D': return "%.1f" % (dist, ) elif what == 'Var': var = route.variation return "%+.0f" % (round(var), ) if what in ['W', 'V', 'Alt', 'TAS', 'Dev']: #routes=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'], # Route.waypoint1==a.id,Route.waypoint2==b.id)).all()) if what == 'W': return "%03.0f" % (route.winddir) elif what == 'V': return "%.0f" % (route.windvel) elif what == 'Alt': try: #print "Parsing elev:",route.altitude mapper.parse_elev(route.altitude) except Exception, cause: #print "couldn't parse elev:",route.altitude return "1500" return route.altitude elif what == 'Dev': #print "Dev is:",repr(route.deviation) return "%.0f" % ( route.deviation) if route.deviation != None else '' elif what == 'TAS': #print "A:<%s>"%(what,),a.id,b.id,route.tas,id(route) if not route.tas: return 75 return "%.0f" % (route.tas) return "" return ""
def index(self): if not self.validate(exception=False): redirect(h.url_for(controller='mapview',action="index")) c.flash=request.params.get('flash',None) c.waypoints=list(meta.Session.query(Waypoint).filter(sa.and_( Waypoint.user==tripuser(),Waypoint.trip==c.trip.trip)).order_by(Waypoint.ordering).all()) if len(c.waypoints): wp0=c.waypoints[0] if wp0.stay!=None: c.stay=wp0.stay else: #print "No 'Stay', adding" c.stay=Stay(c.trip.user,c.trip.trip,wp0.id) meta.Session.add(c.stay) meta.Session.flush() meta.Session.commit() else: c.stay=None c.realname=c.userobj.realname dummy,routes=get_route(tripuser(),c.trip.trip) c.derived_data=self.get_json_routeinfo(routes) c.totdist=0.0 if len(routes)>0: c.totdist=routes[-1].accum_dist wp2route=dict() for rt in routes: wp2route[(rt.waypoint1,rt.waypoint2)]=rt def get(what,a,b): #print "A:<%s>"%(what,),a.pos,b.pos route=wp2route.get((a.id,b.id),None) if route: if what in ['TT','D','Var']: bear,dist=route.tt,route.d #mapper.bearing_and_distance(a.pos,b.pos) #print "Bear,dist:",bear,dist if what=='TT': return "%03.0f"%(bear,) elif what=='D': return "%.1f"%(dist,) elif what=='Var': var=route.variation return "%+.0f"%(round(var),) if what in ['W','V','Alt','TAS','Dev']: #routes=list(meta.Session.query(Route).filter(sa.and_( # Route.user==tripuser(),Route.trip==session['current_trip'], # Route.waypoint1==a.id,Route.waypoint2==b.id)).all()) if what=='W': return "%03.0f"%(route.winddir) elif what=='V': return "%.0f"%(route.windvel) elif what=='Alt': try: #print "Parsing elev:",route.altitude mapper.parse_elev(route.altitude) except Exception,cause: #print "couldn't parse elev:",route.altitude return "1500" return route.altitude elif what=='Dev': #print "Dev is:",repr(route.deviation) return "%.0f"%(route.deviation) if route.deviation!=None else '' elif what=='TAS': #print "A:<%s>"%(what,),a.id,b.id,route.tas,id(route) if not route.tas: return 75 return "%.0f"%(route.tas) return "" return ""
def obstacles(self): routes, baseroute = get_route(tripuser(), session['current_trip']) tripobj = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == session['current_trip'])).one() c.trip = tripobj.trip id2order = dict([(rt.a.id, rt.a.ordering) for rt in baseroute]) byidsorted = sorted(self.get_obstacles(routes).items(), key=lambda x: id2order.get(x[0], 0)) out = [] def classify(item): #print item vertlimit = 1000 if item.get('kind', None) == 'lowsun': return "#ffffb0" if item.get('kind', None) == 'terrain': vertlimit = 500 try: margin = item['closestalt'] - mapper.parse_elev(item['elev']) except Exception: return "#0000ff" #Unknown margin, unknown height if item['dist'] > 0.6 / 1.852: return None #Not really too close anyway if margin < 0: return "#ff3030" if margin < vertlimit: return "#ffb0b0" return None dupecheck = dict() for idx, items in byidsorted: for item in items: ident = (item['name'], item['pos'], item.get('elev', None)) dupecheck.setdefault(ident, []).append(item) bestdupe = dict() for ident, dupes in dupecheck.items(): best = min(dupes, key=lambda x: x['dist']) bestdupe[ident] = best for idx, items in byidsorted: cur = [] for item in items: dist_from_a = item['dist_from_a'] dist_from_b = item['dist_from_b'] if abs(dist_from_a) < 0.5: descr = "Near %s" % (item['a'].waypoint, ) elif abs(dist_from_b) < 0.5: descr = "Near %s" % (item['b'].waypoint, ) elif dist_from_a < dist_from_b: descr = "%.0fNM %s of %s" % ( dist_from_a, item['dir_from_a'], item['a'].waypoint) else: descr = "%.0fNM %s of %s" % ( dist_from_b, item['dir_from_b'], item['b'].waypoint) ident = (item['name'], item['pos'], item.get('elev', None)) best = bestdupe[ident] if not (best is item): continue #if ident in seen: continue #seen.add(ident) cur.append( dict( routepointdescr=descr, #dir_from_a=item['dir_from_a'], #fromwhat=fromwhat, kind=item.get('kind', None), bearing=item.get('bearing', None), along_nm=dist_from_a, dist=item['dist'], name=item['name'], closestalt=item['closestalt'], elev=item.get('elev', None))) cur[-1]['color'] = classify(cur[-1]) out.append((items[0]['a'].waypoint, sorted(cur, key=lambda x: x['along_nm']))) c.items = out return render('/obstacles.mako')
def save(self): try: if 'pos' in request.params and 'zoomlevel' in request.params: save_merc_x, save_merc_y = [ int(x) for x in request.params['pos'].split(",") ] save_zoom = int(request.params['zoomlevel']) pos = mapper.merc2latlon((save_merc_x, save_merc_y), save_zoom) self.set_pos_zoom(pos, save_zoom) wps = self.get_waypoints(request.params) oldname = request.params.get('oldtripname', '') tripname = request.params.get('tripname', '') if tripsharing.sharing_active(): #Can't rename trips while tripsharing is active! tripname = session['current_trip'] if oldname != session['current_trip']: #In some strange way a non-tripsharing oldname appeared in the post. This #means that something has gone awry. Don't save! print "Bad trip oldname while tripsharing active!" return "notok" if 'showarea' in request.params and request.params['showarea']: sha = request.params['showarea'] if (sha == '.'): session['showarea'] = '' session['showarea_id'] = '' session['showtrack'] = None else: session['showarea'] = sha session['showarea_id'] = md5( sha.encode('utf8')).hexdigest() session['showtrack'] = None session['mapvariant'] = request.params.get('mapvariant', 'airspace') #print "Req:",request.params oldtrip = None if not oldname.strip(): oldname = tripname oldtrips = meta.Session.query(Trip).filter( sa.and_(Trip.user == tripuser(), Trip.trip == oldname)).all() if len(oldtrips) == 1: oldtrip = oldtrips[0] if oldtrip: trip = oldtrip if trip.trip != tripname: if tripsharing.sharing_active(): #attempt to rename someone elses trip! Can't be allowed! set tripname to old name print "Attempt to rename trip while viewing shared trip (tripsharing)" return "notok" else: trip.trip = self.get_free_tripname(tripname) if session[ 'current_trip'] != trip.trip and tripsharing.sharing_active( ): #internal error if we get here - the earlier test for current_trip not changing failed. print "Unexpected tripsharing error #2" return "notok" session['current_trip'] = trip.trip else: if tripsharing.sharing_active(): #we use sharing, but the shared trip can't be found! print "Tripsharing active, but named trip didn't exist (deleted, probably)" return "notok" tripname = self.get_free_tripname(tripname) trip = Trip(tripuser(), tripname) acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.user == tripuser())).all() if len(acs): trip.aircraft = acs[0].aircraft meta.Session.add(trip) session['current_trip'] = tripname oldwps = set([(wp.id) for wp in meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == trip.trip)).all()]) newwps = set(wps.keys()) #print "NEW WPS",wps removed = oldwps.difference(newwps) added = newwps.difference(oldwps) updated = newwps.intersection(oldwps) print "Removed: ", removed addedwps = added removedwps = removed updatedwps = updated ordering2wpid = dict() for remord in removed: meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == trip.trip, Waypoint.id == remord)).delete() #print "\n\n====DELETING!=====\n%s\n\n"%(rem,) resultant_by_order = dict() resultant_id2order = dict() waypointlink = dict() for add in added: wp = wps[add] waypoint = Waypoint(tripuser(), trip.trip, wp['pos'], int(wp['id']), int(wp['ordering']), wp['name'], wp['altitude']) resultant_by_order[int(wp['ordering'])] = waypoint resultant_id2order[int(wp['id'])] = wp['ordering'] #print "\n\n====ADDING!=====\n%s %s %s\n\n"%(waypoint.id,waypoint.pos,waypoint.waypoint) meta.Session.add(waypoint) for upd in updated: wp = wps[upd] us = meta.Session.query(Waypoint).filter( sa.and_(Waypoint.user == tripuser(), Waypoint.trip == trip.trip, Waypoint.id == upd)).all() if len(us) > 0: u = us[0] prevpos = mapper.from_str(u.pos) newpos = mapper.from_str(wp['pos']) approxdist = (prevpos[0] - newpos[0])**2 + (prevpos[1] - newpos[1])**2 if approxdist > ( 1.0 / 36000.0 )**2: #if moved more than 0.1 arc-second, otherwise leave be. u.pos = wp['pos'] print "Waypoint %d moved! (%f deg)" % ( u.id, math.sqrt(approxdist)) else: print "Waypoint %d has only moved a little (%f deg)" % ( u.id, math.sqrt(approxdist)) u.waypoint = wp['name'] assert u.id == int(wp['id']) u.ordering = wp['ordering'] u.altitude = wp['altitude'] resultant_by_order[int(wp['ordering'])] = u resultant_id2order[int(wp['id'])] = wp['ordering'] #print "\n\n====UPDATING!=====\n%s %s %s\n\n"%(u.id,u.pos,u.waypoint) #print "Resultant by ordering: %s"%(resultant_by_order,) seq = list(sorted(resultant_by_order.items())) newroutes = set() for (ord1, waypoint1), (ord2, waypoint2) in zip(seq[:-1], seq[1:]): if not int(ord1) + 1 == int(ord2): print "Waypoints %s and %s not consecutive (#%d, #%d)" % ( waypoint1, waypoint2, int(ord1), int(ord2)) assert int(ord1) + 1 == int(ord2) newroutes.add((waypoint1.id, waypoint2.id)) oldrouteobjs = list( meta.Session.query(Route).filter( sa.and_(Route.user == tripuser(), Route.trip == trip.trip)).all()) oldroutes = set([(route.waypoint1, route.waypoint2) for route in oldrouteobjs]) prevalts = dict() for rt in oldrouteobjs: prevalts[(rt.a.id, +1)] = rt.altitude prevalts[(rt.b.id, -1)] = rt.altitude #Routes: removed = oldroutes.difference(newroutes) added = newroutes.difference(oldroutes) updated = newroutes.intersection(oldroutes) print "Removed routes:", removed print "Added routes:", added print "Kept routes: ", updated for rem1, rem2 in removed: meta.Session.query(Route).filter( sa.and_(Route.user == tripuser(), Route.trip == trip.trip, Route.waypoint1 == rem1, Route.waypoint2 == rem2)).delete() sel_acs = meta.Session.query(Aircraft).filter( sa.and_(Aircraft.aircraft == trip.aircraft, Aircraft.user == tripuser())).all() if len(sel_acs): tas = sel_acs[0].cruise_speed else: tas = 75 for a1, a2 in added: cruisealt = "" a = None if a1 in addedwps: startord = resultant_id2order.get(int(a1), 0) elif a2 in addedwps: startord = resultant_id2order.get(int(a2), 0) else: startord = resultant_id2order.get(int(a1), 0) print "Ordering of new wp: %d is %d" % (a1, startord) num_waypoints = len(resultant_by_order) def searchpattern(begin, num): assert begin >= 0 and begin < num down = begin - 1 up = begin + 1 while True: work = False if down >= 0: yield down down -= 1 work = True if up < num: yield up up += 1 work = True if not work: break for wpord in searchpattern(startord, num_waypoints): wp = resultant_by_order.get(wpord, None) print "Searchpattern visiting order: %d" % (wpord, ) if wp: if wpord < startord: cruisealt = prevalts.get((wp.id, +1), '') print "Looking for alt previously after wp %d, got: %s" % ( wp.id, cruisealt) else: cruisealt = prevalts.get((wp.id, -1), '') print "Looking for alt previously before wp %d, got: %s" % ( wp.id, cruisealt) if cruisealt != "": break if cruisealt == "": cruisealt = "1500" r = Route(tripuser(), trip.trip, a1, a2, 0, 0, tas, None, cruisealt) meta.Session.add(r) session.save() meta.Session.flush() meta.Session.commit() ret = json.dumps([tripname]) print "mapview returning json:", ret return ret except Exception, cause: #print line number and stuff as well print cause #TODO: ONLY FOR TESTING!!!! raise return "notok"