Ejemplo n.º 1
0
def mavlink_packet(m):
    '''handle an incoming mavlink packet'''
    state = mpstate.antenna_state
    #If ground control station location is not set and waypoints exist, then
    #set the ground control station location to the first waypoint
    if state.gcs_location is None and mpstate.status.wploader.count() > 0:
        home = mpstate.status.wploader.wp(0)
        mpstate.antenna_state.gcs_location = (home.x, home.y)
        print("Antenna home set")
    #Bail out if the ground control station location is not set
    if state.gcs_location is None:
        return
    #If this is a GPS_RAW mavlink packet, then determine the bearing to the plane
    if m.get_type() == 'GPS_RAW' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
    #If this is a GPS_RAW_INT mavlink packet, then determine the bearing to the plane        
    elif m.get_type() == 'GPS_RAW_INT' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat/1.0e7, m.lon/1.0e7)
    else:
        return
    mpstate.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
    #If the bearing is different by 5 degrees and 15 seconds have elapsed, then
    #mention the antenna bearing.
    if abs(bearing - state.last_bearing) > 5 and (time.time() - state.last_announce) > 15:
        state.last_bearing = bearing
        state.last_announce = time.time()
        mpstate.functions.say("Antenna %u" % int(bearing+0.5))
Ejemplo n.º 2
0
    def mavlink_packet(self, m):
        '''handle mavlink packets'''
        if m.get_type() == 'GLOBAL_POSITION_INT':
            bearing = cuav_util.gps_bearing(self.simpletracker_settings.lat, self.simpletracker_settings.long,
                                            m.lat * 1E-7, m.lon * 1E-7)

            ecef = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84')
            lla = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84')

            long_deg = m.lon * 1E-7
            lat_deg = m.lat * 1E-7
            alt_m = m.alt * 1E-3
            uav_x, uav_y, uav_z = pyproj.transform(lla, ecef, long_deg, lat_deg, alt_m, radians=False)
            gcs_x, gcs_y, gcs_z = pyproj.transform(lla, ecef, self.simpletracker_settings.long,
                                                   self.simpletracker_settings.lat, self.simpletracker_settings.alt,
                                                   radians=False)
            # print uav_x, uav_y, uav_z
            dx = uav_x - gcs_x
            dy = uav_y - gcs_y
            dz = uav_z - gcs_z
            cos_el = (gcs_x * dx + gcs_y * dy + gcs_z * dz) / math.sqrt(
                (gcs_x ** 2 + gcs_y ** 2 + gcs_z ** 2) * (dx ** 2 + dy ** 2 + dz ** 2))
            elevation_deg = 90 - math.degrees(math.acos(cos_el))
            # self.say("UAV at Lat: %f, Long: %f , Alt: %f, CGS Az: %f , El: %f" % (lat_deg, long_deg,alt_m, bearing, elevation_deg))
            self.lock.acquire()
            # update angles
            self.azimuth_deg = bearing
            self.elevation_deg = elevation_deg
            self.lock.release()
Ejemplo n.º 3
0
    def projectBearing(self, bearing, startPos, searchArea):
        '''Projects bearing from startPos until it reaches the edge(s) of
        searchArea (list of lat/long tuples. Returns the First/Last position(s)'''

        coPoints = []

        #for each line in the search are border, get any overlaps with startPos on bearing(+-180)
        for point in searchArea:
            dist = cuav_util.gps_distance(point[0], point[1], searchArea[searchArea.index(point)-1][0], searchArea[searchArea.index(point)-1][1])
            theta2 = cuav_util.gps_bearing(point[0], point[1], searchArea[searchArea.index(point)-1][0], searchArea[searchArea.index(point)-1][1])
            posn = self.Intersection(startPos, bearing, point, theta2)
            if posn != 0 and cuav_util.gps_distance(posn[0], posn[1], point[0], point[1]) < dist:
                coPoints.append(posn)
            posn = self.Intersection(startPos, (bearing + 180) % 360, point, theta2)
            if posn != 0 and cuav_util.gps_distance(posn[0], posn[1], point[0], point[1]) < dist:
                coPoints.append(posn)

        #if there's more than two points in coPoints, return the furthest away points
        if len(coPoints) < 2:
            #print str(len(coPoints)) + " point i-sect"
            return 0
        elif len(coPoints) == 2:
            return coPoints
        else:
            dist = 0
            for point in coPoints:
                for pt in coPoints:
                    if cuav_util.gps_distance(pt[0], pt[1], point[0], point[1]) > dist:
                        dist = cuav_util.gps_distance(pt[0], pt[1], point[0], point[1])
                        newcoPoints = [point, pt]
            return newcoPoints
Ejemplo n.º 4
0
 def mavlink_packet(self, m):
     '''handle an incoming mavlink packet'''
     if self.gcs_location is None and self.module('wp').wploader.count() > 0:
         home = self.module('wp').get_home()
         self.gcs_location = (home.x, home.y)
         print("Antenna home set")
     if self.gcs_location is None:
         return
     if m.get_type() == 'GPS_RAW' and self.gcs_location is not None:
         (gcs_lat, gcs_lon) = self.gcs_location
         bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
     elif m.get_type() == 'GPS_RAW_INT' and self.gcs_location is not None:
         (gcs_lat, gcs_lon) = self.gcs_location
         bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat / 1.0e7, m.lon / 1.0e7)
     else:
         return
     self.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
     if abs(bearing - self.last_bearing) > 5 and (time.time() - self.last_announce) > 15:
         self.last_bearing = bearing
         self.last_announce = time.time()
         self.say("Antenna %u" % int(bearing + 0.5))
Ejemplo n.º 5
0
 def mavlink_packet(self, m):
     """handle an incoming mavlink packet"""
     if self.gcs_location is None and self.module("wp").wploader.count() > 0:
         home = self.module("wp").wploader.wp(0)
         self.gcs_location = (home.x, home.y)
         print("Antenna home set")
     if self.gcs_location is None:
         return
     if m.get_type() == "GPS_RAW" and self.gcs_location is not None:
         (gcs_lat, gcs_lon) = self.gcs_location
         bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
     elif m.get_type() == "GPS_RAW_INT" and self.gcs_location is not None:
         (gcs_lat, gcs_lon) = self.gcs_location
         bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat / 1.0e7, m.lon / 1.0e7)
     else:
         return
     self.console.set_status("Antenna", "Antenna %.0f" % bearing, row=0)
     if abs(bearing - self.last_bearing) > 5 and (time.time() - self.last_announce) > 15:
         self.last_bearing = bearing
         self.last_announce = time.time()
         self.say("Antenna %u" % int(bearing + 0.5))
Ejemplo n.º 6
0
def mavlink_packet(m):
    '''handle an incoming mavlink packet'''
    state = mpstate.antenna_state
    if state.gcs_location is None and mpstate.status.wploader.count() > 0:
        home = mpstate.status.wploader.wp(0)
        mpstate.antenna_state.gcs_location = (home.x, home.y)
        print("Antenna home set")
    if state.gcs_location is None:
        return
    if m.get_type() == 'GPS_RAW' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
    elif m.get_type() == 'GPS_RAW_INT' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat/1.0e7, m.lon/1.0e7)
    else:
        return
    mpstate.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
    if abs(bearing - state.last_bearing) > 5 and (time.time() - state.last_announce) > 15:
        state.last_bearing = bearing
        state.last_announce = time.time()
        mpstate.functions.say("Antenna %u" % int(bearing+0.5))
Ejemplo n.º 7
0
def mavlink_packet(m):
    '''handle an incoming mavlink packet'''
    state = mpstate.antenna_state
    if state.gcs_location is None and mpstate.status.wploader.count() > 0:
        home = mpstate.status.wploader.wp(0)
        mpstate.antenna_state.gcs_location = (home.x, home.y)
        print("Antenna home set")
    if state.gcs_location is None:
        return
    if m.get_type() == 'GPS_RAW' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat, m.lon)
    elif m.get_type() == 'GPS_RAW_INT' and state.gcs_location is not None:
        (gcs_lat, gcs_lon) = state.gcs_location
        bearing = cuav_util.gps_bearing(gcs_lat, gcs_lon, m.lat / 1.0e7,
                                        m.lon / 1.0e7)
    else:
        return
    mpstate.console.set_status('Antenna', 'Antenna %.0f' % bearing, row=0)
    if abs(bearing - state.last_bearing) > 5 and (time.time() -
                                                  state.last_announce) > 15:
        state.last_bearing = bearing
        state.last_announce = time.time()
        mpstate.functions.say("Antenna %u" % int(bearing + 0.5))
Ejemplo n.º 8
0
def add_points(wp, argagl, argstep, argmaxdelta, argrtlalt):
    '''add more points for terrain following'''
    wplist = []
    wplist2 = []
    for i in range(0, wp.count()):
        wplist.append(wp.wp(i))
    wplist[0].z = argagl

    # add in RTL
    wplist.append(wplist[0])
    
    wplist2.append(wplist[0])

    home = wp.wp(0)
    home_ground = EleModel.GetElevation(home.x, home.y)

    for i in range(1, len(wplist)):
        prev = (wplist2[-1].x, wplist2[-1].y, wplist2[-1].z)
        dist = cuav_util.gps_distance(wplist2[-1].x, wplist2[-1].y, wplist[i].x, wplist[i].y)
        bearing = cuav_util.gps_bearing(wplist2[-1].x, wplist2[-1].y, wplist[i].x, wplist[i].y)
        print("dist=%u bearing=%u" % (dist, bearing))
        while dist > argstep:
            newpos = cuav_util.gps_newpos(prev[0], prev[1], bearing, argstep)
            ground1 = EleModel.GetElevation(prev[0], prev[1])
            ground2 = EleModel.GetElevation(newpos[0], newpos[1])
            if ground2 == None:
                ground2 = home_ground
            
            agl = (home_ground + prev[2]) - ground2
            if abs(agl - argagl) > argmaxdelta:
                newwp = copy.copy(wplist2[-1])
                newwp.x = newpos[0]
                newwp.y = newpos[1]
                newwp.z = (ground2 + argagl) - home_ground
                wplist2.append(newwp)
                print("Inserting at %u" % newwp.z)
                prev = (newpos[0], newpos[1], newwp.z)
            else:
                prev = (newpos[0], newpos[1], wplist2[-1].z)
            dist -= argstep
        wplist2.append(wplist[i])
    wplist2[-1].z = argrtlalt
    wp2 = mavwp.MAVWPLoader()
    for w in wplist2:
        wp2.add(w)
    wp2.save("newwp.txt")
    return wp2
Ejemplo n.º 9
0
def add_points(wp):
    '''add more points for terrain following'''
    wplist = []
    wplist2 = []
    for i in range(0, wp.count()):
        wplist.append(wp.wp(i))
    wplist[0].z = opts.agl

    # add in RTL
    wplist.append(wplist[0])

    wplist2.append(wplist[0])

    home = wp.wp(0)
    home_ground = get_ground_alt(home.x, home.y)

    for i in range(1, len(wplist)):
        prev = (wplist2[-1].x, wplist2[-1].y, wplist2[-1].z)
        dist = cuav_util.gps_distance(wplist2[-1].x, wplist2[-1].y,
                                      wplist[i].x, wplist[i].y)
        bearing = cuav_util.gps_bearing(wplist2[-1].x, wplist2[-1].y,
                                        wplist[i].x, wplist[i].y)
        print("dist=%u bearing=%u" % (dist, bearing))
        while dist > opts.step:
            newpos = cuav_util.gps_newpos(prev[0], prev[1], bearing, opts.step)
            ground1 = get_ground_alt(prev[0], prev[1])
            ground2 = get_ground_alt(newpos[0], newpos[1])
            agl = (home_ground + prev[2]) - ground2
            if abs(agl - opts.agl) > opts.maxdelta:
                newwp = copy.copy(wplist2[-1])
                newwp.x = newpos[0]
                newwp.y = newpos[1]
                newwp.z = (ground2 + opts.agl) - home_ground
                wplist2.append(newwp)
                print("Inserting at %u" % newwp.z)
                prev = (newpos[0], newpos[1], newwp.z)
            else:
                prev = (newpos[0], newpos[1], wplist2[-1].z)
            dist -= opts.step
        wplist2.append(wplist[i])
    wplist2[-1].z = opts.rtlalt
    wp2 = mavwp.MAVWPLoader()
    for w in wplist2:
        wp2.add(w)
    wp2.save("newwp.txt")
    return wp2
Ejemplo n.º 10
0
def exif_position(filename):
        '''get a MavPosition from exif tags

        See: http://stackoverflow.com/questions/10799366/geotagging-jpegs-with-pyexiv2
        '''
        import pyexiv2
        global _last_position
        
        m = pyexiv2.ImageMetadata(filename)
        m.read()
        GPS = 'Exif.GPSInfo.GPS'
        try:
                lat_ns = str(m[GPS + 'LatitudeRef'].value)
                lng_ns = str(m[GPS + 'LongitudeRef'].value)
                latitude = dms_to_decimal(m[GPS + 'Latitude'].value[0],
                                          m[GPS + 'Latitude'].value[1],
                                          m[GPS + 'Latitude'].value[2],
                                          lat_ns)
                longitude = dms_to_decimal(m[GPS + 'Longitude'].value[0],
                                           m[GPS + 'Longitude'].value[1],
                                           m[GPS + 'Longitude'].value[2],
                                           lng_ns)
        except Exception:
                latitude = 0
                longitude = 0
                

        altitude = float(m[GPS + 'Altitude'].value)

        timestamp = (os.path.splitext(os.path.basename(filename))[0])
        m = re.search("\d", timestamp)
        if m :
            timestamp = timestamp[m.start():]
        
        frame_time = datetime.datetime.strptime(timestamp, "%Y%m%d%H%M%S%fZ")
        frame_time = cuav_util.datetime_to_float(frame_time)
        
        if _last_position is None:
                yaw = 0
        else:
                yaw = cuav_util.gps_bearing(_last_position.lat, _last_position.lon,
                                            latitude, longitude)
        pos = MavPosition(latitude, longitude, altitude, 0, 0, yaw, frame_time)
        _last_position = pos
        return pos
Ejemplo n.º 11
0
 def mouse_event_view(self, event):
     '''called on mouse events in View window'''
     x = event.X
     y = event.Y
     if self.current_view >= len(self.images):
         return
     image = self.images[self.current_view]
     latlon = cuav_util.gps_position_from_xy(x, y, image.pos, C=self.c_params, shape=image.shape, altitude=image.pos.altitude)
     if self.last_view_latlon is None or latlon is None:
         dist = ''
     else:
         distance = cuav_util.gps_distance(self.last_view_latlon[0], self.last_view_latlon[1],
                                           latlon[0], latlon[1])
         bearing = cuav_util.gps_bearing(self.last_view_latlon[0], self.last_view_latlon[1],
                                          latlon[0], latlon[1])
         dist = "dist %.1f bearing %.1f alt=%.1f shape=%s" % (distance, bearing, image.pos.altitude, image.shape)
     print("-> %s %s %s" % (latlon, image.filename, dist))
     self.last_view_latlon = latlon
Ejemplo n.º 12
0
def add_points(wp):
    """add more points for terrain following"""
    wplist = []
    wplist2 = []
    for i in range(0, wp.count()):
        wplist.append(wp.wp(i))
    wplist[0].z = opts.agl

    # add in RTL
    wplist.append(wplist[0])

    wplist2.append(wplist[0])

    home = wp.wp(0)
    home_ground = get_ground_alt(home.x, home.y)

    for i in range(1, len(wplist)):
        prev = (wplist2[-1].x, wplist2[-1].y, wplist2[-1].z)
        dist = cuav_util.gps_distance(wplist2[-1].x, wplist2[-1].y, wplist[i].x, wplist[i].y)
        bearing = cuav_util.gps_bearing(wplist2[-1].x, wplist2[-1].y, wplist[i].x, wplist[i].y)
        print("dist=%u bearing=%u" % (dist, bearing))
        while dist > opts.step:
            newpos = cuav_util.gps_newpos(prev[0], prev[1], bearing, opts.step)
            ground1 = get_ground_alt(prev[0], prev[1])
            ground2 = get_ground_alt(newpos[0], newpos[1])
            agl = (home_ground + prev[2]) - ground2
            if abs(agl - opts.agl) > opts.maxdelta:
                newwp = copy.copy(wplist2[-1])
                newwp.x = newpos[0]
                newwp.y = newpos[1]
                newwp.z = (ground2 + opts.agl) - home_ground
                wplist2.append(newwp)
                print("Inserting at %u" % newwp.z)
                prev = (newpos[0], newpos[1], newwp.z)
            else:
                prev = (newpos[0], newpos[1], wplist2[-1].z)
            dist -= opts.step
        wplist2.append(wplist[i])
    wplist2[-1].z = opts.rtlalt
    wp2 = mavwp.MAVWPLoader()
    for w in wplist2:
        wp2.add(w)
    wp2.save("newwp.txt")
    return wp2
Ejemplo n.º 13
0
def exif_position(filename):
        '''get a MavPosition from exif tags

        See: http://stackoverflow.com/questions/10799366/geotagging-jpegs-with-pyexiv2
        '''
        import pyexiv2
        global _last_position
        
        m = pyexiv2.ImageMetadata(filename)
        m.read()
        GPS = 'Exif.GPSInfo.GPS'
        try:
                lat_ns = str(m[GPS + 'LatitudeRef'].value)
                lng_ns = str(m[GPS + 'LongitudeRef'].value)
                latitude = dms_to_decimal(m[GPS + 'Latitude'].value[0],
                                          m[GPS + 'Latitude'].value[1],
                                          m[GPS + 'Latitude'].value[2],
                                          lat_ns)
                longitude = dms_to_decimal(m[GPS + 'Longitude'].value[0],
                                           m[GPS + 'Longitude'].value[1],
                                           m[GPS + 'Longitude'].value[2],
                                           lng_ns)
        except Exception:
                latitude = 0
                longitude = 0
                
        try:
                altitude = float(m[GPS + 'Altitude'].value) - get_ground_alt(latitude, longitude)
        except Exception:
                altitude = -1

        try:
                t = time.mktime(m['Exif.Image.DateTime'].value.timetuple())
        except Exception:
                t = os.path.getmtime(filename)
        if _last_position is None:
                yaw = 0
        else:
                yaw = cuav_util.gps_bearing(_last_position.lat, _last_position.lon,
                                            latitude, longitude)
        pos = MavPosition(latitude, longitude, altitude, 0, 0, yaw, t)
        _last_position = pos
        return pos
Ejemplo n.º 14
0
def exif_position(filename):
        '''get a MavPosition from exif tags

        See: http://stackoverflow.com/questions/10799366/geotagging-jpegs-with-pyexiv2
        '''
        import pyexiv2
        global _last_position
        
        m = pyexiv2.ImageMetadata(filename)
        m.read()
        try:
                GPS = 'Exif.GPSInfo.GPS'
                lat_ns = str(m[GPS + 'LatitudeRef'].value)
                lng_ns = str(m[GPS + 'LongitudeRef'].value)
                latitude = dms_to_decimal(m[GPS + 'Latitude'].value[0],
                                          m[GPS + 'Latitude'].value[1],
                                          m[GPS + 'Latitude'].value[2],
                                          lat_ns)
                longitude = dms_to_decimal(m[GPS + 'Longitude'].value[0],
                                           m[GPS + 'Longitude'].value[1],
                                           m[GPS + 'Longitude'].value[2],
                                           lng_ns)
        except Exception:
                latitude = 0
                longitude = 0
                
        try:
                altitude = float(m[GPS + 'Altitude'].value)
        except Exception:
                altitude = -1

        try:
                t = time.mktime(m['Exif.Image.DateTime'].value.timetuple())
        except Exception:
                t = os.path.getmtime()
        if _last_position is None:
                yaw = 0
        else:
                yaw = cuav_util.gps_bearing(_last_position.lat, _last_position.lon,
                                            latitude, longitude)
        pos = MavPosition(latitude, longitude, altitude, 0, 0, yaw, t)
        _last_position = pos
        return pos
Ejemplo n.º 15
0
def exif_position(filename):
    '''get a MavPosition from exif tags

        See: http://stackoverflow.com/questions/10799366/geotagging-jpegs-with-pyexiv2
        '''
    import pyexiv2
    global _last_position

    m = pyexiv2.ImageMetadata(filename)
    m.read()
    GPS = 'Exif.GPSInfo.GPS'
    try:
        lat_ns = str(m[GPS + 'LatitudeRef'].value)
        lng_ns = str(m[GPS + 'LongitudeRef'].value)
        latitude = dms_to_decimal(m[GPS + 'Latitude'].value[0],
                                  m[GPS + 'Latitude'].value[1],
                                  m[GPS + 'Latitude'].value[2], lat_ns)
        longitude = dms_to_decimal(m[GPS + 'Longitude'].value[0],
                                   m[GPS + 'Longitude'].value[1],
                                   m[GPS + 'Longitude'].value[2], lng_ns)
    except Exception:
        latitude = 0
        longitude = 0

    altitude = float(m[GPS + 'Altitude'].value)

    timestamp = (os.path.splitext(os.path.basename(filename))[0])
    m = re.search("\d", timestamp)
    if m:
        timestamp = timestamp[m.start():]

    frame_time = datetime.datetime.strptime(timestamp, "%Y%m%d%H%M%S%fZ")
    frame_time = cuav_util.datetime_to_float(frame_time)

    if _last_position is None:
        yaw = 0
    else:
        yaw = cuav_util.gps_bearing(_last_position.lat, _last_position.lon,
                                    latitude, longitude)
    pos = MavPosition(latitude, longitude, altitude, 0, 0, yaw, frame_time)
    _last_position = pos
    return pos
Ejemplo n.º 16
0
    def projectBearing(self, bearing, startPos, searchArea):
        '''Projects bearing from startPos until it reaches the edge(s) of
        searchArea (list of lat/long tuples. Returns the First/Last position(s)'''

        coPoints = []

        #for each line in the search are border, get any overlaps with startPos on bearing(+-180)
        for point in searchArea:
            dist = cuav_util.gps_distance(
                point[0], point[1], searchArea[searchArea.index(point) - 1][0],
                searchArea[searchArea.index(point) - 1][1])
            theta2 = cuav_util.gps_bearing(
                point[0], point[1], searchArea[searchArea.index(point) - 1][0],
                searchArea[searchArea.index(point) - 1][1])
            posn = self.Intersection(startPos, bearing, point, theta2)
            if posn != 0 and cuav_util.gps_distance(posn[0], posn[1], point[0],
                                                    point[1]) < dist:
                coPoints.append(posn)
            posn = self.Intersection(startPos, (bearing + 180) % 360, point,
                                     theta2)
            if posn != 0 and cuav_util.gps_distance(posn[0], posn[1], point[0],
                                                    point[1]) < dist:
                coPoints.append(posn)

        #if there's more than two points in coPoints, return the furthest away points
        if len(coPoints) < 2:
            #print str(len(coPoints)) + " point i-sect"
            return 0
        elif len(coPoints) == 2:
            return coPoints
        else:
            dist = 0
            for point in coPoints:
                for pt in coPoints:
                    if cuav_util.gps_distance(pt[0], pt[1], point[0],
                                              point[1]) > dist:
                        dist = cuav_util.gps_distance(pt[0], pt[1], point[0],
                                                      point[1])
                        newcoPoints = [point, pt]
            return newcoPoints
Ejemplo n.º 17
0
    def update_mission(self):
        '''update mission status'''
        if not self.cuav_settings.auto_mission:
            return
        wpmod = self.module('wp')
        wploader = wpmod.wploader
        if wploader.count(
        ) < 2 and self.last_attitude_ms - self.last_wp_list_ms > 5000:
            self.last_wp_list_ms = self.last_attitude_ms
            wpmod.cmd_wp(["list"])

        wp_start = self.find_user_wp(wploader, self.cuav_settings.wp_start)
        wp_center = self.find_user_wp(wploader, self.cuav_settings.wp_center)
        wp_end = self.find_user_wp(wploader, self.cuav_settings.wp_end)

        if (wp_center is None or wp_start is None or wp_end is None):
            # not configured
            return

        # run every 5 seconds
        if self.last_attitude_ms - self.last_mission_check_ms < 5000:
            return
        self.last_mission_check_ms = self.last_attitude_ms

        if self.updated_waypoints:
            cam = self.module('camera_air')
            if wpmod.loading_waypoints:
                self.send_message("listing waypoints")
                wpmod.cmd_wp(["list"])
            else:
                self.send_message("sending waypoints")
                self.updated_waypoints = False
                wploader.save("newwp.txt")
                cam.send_file("newwp.txt")

        if self.started_landing:
            # no more to do
            return

        if self.last_attitude_ms - self.last_wp_move_ms < 2 * 60 * 1000:
            # only move waypoints every 2 minutes
            return

        try:
            cam = self.module('camera_air')
            lz = cam.lz
            target_latitude = cam.camera_settings.target_latitude
            target_longitude = cam.camera_settings.target_longitude
            target_radius = cam.camera_settings.target_radius
        except Exception:
            self.send_message("target not set")
            return

        lzresult = lz.calclandingzone()
        if lzresult is None:
            return

        self.send_message("lzresult nr:%u avgscore:%u" %
                          (lzresult.numregions, lzresult.avgscore))

        if lzresult.numregions < 5 and lzresult.avgscore < 20000:
            # only accept short lists if they have high scores
            return

        (lat, lon) = lzresult.latlon
        # check it is within the target radius
        if target_radius > 0:
            dist = cuav_util.gps_distance(lat, lon, target_latitude,
                                          target_longitude)
            self.send_message("dist %u" % dist)
            if dist > target_radius:
                return
            # don't move more than 70m from the center of the search, this keeps us
            # over more of the search area, and further from the fence
            max_move = target_radius
            if self.wp_move_count == 0:
                # don't move more than 50m from center on first move
                max_move = 35
            if self.wp_move_count == 1:
                # don't move more than 80m from center on 2nd move
                max_move = 80
            if dist > max_move:
                bearing = cuav_util.gps_bearing(target_latitude,
                                                target_longitude, lat, lon)
                (lat, lon) = cuav_util.gps_newpos(target_latitude,
                                                  target_longitude, bearing,
                                                  max_move)

        # we may need to fetch the wp list
        if self.last_attitude_ms - self.last_wp_list_ms > 120000 or wpmod.loading_waypoints:
            self.last_wp_list_ms = self.last_attitude_ms
            self.send_message("fetching waypoints")
            wpmod.cmd_wp(["list"])
            return

        self.last_wp_move_ms = self.last_attitude_ms
        self.wp_move_count += 1
        self.send_message("Moving search to: (%f,%f) %u" %
                          (lat, lon, self.wp_move_count))
        wpmod.cmd_wp_movemulti([wp_center, wp_start, wp_end], (lat, lon))

        wp_land = self.find_user_wp(wploader, self.cuav_settings.wp_land)
        if (wp_land is not None and self.wp_move_count >= 3
                and lzresult.numregions > 10
                and self.master.flightmode == "AUTO"):
            self.send_message("Starting landing")
            self.master.waypoint_set_current_send(wp_land)
            self.started_landing = True
        self.updated_waypoints = True
Ejemplo n.º 18
0
    def altitudeCompensation(self, heightAGL, numMaxPoints=100, threshold=5):
        '''Creates height points (ASL) for each point in searchArea,
        entry and exit points such that the plane stays a constant altitude above the ground,
        constrained by a max number of waypoints'''
        maxDeltaAlt = 0
        maxDeltaAltPoints = []
        maxDeltapercentAlong = 0

        EleModel = mp_elevation.ElevationModel()
        #make sure the SRTM tiles are downloaded
        EleModel.GetElevation(self.SearchPattern[0][0],
                              self.SearchPattern[0][1])

        #get the ASL height of the airfield home, entry and exit points and initial search pattern
        # and add the heightAGL to them
        self.airportHeight = EleModel.GetElevation(self.airfieldHome[0],
                                                   self.airfieldHome[1])
        if abs(opts.basealt - self.airportHeight) > 30:
            print("BAD BASE ALTITUDE %u - airfieldhome %u" %
                  (opts.basealt, self.airportHeight))
            sys.exit(1)
        self.airportHeight = opts.basealt
        self.airfieldHome = (self.airfieldHome[0], self.airfieldHome[1],
                             heightAGL + opts.basealt)

        for point in self.entryPoints:
            self.entryPoints[self.entryPoints.index(point)] = (
                point[0], point[1],
                heightAGL + 10 + EleModel.GetElevation(point[0], point[1]))

        for point in self.exitPoints:
            self.exitPoints[self.exitPoints.index(point)] = (
                point[0], point[1],
                heightAGL + 10 + EleModel.GetElevation(point[0], point[1]))

        for point in self.SearchPattern:
            self.SearchPattern[self.SearchPattern.index(point)] = (
                point[0], point[1],
                heightAGL + EleModel.GetElevation(point[0], point[1]))

        #keep looping through the search area waypoints and add new waypoints where needed
        #to maintain const height above terrain
        print "---Starting terrain tracking optimisation---"
        while True:
            maxDeltaAlt = 0
            maxDeltaAltPoints = []
            maxDeltaPointIndex = 0

            for point in self.SearchPattern:
                if point != self.SearchPattern[-1]:
                    dist = cuav_util.gps_distance(
                        point[0], point[1],
                        self.SearchPattern[self.SearchPattern.index(point) +
                                           1][0],
                        self.SearchPattern[self.SearchPattern.index(point) +
                                           1][1])
                    theta = cuav_util.gps_bearing(
                        point[0], point[1],
                        self.SearchPattern[self.SearchPattern.index(point) +
                                           1][0],
                        self.SearchPattern[self.SearchPattern.index(point) +
                                           1][1])
                    AltDiff = float(self.SearchPattern[
                        self.SearchPattern.index(point) + 1][2] - point[2])

                    if numpy.around(theta) == numpy.around(
                            self.searchBearing) or numpy.around(
                                theta) == numpy.around(
                                    (self.searchBearing + 180) % 360):
                        #increment 10% along waypoint-to-waypoint and get max height difference
                        for i in range(1, 9):
                            partPoint = cuav_util.gps_newpos(
                                point[0], point[1], theta, (i * dist / 10))
                            partAlt = EleModel.GetElevation(
                                partPoint[0], partPoint[1]) + heightAGL
                            #print "Part = " + str(partAlt) + ", Orig = " + str(point[2])
                            if numpy.abs(point[2] + (
                                (AltDiff * i) / 10) - partAlt) > maxDeltaAlt:
                                maxDeltaAlt = numpy.abs(point[2] +
                                                        ((AltDiff * i) / 10) -
                                                        partAlt)
                                maxDeltaAltPoint = (partPoint[0], partPoint[1],
                                                    partAlt)
                                maxDeltaPointIndex = self.SearchPattern.index(
                                    point) + 1
                                #print "New max alt diff: " + str(maxDeltaAlt) + ", " + str(partAlt)
            #now put a extra waypoint in between the two maxDeltaAltPoints
            if maxDeltaAltPoint is not None:
                self.SearchPattern.insert(maxDeltaPointIndex, maxDeltaAltPoint)
            #print "There are " + str(len(self.SearchPattern)) + " points in the search pattern. Max Alt error is " + str(maxDeltaAlt)
            if len(self.SearchPattern
                   ) >= numMaxPoints or threshold > maxDeltaAlt:
                break
        print "---Done terrain tracking optimisation---"
Ejemplo n.º 19
0
    def CreateSearchPattern(self,
                            width=50.0,
                            overlap=10.0,
                            offset=10,
                            wobble=10,
                            alt=100):
        '''Generate the waypoints for the search pattern, using alternating strips
        width is the width (m) of each strip, overlap is the % overlap between strips, 
        alt is the altitude (relative to ground) of the points'''
        self.SearchPattern = []

        #find the nearest point to Airfield Home - use this as a starting point (if entry lanes are not used)
        if len(self.entryPoints) == 0:
            nearestdist = cuav_util.gps_distance(self.airfieldHome[0],
                                                 self.airfieldHome[1],
                                                 self.searchArea[0][0],
                                                 self.searchArea[0][1])
            nearest = self.searchArea[0]
            for point in self.searchArea:
                newdist = cuav_util.gps_distance(self.airfieldHome[0],
                                                 self.airfieldHome[1],
                                                 point[0], point[1])
                if newdist < nearestdist:
                    nearest = point
                    nearestdist = newdist
        else:
            nearestdist = cuav_util.gps_distance(self.entryPoints[0][0],
                                                 self.entryPoints[0][1],
                                                 self.searchArea[0][0],
                                                 self.searchArea[0][1])
            nearest = self.searchArea[0]
            for point in self.searchArea:
                newdist = cuav_util.gps_distance(self.entryPoints[0][0],
                                                 self.entryPoints[0][1],
                                                 point[0], point[1])
                #print "dist = " + str(newdist)
                if newdist < nearestdist:
                    nearest = point
                    nearestdist = newdist

        #print "Start = " + str(nearest) + ", dist = " + str(nearestdist)

        #the search pattern will run between the longest side from nearest
        bearing1 = cuav_util.gps_bearing(
            nearest[0], nearest[1],
            self.searchArea[self.searchArea.index(nearest) - 1][0],
            self.searchArea[self.searchArea.index(nearest) - 1][1])
        bearing2 = cuav_util.gps_bearing(
            nearest[0], nearest[1],
            self.searchArea[self.searchArea.index(nearest) + 1][0],
            self.searchArea[self.searchArea.index(nearest) + 1][1])
        dist1 = cuav_util.gps_distance(
            nearest[0], nearest[1],
            self.searchArea[self.searchArea.index(nearest) - 1][0],
            self.searchArea[self.searchArea.index(nearest) - 1][1])
        dist2 = cuav_util.gps_distance(
            nearest[0], nearest[1],
            self.searchArea[self.searchArea.index(nearest) + 1][0],
            self.searchArea[self.searchArea.index(nearest) + 1][1])
        if dist1 > dist2:
            self.searchBearing = bearing1
        else:
            self.searchBearing = bearing2

        #the search pattern will then run parallel between the two furthest points in the list
        #searchLine = (0, 0)
        #for point in self.searchArea:
        #    newdist = cuav_util.gps_distance(point[0], point[1], self.searchArea[self.searchArea.index(point)-1][0], self.searchArea[self.searchArea.index(point)-1][1])
        #    if newdist > searchLine[0]:
        #        searchLine = (newdist, cuav_util.gps_bearing(point[0], point[1], self.searchArea[self.searchArea.index(point)-1][0], self.searchArea[self.searchArea.index(point)-1][1]))

        #self.searchBearing = searchLine[1]

        #need to find the 90 degree bearing to searchBearing that is inside the search area. This
        #will be the bearing we increment the search rows by
        #need to get the right signs for the bearings, depending which quadrant the search area is in wrt nearest
        if not cuav_util.polygon_outside(
                cuav_util.gps_newpos(nearest[0], nearest[1],
                                     (self.searchBearing + 45) % 360, 10),
                self.searchArea):
            self.crossBearing = (self.searchBearing + 90) % 360
        elif not cuav_util.polygon_outside(
                cuav_util.gps_newpos(nearest[0], nearest[1],
                                     (self.searchBearing + 135) % 360, 10),
                self.searchArea):
            self.crossBearing = (self.searchBearing + 90) % 360
            self.searchBearing = (self.searchBearing + 180) % 360
        elif not cuav_util.polygon_outside(
                cuav_util.gps_newpos(nearest[0], nearest[1],
                                     (self.searchBearing - 45) % 360, 10),
                self.searchArea):
            self.crossBearing = (self.searchBearing - 90) % 360
        else:
            self.crossBearing = (self.searchBearing - 90) % 360
            self.searchBearing = (self.searchBearing - 180) % 360

        print "Search bearing is " + str(self.searchBearing) + "/" + str(
            (self.searchBearing + 180) % 360)
        print "Cross bearing is: " + str(self.crossBearing)

        #the distance between runs is this:
        self.deltaRowDist = width - width * (float(overlap) / 100)
        if self.deltaRowDist <= 0:
            print "Error, overlap % is too high"
            return
        print "Delta row = " + str(self.deltaRowDist)

        #expand the search area to 1/2 deltaRowDist to ensure full coverage

        #we are starting at the "nearest" and mowing the lawn parallel to "self.searchBearing"
        #first waypoint is right near the Search Area boundary (without being on it) (10% of deltaRowDist
        #on an opposite bearing (so behind the search area)
        nextWaypoint = cuav_util.gps_newpos(nearest[0], nearest[1],
                                            self.crossBearing,
                                            self.deltaRowDist / 10)
        print "First = " + str(nextWaypoint)
        #self.SearchPattern.append(firstWaypoint)

        #mow the lawn, every 2nd row:
        while True:
            pts = self.projectBearing(self.searchBearing, nextWaypoint,
                                      self.searchArea)
            #print "Projecting " + str(nextWaypoint) + " along " + str(self.searchBearing)
            #check if we're outside the search area
            if pts == 0:
                break
            (nextW, nextnextW) = (pts[0], pts[1])
            if cuav_util.gps_distance(
                    nextWaypoint[0], nextWaypoint[1],
                    nextW[0], nextW[1]) < cuav_util.gps_distance(
                        nextWaypoint[0], nextWaypoint[1], nextnextW[0],
                        nextnextW[1]):
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextW[0], nextW[1],
                                         (self.searchBearing + 180) % 360,
                                         (offset + wobble)))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                         self.searchBearing,
                                         (offset + wobble)))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                                    self.crossBearing,
                                                    self.deltaRowDist * 2)
                self.searchBearing = (self.searchBearing + 180) % 360
            else:
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                         (self.searchBearing + 180) % 360,
                                         offset + wobble))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextW[0], nextW[1],
                                         self.searchBearing,
                                         (offset + wobble)))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextW[0], nextW[1],
                                                    self.crossBearing,
                                                    self.deltaRowDist * 2)
                self.searchBearing = (self.searchBearing + 180) % 360

            print "Next = " + str(nextWaypoint)

        #go back and do the rows we missed. There still might be one more row to do in
        # the crossbearing direction, so check for that first
        nextWaypoint = cuav_util.gps_newpos(nextWaypoint[0], nextWaypoint[1],
                                            self.crossBearing,
                                            -self.deltaRowDist)
        pts = self.projectBearing(self.searchBearing, nextWaypoint,
                                  self.searchArea)
        if pts == 0:
            nextWaypoint = cuav_util.gps_newpos(nextWaypoint[0],
                                                nextWaypoint[1],
                                                self.crossBearing,
                                                -2 * self.deltaRowDist)
            self.crossBearing = (self.crossBearing + 180) % 360
        else:
            self.crossBearing = (self.crossBearing + 180) % 360

        while True:
            pts = self.projectBearing(self.searchBearing, nextWaypoint,
                                      self.searchArea)
            #print "Projecting " + str(nextWaypoint) + " along " + str(self.searchBearing)
            #check if we're outside the search area
            if pts == 0:
                break
            (nextW, nextnextW) = (pts[0], pts[1])
            if cuav_util.gps_distance(
                    nextWaypoint[0], nextWaypoint[1],
                    nextW[0], nextW[1]) < cuav_util.gps_distance(
                        nextWaypoint[0], nextWaypoint[1], nextnextW[0],
                        nextnextW[1]):
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextW[0], nextW[1],
                                         (self.searchBearing + 180) % 360,
                                         offset))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                         self.searchBearing, offset))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                                    self.crossBearing,
                                                    self.deltaRowDist * 2)
                self.searchBearing = (self.searchBearing + 180) % 360
            else:
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextnextW[0], nextnextW[1],
                                         (self.searchBearing + 180) % 360,
                                         offset))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(
                    cuav_util.gps_newpos(nextW[0], nextW[1],
                                         self.searchBearing, offset))
                self.SearchPattern[-1] = (self.SearchPattern[-1][0],
                                          self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextW[0], nextW[1],
                                                    self.crossBearing,
                                                    self.deltaRowDist * 2)
                self.searchBearing = (self.searchBearing + 180) % 360

            print "Next(alt) = " + str(nextWaypoint)

        #add in the altitude points (relative to airfield home)
        for point in self.SearchPattern:
            self.SearchPattern[self.SearchPattern.index(point)] = (point[0],
                                                                   point[1],
                                                                   alt)
Ejemplo n.º 20
0
    def CreateSearchPattern(self, width=50.0, overlap=10.0, offset=10, wobble=10, alt=100):
        '''Generate the waypoints for the search pattern, using alternating strips
        width is the width (m) of each strip, overlap is the % overlap between strips, 
        alt is the altitude (relative to ground) of the points'''
        self.SearchPattern = []

        #find the nearest point to Airfield Home - use this as a starting point (if entry lanes are not used)
        if len(self.entryPoints) == 0:
            nearestdist = cuav_util.gps_distance(self.airfieldHome[0], self.airfieldHome[1], self.searchArea[0][0], self.searchArea[0][1])
            nearest = self.searchArea[0]
            for point in self.searchArea:
                newdist = cuav_util.gps_distance(self.airfieldHome[0], self.airfieldHome[1], point[0], point[1])
                if newdist < nearestdist:
                    nearest = point
                    nearestdist = newdist
        else:
            nearestdist = cuav_util.gps_distance(self.entryPoints[0][0], self.entryPoints[0][1], self.searchArea[0][0], self.searchArea[0][1])
            nearest = self.searchArea[0]
            for point in self.searchArea:
                newdist = cuav_util.gps_distance(self.entryPoints[0][0], self.entryPoints[0][1], point[0], point[1])
                #print "dist = " + str(newdist)
                if newdist < nearestdist:
                    nearest = point
                    nearestdist = newdist

        #print "Start = " + str(nearest) + ", dist = " + str(nearestdist)

        #the search pattern will run between the longest side from nearest
        bearing1 = cuav_util.gps_bearing(nearest[0], nearest[1], self.searchArea[self.searchArea.index(nearest)-1][0], self.searchArea[self.searchArea.index(nearest)-1][1])
        bearing2 = cuav_util.gps_bearing(nearest[0], nearest[1], self.searchArea[self.searchArea.index(nearest)+1][0], self.searchArea[self.searchArea.index(nearest)+1][1])
        dist1 = cuav_util.gps_distance(nearest[0], nearest[1], self.searchArea[self.searchArea.index(nearest)-1][0], self.searchArea[self.searchArea.index(nearest)-1][1])
        dist2 = cuav_util.gps_distance(nearest[0], nearest[1], self.searchArea[self.searchArea.index(nearest)+1][0], self.searchArea[self.searchArea.index(nearest)+1][1])
        if dist1 > dist2:
            self.searchBearing = bearing1
        else:
            self.searchBearing = bearing2

        #the search pattern will then run parallel between the two furthest points in the list
        #searchLine = (0, 0)
        #for point in self.searchArea: 
        #    newdist = cuav_util.gps_distance(point[0], point[1], self.searchArea[self.searchArea.index(point)-1][0], self.searchArea[self.searchArea.index(point)-1][1])
        #    if newdist > searchLine[0]:
        #        searchLine = (newdist, cuav_util.gps_bearing(point[0], point[1], self.searchArea[self.searchArea.index(point)-1][0], self.searchArea[self.searchArea.index(point)-1][1]))

        #self.searchBearing = searchLine[1]
        

        #need to find the 90 degree bearing to searchBearing that is inside the search area. This
        #will be the bearing we increment the search rows by
        #need to get the right signs for the bearings, depending which quadrant the search area is in wrt nearest
        if not cuav_util.polygon_outside(cuav_util.gps_newpos(nearest[0], nearest[1], (self.searchBearing + 45) % 360, 10), self.searchArea):
            self.crossBearing = (self.searchBearing + 90) % 360
        elif not cuav_util.polygon_outside(cuav_util.gps_newpos(nearest[0], nearest[1], (self.searchBearing + 135) % 360, 10), self.searchArea):
            self.crossBearing = (self.searchBearing + 90) % 360
            self.searchBearing = (self.searchBearing + 180) % 360
        elif not cuav_util.polygon_outside(cuav_util.gps_newpos(nearest[0], nearest[1], (self.searchBearing - 45) % 360, 10), self.searchArea):
            self.crossBearing = (self.searchBearing - 90) % 360
        else:
            self.crossBearing = (self.searchBearing - 90) % 360
            self.searchBearing = (self.searchBearing - 180) % 360

        print "Search bearing is " + str(self.searchBearing) + "/" + str((self.searchBearing + 180) % 360)
        print "Cross bearing is: " + str(self.crossBearing)

        #the distance between runs is this:
        self.deltaRowDist = width - width*(float(overlap)/100)
        if self.deltaRowDist <= 0:
            print "Error, overlap % is too high"
            return
        print "Delta row = " + str(self.deltaRowDist)

        #expand the search area to 1/2 deltaRowDist to ensure full coverage

        #we are starting at the "nearest" and mowing the lawn parallel to "self.searchBearing"
        #first waypoint is right near the Search Area boundary (without being on it) (10% of deltaRowDist
        #on an opposite bearing (so behind the search area)
        nextWaypoint =  cuav_util.gps_newpos(nearest[0], nearest[1], self.crossBearing, self.deltaRowDist/10)
        print "First = " + str(nextWaypoint)
        #self.SearchPattern.append(firstWaypoint)

        #mow the lawn, every 2nd row:
        while True:
            pts = self.projectBearing(self.searchBearing, nextWaypoint, self.searchArea)
            #print "Projecting " + str(nextWaypoint) + " along " + str(self.searchBearing)
            #check if we're outside the search area
            if pts == 0:
                break
            (nextW, nextnextW) = (pts[0], pts[1])
            if cuav_util.gps_distance(nextWaypoint[0], nextWaypoint[1], nextW[0], nextW[1]) < cuav_util.gps_distance(nextWaypoint[0], nextWaypoint[1], nextnextW[0], nextnextW[1]):
                self.SearchPattern.append(cuav_util.gps_newpos(nextW[0], nextW[1], (self.searchBearing + 180) % 360, (offset+wobble)))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(cuav_util.gps_newpos(nextnextW[0], nextnextW[1], self.searchBearing, (offset+wobble)))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextnextW[0], nextnextW[1], self.crossBearing, self.deltaRowDist*2)
                self.searchBearing = (self.searchBearing + 180) % 360
            else:
                self.SearchPattern.append(cuav_util.gps_newpos(nextnextW[0], nextnextW[1], (self.searchBearing + 180) % 360, offset+wobble))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(cuav_util.gps_newpos(nextW[0], nextW[1], self.searchBearing, (offset+wobble)))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextW[0], nextW[1], self.crossBearing, self.deltaRowDist*2)
                self.searchBearing = (self.searchBearing + 180) % 360

            print "Next = " + str(nextWaypoint)
        
        #go back and do the rows we missed. There still might be one more row to do in 
        # the crossbearing direction, so check for that first
        nextWaypoint = cuav_util.gps_newpos(nextWaypoint[0], nextWaypoint[1], self.crossBearing, -self.deltaRowDist)
        pts = self.projectBearing(self.searchBearing, nextWaypoint, self.searchArea)
        if pts == 0:
            nextWaypoint = cuav_util.gps_newpos(nextWaypoint[0], nextWaypoint[1], self.crossBearing, -2*self.deltaRowDist)
            self.crossBearing = (self.crossBearing + 180) % 360
        else:
            self.crossBearing = (self.crossBearing + 180) % 360

        while True:
            pts = self.projectBearing(self.searchBearing, nextWaypoint, self.searchArea)
            #print "Projecting " + str(nextWaypoint) + " along " + str(self.searchBearing)
            #check if we're outside the search area
            if pts == 0:
                break
            (nextW, nextnextW) = (pts[0], pts[1])
            if cuav_util.gps_distance(nextWaypoint[0], nextWaypoint[1], nextW[0], nextW[1]) < cuav_util.gps_distance(nextWaypoint[0], nextWaypoint[1], nextnextW[0], nextnextW[1]):
                self.SearchPattern.append(cuav_util.gps_newpos(nextW[0], nextW[1], (self.searchBearing + 180) % 360, offset))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(cuav_util.gps_newpos(nextnextW[0], nextnextW[1], self.searchBearing, offset))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextnextW[0], nextnextW[1], self.crossBearing, self.deltaRowDist*2)
                self.searchBearing = (self.searchBearing + 180) % 360
            else:
                self.SearchPattern.append(cuav_util.gps_newpos(nextnextW[0], nextnextW[1], (self.searchBearing + 180) % 360, offset))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                self.SearchPattern.append(cuav_util.gps_newpos(nextW[0], nextW[1], self.searchBearing, offset))
                self.SearchPattern[-1] =(self.SearchPattern[-1][0], self.SearchPattern[-1][1], alt)
                #now turn 90degrees from bearing and width distance
                nextWaypoint = cuav_util.gps_newpos(nextW[0], nextW[1], self.crossBearing, self.deltaRowDist*2)
                self.searchBearing = (self.searchBearing + 180) % 360

            print "Next(alt) = " + str(nextWaypoint)

        #add in the altitude points (relative to airfield home)
        for point in self.SearchPattern:
            self.SearchPattern[self.SearchPattern.index(point)] = (point[0], point[1], alt)
Ejemplo n.º 21
0
    def update_mission(self, m):
        '''update mission status'''
        if not self.cuav_settings.auto_mission:
            return

        wpmod = self.module('wp')
        wploader = wpmod.wploader
        if wploader.count() < 2 and self.last_attitude_ms - self.last_wp_list_ms > 5000:
            self.last_wp_list_ms = self.last_attitude_ms
            wpmod.cmd_wp(["list"])

        wp_start = self.find_user_wp(wploader, self.cuav_settings.wp_start)
        wp_center = self.find_user_wp(wploader, self.cuav_settings.wp_center)
        wp_end = self.find_user_wp(wploader, self.cuav_settings.wp_end)

        if (wp_center is None or
            wp_start is None or
            wp_end is None):
            # not configured
            return

        if m.seq >= wp_start and m.seq <= wp_end:
            lookahead = self.cuav_settings.lookahead_search
            margin_exc = self.cuav_settings.margin_exc_search
        else:
            lookahead = self.cuav_settings.lookahead_default
            margin_exc = self.cuav_settings.margin_exc_default

        v = self.mav_param.get('AVD_LOOKAHEAD', None)
        if v is not None and abs(v - lookahead) > 1:
            self.send_message("Set AVD_LOOKAHEAD %u" % lookahead)
            self.master.param_set_send('AVD_LOOKAHEAD', lookahead)

        v = self.mav_param.get('AVD_MARGIN_EXCL', None)
        if v is not None and abs(v - margin_exc) > 1:
            self.send_message("Set AVD_MARGIN_EXCL %u" % margin_exc)
            self.master.param_set_send('AVD_MARGIN_EXCL', margin_exc)
            
        # run every 5 seconds
        if self.last_attitude_ms - self.last_mission_check_ms < 5000:
            return
        self.last_mission_check_ms = self.last_attitude_ms

        if self.updated_waypoints:
            cam = self.module('camera_air')
            if wpmod.loading_waypoints:
                self.send_message("listing waypoints")                
                wpmod.cmd_wp(["list"])
            else:
                self.send_message("sending waypoints")
                self.updated_waypoints = False
                wploader.save("newwp.txt")
                cam.send_file("newwp.txt")
        
        if self.started_landing:
            # no more to do
            return

        if self.last_attitude_ms - self.last_wp_move_ms < 2*60*1000:
            # only move waypoints every 2 minutes
            return

        try:
            cam = self.module('camera_air')
            lz = cam.lz
            target_latitude = cam.camera_settings.target_latitude
            target_longitude = cam.camera_settings.target_longitude
            target_radius = cam.camera_settings.target_radius
        except Exception:
            self.send_message("target not set")
            return
        
        lzresult = lz.calclandingzone()
        if lzresult is None:
            return
        
        self.send_message("lzresult nr:%u avgscore:%u" % (lzresult.numregions, lzresult.avgscore))
        
        if lzresult.numregions < 5 and lzresult.avgscore < 20000:
            # only accept short lists if they have high scores
            return
        
        (lat, lon) = lzresult.latlon
        # check it is within the target radius
        if target_radius > 0:
            dist = cuav_util.gps_distance(lat, lon, target_latitude, target_longitude)
            self.send_message("dist %u" % dist)
            if dist > target_radius:
                return
            # don't move more than 70m from the center of the search, this keeps us
            # over more of the search area, and further from the fence
            max_move = target_radius
            if self.wp_move_count == 0:
                # don't move more than 50m from center on first move
                max_move = 35
            if self.wp_move_count == 1:
                # don't move more than 80m from center on 2nd move
                max_move = 80
            if dist > max_move:
                bearing = cuav_util.gps_bearing(target_latitude, target_longitude, lat, lon)
                (lat, lon) = cuav_util.gps_newpos(target_latitude, target_longitude, bearing, max_move)

        # we may need to fetch the wp list
        if self.last_attitude_ms - self.last_wp_list_ms > 120000 or wpmod.loading_waypoints:
            self.last_wp_list_ms = self.last_attitude_ms
            self.send_message("fetching waypoints")
            wpmod.cmd_wp(["list"])
            return
        
        self.last_wp_move_ms = self.last_attitude_ms
        self.wp_move_count += 1
        self.send_message("Moving search to: (%f,%f) %u" % (lat, lon, self.wp_move_count))
        wpmod.cmd_wp_movemulti([wp_center, wp_start, wp_end], (lat,lon))

        wp_land = self.find_user_wp(wploader, self.cuav_settings.wp_land)
        if (wp_land is not None and
            self.wp_move_count >= 3 and
            lzresult.numregions > 10 and
            self.master.flightmode == "AUTO"):
            self.send_message("Starting landing")
            self.master.waypoint_set_current_send(wp_land)
            self.started_landing = True
        self.updated_waypoints = True
Ejemplo n.º 22
0
    def altitudeCompensation(self, heightAGL, numMaxPoints=100, threshold=5):
        '''Creates height points (ASL) for each point in searchArea,
        entry and exit points such that the plane stays a constant altitude above the ground,
        constrained by a max number of waypoints'''
        maxDeltaAlt = 0
        maxDeltaAltPoints = []
        maxDeltapercentAlong = 0

        EleModel = mp_elevation.ElevationModel()
        #make sure the SRTM tiles are downloaded
        EleModel.GetElevation(self.SearchPattern[0][0], self.SearchPattern[0][1])

        #get the ASL height of the airfield home, entry and exit points and initial search pattern
        # and add the heightAGL to them
        self.airportHeight = EleModel.GetElevation(self.airfieldHome[0], self.airfieldHome[1])
        if abs(opts.basealt - self.airportHeight) > 30:
            print("BAD BASE ALTITUDE %u - airfieldhome %u" % (opts.basealt, self.airportHeight))
            sys.exit(1)
        self.airportHeight = opts.basealt
        self.airfieldHome = (self.airfieldHome[0], self.airfieldHome[1], heightAGL+opts.basealt)

        for point in self.entryPoints:
            self.entryPoints[self.entryPoints.index(point)] = (point[0], point[1], heightAGL+10+EleModel.GetElevation(point[0], point[1]))

        for point in self.exitPoints:
            self.exitPoints[self.exitPoints.index(point)] = (point[0], point[1], heightAGL+10+EleModel.GetElevation(point[0], point[1]))

        for point in self.SearchPattern:
            self.SearchPattern[self.SearchPattern.index(point)] = (point[0], point[1], heightAGL+EleModel.GetElevation(point[0], point[1]))

        #keep looping through the search area waypoints and add new waypoints where needed 
        #to maintain const height above terrain
        print "---Starting terrain tracking optimisation---"
        while True:
            maxDeltaAlt = 0
            maxDeltaAltPoints = []
            maxDeltaPointIndex = 0

            for point in self.SearchPattern:
                if point != self.SearchPattern[-1]:
                    dist = cuav_util.gps_distance(point[0], point[1], self.SearchPattern[self.SearchPattern.index(point)+1][0], self.SearchPattern[self.SearchPattern.index(point)+1][1])
                    theta = cuav_util.gps_bearing(point[0], point[1], self.SearchPattern[self.SearchPattern.index(point)+1][0], self.SearchPattern[self.SearchPattern.index(point)+1][1])
                    AltDiff = float(self.SearchPattern[self.SearchPattern.index(point)+1][2] - point[2])
    
                    if numpy.around(theta) == numpy.around(self.searchBearing) or numpy.around(theta) == numpy.around((self.searchBearing+180) % 360):           
                        #increment 10% along waypoint-to-waypoint and get max height difference
                        for i in range(1, 9):
                            partPoint = cuav_util.gps_newpos(point[0], point[1], theta, (i*dist/10))
                            partAlt = EleModel.GetElevation(partPoint[0], partPoint[1]) + heightAGL
                            #print "Part = " + str(partAlt) + ", Orig = " + str(point[2])
                            if numpy.abs(point[2] + ((AltDiff*i)/10) - partAlt) > maxDeltaAlt:
                                maxDeltaAlt = numpy.abs(point[2] + ((AltDiff*i)/10) - partAlt)
                                maxDeltaAltPoint = (partPoint[0], partPoint[1], partAlt)
                                maxDeltaPointIndex = self.SearchPattern.index(point)+1
                                #print "New max alt diff: " + str(maxDeltaAlt) + ", " + str(partAlt)
            #now put a extra waypoint in between the two maxDeltaAltPoints
            if maxDeltaAltPoint is not None:
                self.SearchPattern.insert(maxDeltaPointIndex, maxDeltaAltPoint)
            #print "There are " + str(len(self.SearchPattern)) + " points in the search pattern. Max Alt error is " + str(maxDeltaAlt)
            if len(self.SearchPattern) >= numMaxPoints or threshold > maxDeltaAlt:
                break
        print "---Done terrain tracking optimisation---"