Esempio n. 1
0
 def setUp(self):
     """Creates test data."""
     # Form test set for contains position
     self.testdata_containspos = []
     for test_data in TESTDATA_FLYZONE_CONTAINSPOS:
         # Create the FlyZone
         zone = FlyZone()
         zone.altitude_msl_min = test_data['min_alt']
         zone.altitude_msl_max = test_data['max_alt']
         zone.save()
         for waypoint_id in range(len(test_data['waypoints'])):
             (lat, lon) = test_data['waypoints'][waypoint_id]
             gpos = GpsPosition()
             gpos.latitude = lat
             gpos.longitude = lon
             gpos.save()
             apos = AerialPosition()
             apos.gps_position = gpos
             apos.altitude_msl = 0
             apos.save()
             wpt = Waypoint()
             wpt.order = waypoint_id
             wpt.position = apos
             wpt.save()
             zone.boundary_pts.add(wpt)
         # Form test set
         test_pos = []
         for pos in test_data['inside_pos']:
             test_pos.append((pos, True))
         for pos in test_data['outside_pos']:
             test_pos.append((pos, False))
         # Store
         self.testdata_containspos.append((zone, test_pos))
    def create_uas_logs(self, user, entries):
        """Create a list of uas telemetry logs.

        Args:
            user: User to create logs for.
            entries: List of (lat, lon, alt) tuples for each entry.

        Returns:
            List of UasTelemetry objects
        """
        ret = []

        for (lat, lon, alt) in entries:
            pos = GpsPosition()
            pos.latitude = lat
            pos.longitude = lon
            pos.save()
            apos = AerialPosition()
            apos.altitude_msl = alt
            apos.gps_position = pos
            apos.save()
            log = UasTelemetry()
            log.user = user
            log.uas_position = apos
            log.uas_heading = 0
            log.save()
            ret.append(log)

        return ret
Esempio n. 3
0
    def create_logs(self,
                    user,
                    num=10,
                    start=None,
                    delta=None,
                    altitude=100,
                    heading=90):
        if start is None:
            start = timezone.now()
        if delta is None:
            delta = datetime.timedelta(seconds=1)

        logs = []

        for i in xrange(num):
            gps = GpsPosition(latitude=38 + 0.001 * i,
                              longitude=-78 + 0.001 * i)
            gps.save()

            pos = AerialPosition(gps_position=gps, altitude_msl=altitude)
            pos.save()

            log = UasTelemetry(user=user,
                               uas_position=pos,
                               uas_heading=heading)
            log.save()
            log.timestamp = start + i * delta
            log.save()
            logs.append(log)

        return logs
Esempio n. 4
0
    def test_put_one(self):
        """PUT update one field without affecting others."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user,
                   target_type=TargetType.standard,
                   location=l,
                   orientation=Orientation.s,
                   shape=Shape.square,
                   background_color=Color.white,
                   alphanumeric='ABC',
                   alphanumeric_color=Color.black,
                   description='Test target')
        t.save()

        data = {'shape': 'circle'}

        response = self.client.put(
            targets_id_url(args=[t.pk]),
            data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        t.location.refresh_from_db()
        self.assertEqual(self.user, t.user)
        self.assertEqual(TargetType.standard, t.target_type)
        self.assertEqual(38, t.location.latitude)
        self.assertEqual(-76, t.location.longitude)
        self.assertEqual(Orientation.s, t.orientation)
        self.assertEqual(Shape.circle, t.shape)
        self.assertEqual(Color.white, t.background_color)
        self.assertEqual('ABC', t.alphanumeric)
        self.assertEqual(Color.black, t.alphanumeric_color)
        self.assertEqual('Test target', t.description)
Esempio n. 5
0
 def test_get_waypoint_travel_time(self):
     """Tests travel time calc."""
     test_spds = [1, 10, 100, 500]
     for (lon2, lat2, lon1, lat1, dist_km) in TESTDATA_COMPETITION_DIST:
         dist_ft = units.kilometers_to_feet(dist_km)
         for speed in test_spds:
             speed_fps = units.knots_to_feet_per_second(speed)
             time = dist_ft / speed_fps
             gpos1 = GpsPosition()
             gpos1.latitude = lat1
             gpos1.longitude = lon1
             gpos1.save()
             apos1 = AerialPosition()
             apos1.gps_position = gpos1
             apos1.altitude_msl = 0
             apos1.save()
             wpt1 = Waypoint()
             wpt1.position = apos1
             gpos2 = GpsPosition()
             gpos2.latitude = lat2
             gpos2.longitude = lon2
             gpos2.save()
             apos2 = AerialPosition()
             apos2.gps_position = gpos2
             apos2.altitude_msl = 0
             apos2.save()
             wpt2 = Waypoint()
             wpt2.position = apos2
             waypoints = [wpt1, wpt2]
             obstacle = MovingObstacle()
             obstacle.speed_avg = speed
             self.assertTrue(self.eval_travel_time(
                 obstacle.get_waypoint_travel_time(waypoints, 0, 1), time))
Esempio n. 6
0
    def setUp(self):
        """Sets up the client, server info URL, and user."""
        cache.clear()
        self.user = User.objects.create_user('testuser', '*****@*****.**',
                                             'testpass')
        self.user.save()

        response = self.client.post(login_url, {
            'username': '******',
            'password': '******',
        })
        self.assertEqual(200, response.status_code)

        self.info = ServerInfo()
        self.info.team_msg = 'test message'
        self.info.save()

        gpos = GpsPosition(latitude=0, longitude=0)
        gpos.save()

        self.mission = MissionConfig()
        self.mission.is_active = True
        self.mission.home_pos = gpos
        self.mission.emergent_last_known_pos = gpos
        self.mission.off_axis_target_pos = gpos
        self.mission.sric_pos = gpos
        self.mission.air_drop_pos = gpos
        self.mission.server_info = self.info
        self.mission.save()
Esempio n. 7
0
    def test_put_one(self):
        """PUT update one field without affecting others."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(
            user=self.user,
            target_type=TargetType.standard,
            location=l,
            orientation=Orientation.s,
            shape=Shape.square,
            background_color=Color.white,
            alphanumeric='ABC',
            alphanumeric_color=Color.black,
            description='Test target')
        t.save()

        data = {'shape': 'circle'}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        t.location.refresh_from_db()
        self.assertEqual(self.user, t.user)
        self.assertEqual(TargetType.standard, t.target_type)
        self.assertEqual(38, t.location.latitude)
        self.assertEqual(-76, t.location.longitude)
        self.assertEqual(Orientation.s, t.orientation)
        self.assertEqual(Shape.circle, t.shape)
        self.assertEqual(Color.white, t.background_color)
        self.assertEqual('ABC', t.alphanumeric)
        self.assertEqual(Color.black, t.alphanumeric_color)
        self.assertEqual('Test target', t.description)
Esempio n. 8
0
    def create_moving_obstacle(self, waypoints):
        """Create a new MovingObstacle model.

        Args:
            waypoints: List of (lat, lon, alt) tuples

        Returns:
            Saved MovingObstacle
        """
        obstacle = MovingObstacle(speed_avg=40, sphere_radius=100)
        obstacle.save()

        for num, waypoint in enumerate(waypoints):
            (lat, lon, alt) = waypoint

            gps = GpsPosition(latitude=lat, longitude=lon)
            gps.save()

            pos = AerialPosition(gps_position=gps, altitude_msl=alt)
            pos.save()

            waypoint = Waypoint(order=num, position=pos)
            waypoint.save()

            obstacle.waypoints.add(waypoint)

        obstacle.save()
        return obstacle
Esempio n. 9
0
    def test_json(self):
        """Test target JSON."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user,
                   target_type=TargetType.standard,
                   location=l,
                   orientation=Orientation.s,
                   shape=Shape.square,
                   background_color=Color.white,
                   alphanumeric='ABC',
                   alphanumeric_color=Color.black,
                   description='Test target')
        t.save()

        d = t.json()

        self.assertIn('id', d)
        self.assertEqual(self.user.pk, d['user'])
        self.assertEqual('standard', d['type'])
        self.assertEqual(38, d['latitude'])
        self.assertEqual(-76, d['longitude'])
        self.assertEqual('s', d['orientation'])
        self.assertEqual('square', d['shape'])
        self.assertEqual('white', d['background_color'])
        self.assertEqual('ABC', d['alphanumeric'])
        self.assertEqual('black', d['alphanumeric_color'])
        self.assertEqual('Test target', d['description'])
Esempio n. 10
0
    def create_data(self):
        """Create a basic sample dataset."""
        self.user1 = User.objects.create_user('user1', '*****@*****.**',
                                              'testpass')
        self.user1.save()

        self.user2 = User.objects.create_user('user2', '*****@*****.**',
                                              'testpass')
        self.user2.save()

        # user1 is flying
        event = TakeoffOrLandingEvent(user=self.user1, uas_in_air=True)
        event.save()

        # user2 has landed
        event = TakeoffOrLandingEvent(user=self.user2, uas_in_air=True)
        event.save()
        event = TakeoffOrLandingEvent(user=self.user2, uas_in_air=False)
        event.save()

        # user2 is active
        self.timestamp = timezone.now()

        gps = GpsPosition(latitude=38.6462, longitude=-76.2452)
        gps.save()

        pos = AerialPosition(gps_position=gps, altitude_msl=0)
        pos.save()

        telem = UasTelemetry(user=self.user2, uas_position=pos, uas_heading=90)
        telem.save()
        telem.timestamp = self.timestamp
        telem.save()
Esempio n. 11
0
    def setUp(self):
        """Setup a single active mission to test live kml with."""
        super(TestGenerateLiveKMLNoFixture, self).setUp()

        pos = GpsPosition()
        pos.latitude = 10
        pos.longitude = 10
        pos.save()

        info = ServerInfo()
        info.timestamp = timezone.now()
        info.message = "Hello World"
        info.save()

        config = MissionConfig()
        config.is_active = True
        config.home_pos = pos
        config.emergent_last_known_pos = pos
        config.off_axis_target_pos = pos
        config.sric_pos = pos
        config.ir_primary_target_pos = pos
        config.ir_secondary_target_pos = pos
        config.air_drop_pos = pos
        config.server_info = info
        config.save()
        self.config = config
Esempio n. 12
0
    def create_moving_obstacle(self, waypoints):
        """Create a new MovingObstacle model.

        Args:
            waypoints: List of (lat, lon, alt) tuples

        Returns:
            Saved MovingObstacle
        """
        obstacle = MovingObstacle(speed_avg=40, sphere_radius=100)
        obstacle.save()

        for num, waypoint in enumerate(waypoints):
            (lat, lon, alt) = waypoint

            gps = GpsPosition(latitude=lat, longitude=lon)
            gps.save()

            pos = AerialPosition(gps_position=gps, altitude_msl=alt)
            pos.save()

            waypoint = Waypoint(order=num, position=pos)
            waypoint.save()

            obstacle.waypoints.add(waypoint)

        obstacle.save()
        return obstacle
Esempio n. 13
0
    def test_json(self):
        """Test target JSON."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user,
                   target_type=TargetType.standard,
                   location=l,
                   orientation=Orientation.s,
                   shape=Shape.square,
                   background_color=Color.white,
                   alphanumeric='ABC',
                   alphanumeric_color=Color.black,
                   description='Test target',
                   autonomous=True)
        t.save()

        d = t.json()

        self.assertIn('id', d)
        self.assertEqual(self.user.pk, d['user'])
        self.assertEqual('standard', d['type'])
        self.assertEqual(38, d['latitude'])
        self.assertEqual(-76, d['longitude'])
        self.assertEqual('s', d['orientation'])
        self.assertEqual('square', d['shape'])
        self.assertEqual('white', d['background_color'])
        self.assertEqual('ABC', d['alphanumeric'])
        self.assertEqual('black', d['alphanumeric_color'])
        self.assertEqual('Test target', d['description'])
        self.assertEqual(True, d['autonomous'])
Esempio n. 14
0
 def test_unicode(self):
     """Tests the unicode method executes."""
     pos = GpsPosition()
     pos.latitude = 10
     pos.longitude = 100
     pos.save()
     apos = AerialPosition()
     apos.altitude_msl = 1000
     apos.gps_position = pos
     apos.save()
     wpt = Waypoint()
     wpt.position = apos
     wpt.order = 10
     wpt.save()
     config = MissionConfig()
     config.home_pos = pos
     config.emergent_last_known_pos = pos
     config.off_axis_target_pos = pos
     config.sric_pos = pos
     config.air_drop_pos = pos
     config.server_info = self.info
     config.save()
     config.mission_waypoints.add(wpt)
     config.search_grid_points.add(wpt)
     config.save()
     self.assertTrue(config.__unicode__())
Esempio n. 15
0
    def setUp(self):
        """Create the obstacles for testing."""
        # Obstacle with no waypoints
        obst_no_wpt = MovingObstacle()
        obst_no_wpt.speed_avg = 1
        obst_no_wpt.sphere_radius = 1
        obst_no_wpt.save()
        self.obst_no_wpt = obst_no_wpt

        # Obstacle with single waypoint
        self.single_wpt_lat = 40
        self.single_wpt_lon = 76
        self.single_wpt_alt = 100
        obst_single_wpt = MovingObstacle()
        obst_single_wpt.speed_avg = 1
        obst_single_wpt.sphere_radius = 1
        obst_single_wpt.save()
        single_gpos = GpsPosition()
        single_gpos.latitude = self.single_wpt_lat
        single_gpos.longitude = self.single_wpt_lon
        single_gpos.save()
        single_apos = AerialPosition()
        single_apos.gps_position = single_gpos
        single_apos.altitude_msl = self.single_wpt_alt
        single_apos.save()
        single_wpt = Waypoint()
        single_wpt.position = single_apos
        single_wpt.name = 'Waypoint'
        single_wpt.order = 1
        single_wpt.save()
        obst_single_wpt.waypoints.add(single_wpt)
        self.obst_single_wpt = obst_single_wpt

        # Obstacles with predefined path
        self.obstacles = list()
        for path in TESTDATA_MOVOBST_PATHS:
            cur_obst = MovingObstacle()
            cur_obst.name = 'MovingObstacle'
            cur_obst.speed_avg = 68
            cur_obst.sphere_radius = 10
            cur_obst.save()
            for pt_id in range(len(path)):
                (lat, lon, alt) = path[pt_id]
                cur_gpos = GpsPosition()
                cur_gpos.latitude = lat
                cur_gpos.longitude = lon
                cur_gpos.save()
                cur_apos = AerialPosition()
                cur_apos.gps_position = cur_gpos
                cur_apos.altitude_msl = alt
                cur_apos.save()
                cur_wpt = Waypoint()
                cur_wpt.position = cur_apos
                cur_wpt.name = 'Waypoint'
                cur_wpt.order = pt_id
                cur_wpt.save()
                cur_obst.waypoints.add(cur_wpt)
            cur_obst.save()
            self.obstacles.append(cur_obst)
Esempio n. 16
0
    def test_duplicate_unequal(self):
        """Tests the duplicate function for nonequal positions."""
        gps1 = GpsPosition(latitude=0, longitude=0)
        gps2 = GpsPosition(latitude=1, longitude=0)
        gps3 = GpsPosition(latitude=0, longitude=1)

        self.assertFalse(gps1.duplicate(gps2))
        self.assertFalse(gps1.duplicate(gps3))
Esempio n. 17
0
    def setUp(self):
        self.user = User.objects.create_user("testuser", "*****@*****.**", "testpass")
        self.user.save()

        # Create an active mission.
        pos = GpsPosition()
        pos.latitude = 10
        pos.longitude = 10
        pos.save()
        info = ServerInfo()
        info.timestamp = datetime.datetime.now()
        info.message = "Hello World"
        info.save()
        config = MissionConfig()
        config.is_active = True
        config.home_pos = pos
        config.emergent_last_known_pos = pos
        config.off_axis_target_pos = pos
        config.sric_pos = pos
        config.air_drop_pos = pos
        config.server_info = info
        config.save()

        # Add a couple of stationary obstacles
        obst = self.create_stationary_obstacle(lat=38.142233, lon=-76.434082, radius=300, height=500)
        config.stationary_obstacles.add(obst)

        obst = self.create_stationary_obstacle(lat=38.442233, lon=-76.834082, radius=100, height=750)
        config.stationary_obstacles.add(obst)

        # And a couple of moving obstacles
        obst = self.create_moving_obstacle(
            [
                # (lat,     lon,        alt)
                (38.142233, -76.434082, 300),
                (38.141878, -76.425198, 700),
            ]
        )
        config.moving_obstacles.add(obst)

        obst = self.create_moving_obstacle(
            [
                # (lat,     lon,        alt)
                (38.145405, -76.428310, 100),
                (38.146582, -76.424099, 200),
                (38.144662, -76.427634, 300),
                (38.147729, -76.419185, 200),
                (38.147573, -76.420832, 100),
                (38.148522, -76.419507, 750),
            ]
        )
        config.moving_obstacles.add(obst)

        config.save()

        # Login
        response = self.client.post(login_url, {"username": "******", "password": "******"})
        self.assertEqual(200, response.status_code)
Esempio n. 18
0
    def test_unicode(self):
        """Tests the unicode method executes."""
        gps = GpsPosition(latitude=10, longitude=100)
        gps.save()

        pos = AerialPosition(gps_position=gps, altitude_msl=100)
        pos.save()

        pos.__unicode__()
 def test_unicode(self):
     """Tests the unicode method executes."""
     pos = GpsPosition(latitude=100, longitude=200)
     pos.save()
     obst = StationaryObstacle(gps_position=pos,
                               cylinder_radius=10,
                               cylinder_height=100)
     obst.save()
     self.assertTrue(obst.__unicode__())
    def test_unicode(self):
        """Tests the unicode method executes."""
        gps = GpsPosition(latitude=10, longitude=100)
        gps.save()

        pos = AerialPosition(gps_position=gps, altitude_msl=100)
        pos.save()

        pos.__unicode__()
Esempio n. 21
0
 def test_unicode(self):
     """Tests the unicode method executes."""
     pos = GpsPosition(latitude=100, longitude=200)
     pos.save()
     obst = StationaryObstacle(gps_position=pos,
                               cylinder_radius=10,
                               cylinder_height=100)
     obst.save()
     self.assertTrue(obst.__unicode__())
Esempio n. 22
0
 def create_log_element(self, lat, lon, alt, user, log_time):
     pos = GpsPosition(latitude=lat, longitude=lon)
     pos.save()
     apos = AerialPosition(gps_position=pos, altitude_msl=alt)
     apos.save()
     log = UasTelemetry(user=user, uas_position=apos, uas_heading=100, )
     log.save()
     log.timestamp = log_time
     log.save()
     return log
Esempio n. 23
0
 def create_log_element(self, timestamp, user, lat, lon, alt, heading):
     pos = GpsPosition(latitude=lat, longitude=lon)
     pos.save()
     apos = AerialPosition(gps_position=pos, altitude_msl=alt)
     apos.save()
     log = UasTelemetry(timestamp=timezone.now(),
                        user=user,
                        uas_position=apos,
                        uas_heading=heading)
     log.save()
     return log
 def create_log_element(self, timestamp, user, lat, lon, alt, heading):
     pos = GpsPosition(latitude=lat, longitude=lon)
     pos.save()
     apos = AerialPosition(gps_position=pos, altitude_msl=alt)
     apos.save()
     log = UasTelemetry(timestamp=timezone.now(),
                        user=user,
                        uas_position=apos,
                        uas_heading=heading)
     log.save()
     return log
Esempio n. 25
0
    def test_put_invalid_json(self):
        """PUT request body must be valid JSON."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data="latitude=76",
                                   content_type='multipart/form-data')
        self.assertEqual(400, response.status_code)
Esempio n. 26
0
 def test_contains_pos(self):
     """Tests the contains_pos method."""
     for (zone, test_pos) in self.testdata_containspos:
         for ((lat, lon, alt), inside) in test_pos:
             gpos = GpsPosition()
             gpos.latitude = lat
             gpos.longitude = lon
             gpos.save()
             apos = AerialPosition()
             apos.altitude_msl = alt
             apos.gps_position = gpos
             self.assertEqual(zone.contains_pos(apos), inside)
Esempio n. 27
0
    def test_put_invalid_json(self):
        """PUT request body must be valid JSON."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        response = self.client.put(
            targets_id_url(args=[t.pk]),
            data="latitude=76",
            content_type='multipart/form-data')
        self.assertEqual(400, response.status_code)
Esempio n. 28
0
    def test_put_partial_clear_location(self):
        """PUT can't clear location with only one of lat/lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': None}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(400, response.status_code)
Esempio n. 29
0
    def test_put_partial_clear_location(self):
        """PUT can't clear location with only one of lat/lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': None}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(400, response.status_code)
Esempio n. 30
0
 def test_getWaypointTravelTime(self):
     """Tests travel time calc."""
     test_spds = [1, 10, 100, 500]
     for (lon2, lat2, lon1, lat1, dist_km) in TESTDATA_COMPETITION_DIST:
         dist_ft = kilometersToFeet(dist_km)
         for speed in test_spds:
             speed_fps = knotsToFeetPerSecond(speed)
             time = dist_ft / speed_fps
             wpt1 = Waypoint()
             apos1 = AerialPosition()
             gpos1 = GpsPosition()
             gpos1.latitude = lat1
             gpos1.longitude = lon1
             apos1.gps_position = gpos1
             apos1.altitude_msl = 0
             wpt1.position = apos1
             wpt2 = Waypoint()
             apos2 = AerialPosition()
             gpos2 = GpsPosition()
             gpos2.latitude = lat2
             gpos2.longitude = lon2
             apos2.gps_position = gpos2
             apos2.altitude_msl = 0
             wpt2.position = apos2
             waypoints = [wpt1, wpt2]
             obstacle = MovingObstacle()
             obstacle.speed_avg = speed
             self.assertTrue(
                 self.eval_travel_time(
                     obstacle.getWaypointTravelTime(waypoints, 0, 1), time))
Esempio n. 31
0
 def create_log_element(self, lat, lon, alt, user, log_time):
     pos = GpsPosition(latitude=lat, longitude=lon)
     pos.save()
     apos = AerialPosition(gps_position=pos, altitude_msl=alt)
     apos.save()
     log = UasTelemetry(
         user=user,
         uas_position=apos,
         uas_heading=100,
     )
     log.save()
     log.timestamp = log_time
     log.save()
     return log
Esempio n. 32
0
 def eval_distanceTo_input(self, lon1, lat1, lon2, lat2, distance_actual):
     """Evaluates the distanceTo functionality for the given inputs."""
     wpt1 = GpsPosition()
     wpt1.latitude = lat1
     wpt1.longitude = lon1
     wpt2 = GpsPosition()
     wpt2.latitude = lat2
     wpt2.longitude = lon2
     dist12 = wpt1.distanceTo(wpt2)
     dist21 = wpt2.distanceTo(wpt1)
     dist_actual_ft = kilometersToFeet(distance_actual)
     diffdist12 = abs(dist12 - dist_actual_ft)
     diffdist21 = abs(dist21 - dist_actual_ft)
     dist_thresh = 10.0
     return diffdist12 <= dist_thresh and diffdist21 <= dist_thresh
Esempio n. 33
0
    def test_put_clear_location(self):
        """PUT clear location by clearing lat and lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': None, 'longitude': None}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        self.assertEqual(None, t.location)
Esempio n. 34
0
    def test_put_clear_location(self):
        """PUT clear location by clearing lat and lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': None, 'longitude': None}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        self.assertEqual(None, t.location)
Esempio n. 35
0
 def test_contains_many_pos(self):
     """Tests the contains_many_pos method."""
     for (zone, test_pos) in self.testdata_containspos:
         aerial_pos_list = []
         expected_results = []
         for ((lat, lon, alt), inside) in test_pos:
             gpos = GpsPosition()
             gpos.latitude = lat
             gpos.longitude = lon
             gpos.save()
             apos = AerialPosition()
             apos.altitude_msl = alt
             apos.gps_position = gpos
             aerial_pos_list.append(apos)
             expected_results.append(inside)
         self.assertEqual(
             zone.contains_many_pos(aerial_pos_list), expected_results)
Esempio n. 36
0
    def post(self, request):
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Request body is not valid JSON.')

        # Target type is required.
        if 'type' not in data:
            return HttpResponseBadRequest('Target type required.')

        latitude = data.get('latitude')
        longitude = data.get('longitude')

        # Require zero or both of latitude and longitude.
        if (latitude is not None and longitude is None) or \
            (latitude is None and longitude is not None):
            return HttpResponseBadRequest(
                'Either none or both of latitude and longitude required.')

        try:
            data = normalize_data(data)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))

        l = None
        if latitude is not None and longitude is not None:
            l = GpsPosition(latitude=data['latitude'],
                            longitude=data['longitude'])
            l.save()

        # Use the dictionary get() method to default non-existent values to None.
        t = Target(user=request.user,
                   target_type=data['type'],
                   location=l,
                   orientation=data.get('orientation'),
                   shape=data.get('shape'),
                   background_color=data.get('background_color'),
                   alphanumeric=data.get('alphanumeric', ''),
                   alphanumeric_color=data.get('alphanumeric_color'),
                   description=data.get('description', ''),
                   autonomous=data.get('autonomous', False))
        t.save()

        return JsonResponse(
            t.json(is_superuser=request.user.is_superuser),
            status=201)
Esempio n. 37
0
 def setUp(self):
     """Sets up the client, obstacle URL, obstacles, and user."""
     # Setup user
     self.user = User.objects.create_user(
             'testuser', '*****@*****.**', 'testpass')
     self.user.save()
     # Setup the obstacles
     for path in TESTDATA_MOVOBST_PATHS:
         # Stationary obstacle
         (stat_lat, stat_lon, _) = path[0]
         stat_gps = GpsPosition()
         stat_gps.latitude = stat_lat
         stat_gps.longitude = stat_lon
         stat_gps.save()
         stat_obst = StationaryObstacle()
         stat_obst.gps_position = stat_gps
         stat_obst.cylinder_radius = 100
         stat_obst.cylinder_height = 200
         stat_obst.save()
         # Moving obstacle
         mov_obst = MovingObstacle()
         mov_obst.speed_avg = 40
         mov_obst.sphere_radius = 100
         mov_obst.save()
         for pt_id  in range(len(path)):
             # Obstacle waypoints
             (wpt_lat, wpt_lon, wpt_alt) = path[pt_id]
             gpos = GpsPosition()
             gpos.latitude = wpt_lat
             gpos.longitude = wpt_lon
             gpos.save()
             apos = AerialPosition()
             apos.altitude_msl = wpt_alt
             apos.gps_position = gpos
             apos.save()
             wpt = Waypoint()
             wpt.name = 'test waypoint'
             wpt.order = pt_id
             wpt.position = apos
             wpt.save()
             mov_obst.waypoints.add(wpt)
         mov_obst.save()
     # Setup test objs
     self.client = Client()
     self.loginUrl = reverse('auvsi_suas:login')
     self.obstUrl = reverse('auvsi_suas:obstacles')
Esempio n. 38
0
    def evaluate_distance_inputs(self, io_list):
        """Evaluates the distance_to calc with the given input list."""
        for (lon1, lat1, lon2, lat2, dist_actual) in io_list:
            gps1 = GpsPosition(latitude=lat1, longitude=lon1)
            gps1.save()

            gps2 = GpsPosition(latitude=lat2, longitude=lon2)
            gps2.save()

            self.assert_distance_equal(gps1, gps2, dist_actual)
Esempio n. 39
0
    def post(self, request):
        try:
            data = json.loads(request.body)
        except ValueError:
            return HttpResponseBadRequest('Request body is not valid JSON.')

        # Target type is required.
        if 'type' not in data:
            return HttpResponseBadRequest('Target type required.')

        latitude = data.get('latitude')
        longitude = data.get('longitude')

        # Require zero or both of latitude and longitude.
        if (latitude is not None and longitude is None) or \
            (latitude is None and longitude is not None):
            return HttpResponseBadRequest(
                'Either none or both of latitude and longitude required.')

        try:
            data = normalize_data(data)
        except ValueError as e:
            return HttpResponseBadRequest(str(e))

        l = None
        if latitude is not None and longitude is not None:
            l = GpsPosition(latitude=data['latitude'],
                            longitude=data['longitude'])
            l.save()

        # Use the dictionary get() method to default non-existent values to None.
        t = Target(user=request.user,
                   target_type=data['type'],
                   location=l,
                   orientation=data.get('orientation'),
                   shape=data.get('shape'),
                   background_color=data.get('background_color'),
                   alphanumeric=data.get('alphanumeric', ''),
                   alphanumeric_color=data.get('alphanumeric_color'),
                   description=data.get('description', ''),
                   autonomous=data.get('autonomous', False))
        t.save()

        return JsonResponse(t.json(is_superuser=request.user.is_superuser),
                            status=201)
Esempio n. 40
0
    def create_stationary_obstacle(self, lat, lon, radius, height):
        """Create a new StationaryObstacle model.

        Args:
            lat: Latitude of centroid
            lon: Longitude of centroid
            radius: Cylinder radius
            height: Cylinder height

        Returns:
            Saved StationaryObstacle
        """
        gps = GpsPosition(latitude=lat, longitude=lon)
        gps.save()

        obstacle = StationaryObstacle(gps_position=gps, cylinder_radius=radius, cylinder_height=height)
        obstacle.save()
        return obstacle
Esempio n. 41
0
    def test_put_update_location(self):
        """PUT updating location only requires one of lat/lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': 39}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        t.location.refresh_from_db()
        self.assertEqual(39, t.location.latitude)
        self.assertEqual(-76, t.location.longitude)
Esempio n. 42
0
    def test_put_update_location(self):
        """PUT updating location only requires one of lat/lon."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user, target_type=TargetType.standard, location=l)
        t.save()

        data = {'latitude': 39}

        response = self.client.put(targets_id_url(args=[t.pk]),
                                   data=json.dumps(data))
        self.assertEqual(200, response.status_code)

        t.refresh_from_db()
        t.location.refresh_from_db()
        self.assertEqual(39, t.location.latitude)
        self.assertEqual(-76, t.location.longitude)
Esempio n. 43
0
    def test_json(self):
        """Test target JSON."""
        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(
            user=self.user,
            target_type=TargetType.standard,
            location=l,
            orientation=Orientation.s,
            shape=Shape.square,
            background_color=Color.white,
            alphanumeric="ABC",
            alphanumeric_color=Color.black,
            description="Test target",
            autonomous=True,
        )
        t.save()

        d = t.json()

        self.assertIn("id", d)
        self.assertEqual(self.user.pk, d["user"])
        self.assertEqual("standard", d["type"])
        self.assertEqual(38, d["latitude"])
        self.assertEqual(-76, d["longitude"])
        self.assertEqual("s", d["orientation"])
        self.assertEqual("square", d["shape"])
        self.assertEqual("white", d["background_color"])
        self.assertEqual("ABC", d["alphanumeric"])
        self.assertEqual("black", d["alphanumeric_color"])
        self.assertEqual("Test target", d["description"])
        self.assertEqual(True, d["autonomous"])
        self.assertNotIn("thumbnail_approved", d)

        d = t.json(is_superuser=True)
        self.assertIn("thumbnail_approved", d)

        t.thumbnail_approved = True
        t.save()
        d = t.json(is_superuser=True)
        self.assertEqual(None, d["thumbnail"])
        self.assertEqual(True, d["thumbnail_approved"])
Esempio n. 44
0
    def test_valid(self):
        """Test creating a valid target."""
        with open(os.path.join(settings.BASE_DIR,
                               'auvsi_suas/fixtures/testdata/S.jpg')) as f:
            thumb = SimpleUploadedFile('thumb.jpg', f.read())

        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user,
                   target_type=TargetType.standard,
                   location=l,
                   orientation=Orientation.s,
                   shape=Shape.square,
                   background_color=Color.white,
                   alphanumeric='ABC',
                   alphanumeric_color=Color.black,
                   description='Test target',
                   thumbnail=thumb)
        t.save()
Esempio n. 45
0
 def eval_distanceTo_input(self, lon1, lat1, alt1, lon2, lat2, alt2,
                           dist_actual):
     """Evaluates the distanceTo calc with the given inputs."""
     pos1 = AerialPosition()
     pos1.gps_position = GpsPosition()
     pos1.gps_position.latitude = lat1
     pos1.gps_position.longitude = lon1
     pos1.altitude_msl = alt1
     pos2 = AerialPosition()
     pos2.gps_position = GpsPosition()
     pos2.gps_position.latitude = lat2
     pos2.gps_position.longitude = lon2
     pos2.altitude_msl = alt2
     dist12 = pos1.distanceTo(pos2)
     dist21 = pos2.distanceTo(pos1)
     dist_actual_ft = kilometersToFeet(dist_actual)
     diffdist12 = abs(dist12 - dist_actual_ft)
     diffdist21 = abs(dist21 - dist_actual_ft)
     dist_thresh = 10.0
     return diffdist12 <= dist_thresh and diffdist21 <= dist_thresh
Esempio n. 46
0
    def evaluate_distance_inputs(self, io_list):
        """Evaluates the distance_to calc with the given input list."""
        for (lon1, lat1, alt1, lon2, lat2, alt2, dist_actual) in io_list:
            gps1 = GpsPosition(latitude=lat1, longitude=lon1)
            gps1.save()

            gps2 = GpsPosition(latitude=lat2, longitude=lon2)
            gps2.save()

            pos1 = AerialPosition(gps_position=gps1, altitude_msl=alt1)
            pos2 = AerialPosition(gps_position=gps2, altitude_msl=alt2)

            self.assertDistanceEqual(pos1, pos2, dist_actual)
Esempio n. 47
0
    def test_valid(self):
        """Test creating a valid target."""
        with open(os.path.join(settings.BASE_DIR,
                               'auvsi_suas/fixtures/testdata/S.jpg')) as f:
            thumb = SimpleUploadedFile('thumb.jpg', f.read())

        l = GpsPosition(latitude=38, longitude=-76)
        l.save()

        t = Target(user=self.user,
                   target_type=TargetType.standard,
                   location=l,
                   orientation=Orientation.s,
                   shape=Shape.square,
                   background_color=Color.white,
                   alphanumeric='ABC',
                   alphanumeric_color=Color.black,
                   description='Test target',
                   thumbnail=thumb)
        t.save()
Esempio n. 48
0
    def test_duplicate_equal(self):
        """Tests the duplicate function with unequal positions."""
        gps1 = GpsPosition(latitude=0, longitude=0)
        gps1.save()
        gps2 = GpsPosition(latitude=0, longitude=0)
        gps2.save()

        pos1 = AerialPosition(gps_position=gps1, altitude_msl=0)
        pos2 = AerialPosition(gps_position=gps2, altitude_msl=0)
        pos3 = AerialPosition(gps_position=gps1, altitude_msl=0)

        self.assertTrue(pos1.duplicate(pos2))
        self.assertTrue(pos1.duplicate(pos3))
Esempio n. 49
0
    def create_stationary_obstacle(self, lat, lon, radius, height):
        """Create a new StationaryObstacle model.

        Args:
            lat: Latitude of centroid
            lon: Longitude of centroid
            radius: Cylinder radius
            height: Cylinder height

        Returns:
            Saved StationaryObstacle
        """
        gps = GpsPosition(latitude=lat, longitude=lon)
        gps.save()

        obstacle = StationaryObstacle(gps_position=gps,
                                      cylinder_radius=radius,
                                      cylinder_height=height)
        obstacle.save()
        return obstacle
Esempio n. 50
0
    def setUp(self):
        """Populates an active mission to test a cached view."""
        pos = GpsPosition()
        pos.latitude = 10
        pos.longitude = 10
        pos.save()
        self.pos = pos

        obst = StationaryObstacle()
        obst.gps_position = pos
        obst.cylinder_radius = 10
        obst.cylinder_height = 10
        obst.save()
        self.obst = obst

        config = MissionConfig()
        config.is_active = True
        config.home_pos = pos
        config.emergent_last_known_pos = pos
        config.off_axis_target_pos = pos
        config.sric_pos = pos
        config.air_drop_pos = pos
        config.save()
        self.config = config
        config.stationary_obstacles.add(obst)
        config.save()

        self.login_url = reverse('auvsi_suas:login')
        self.obst_url = reverse('auvsi_suas:obstacles')
        self.clear_cache_url = reverse('auvsi_suas:clear_cache')
Esempio n. 51
0
 def test_unicode(self):
     """Tests the unicode method executes."""
     pos = GpsPosition()
     pos.latitude = 10
     pos.longitude = 100
     pos.save()
     apos = AerialPosition()
     apos.altitude_msl = 1000
     apos.gps_position = pos
     apos.save()
     wpt = Waypoint()
     wpt.position = apos
     wpt.order = 10
     wpt.save()
     config = MissionConfig()
     config.home_pos = pos
     config.emergent_last_known_pos = pos
     config.off_axis_target_pos = pos
     config.sric_pos = pos
     config.air_drop_pos = pos
     config.server_info = self.info
     config.save()
     config.mission_waypoints.add(wpt)
     config.search_grid_points.add(wpt)
     config.save()
     self.assertTrue(config.__unicode__())
Esempio n. 52
0
 def setUp(self):
     """Creates test data."""
     # Form test set for contains position
     self.testdata_containspos = []
     for test_data in TESTDATA_FLYZONE_CONTAINSPOS:
         # Create the FlyZone
         zone = FlyZone()
         zone.altitude_msl_min = test_data['min_alt']
         zone.altitude_msl_max = test_data['max_alt']
         zone.save()
         for waypoint_id in range(len(test_data['waypoints'])):
             (lat, lon) = test_data['waypoints'][waypoint_id]
             gpos = GpsPosition()
             gpos.latitude = lat
             gpos.longitude = lon
             gpos.save()
             apos = AerialPosition()
             apos.gps_position = gpos
             apos.altitude_msl = 0
             apos.save()
             wpt = Waypoint()
             wpt.order = waypoint_id
             wpt.position = apos
             wpt.save()
             zone.boundary_pts.add(wpt)
         # Form test set
         test_pos = []
         for pos in test_data['inside_pos']:
             test_pos.append((pos, True))
         for pos in test_data['outside_pos']:
             test_pos.append((pos, False))
         # Store
         self.testdata_containspos.append((zone, test_pos))
Esempio n. 53
0
    def create_uas_logs(self, user, entries):
        """Create a list of uas telemetry logs.

        Args:
            user: User to create logs for.
            entries: List of (lat, lon, alt) tuples for each entry.

        Returns:
            List of UasTelemetry objects
        """
        ret = []

        for (lat, lon, alt) in entries:
            pos = GpsPosition()
            pos.latitude = lat
            pos.longitude = lon
            pos.save()
            apos = AerialPosition()
            apos.altitude_msl = alt
            apos.gps_position = pos
            apos.save()
            log = UasTelemetry()
            log.user = user
            log.uas_position = apos
            log.uas_heading = 0
            log.save()
            ret.append(log)

        return ret
Esempio n. 54
0
def postUasPosition(request):
    """Posts the UAS position with a POST request.

    User must send a POST request with the following paramters:
    latitude: A latitude in decimal degrees.
    longitude: A logitude in decimal degrees.
    altitude_msl: An MSL altitude in decimal feet.
    uas_heading: The UAS heading in decimal degrees. (0=north, 90=east)
    """
    # Validate user is logged in to make request
    if not request.user.is_authenticated():
        return HttpResponseBadRequest('User not logged in. Login required.')
    # Validate user made a POST request
    if request.method != 'POST':
        return HttpResponseBadRequest('Request must be POST request.')

    try:
        # Get the parameters
        latitude = float(request.POST['latitude'])
        longitude = float(request.POST['longitude'])
        altitude_msl = float(request.POST['altitude_msl'])
        uas_heading = float(request.POST['uas_heading'])
    except KeyError:
        # Failed to get POST parameters
        return HttpResponseBadRequest(
                'Posting UAS position must contain POST parameters "latitude", '
                '"longitude", "altitude_msl", and "uas_heading".')
    except ValueError:
        # Failed to convert parameters
        return HttpResponseBadRequest(
                'Failed to convert provided POST parameters to correct form.')
    else:
        # Check the values make sense
        if latitude < -90 or latitude > 90:
            return HttpResponseBadRequest(
                    'Must provide latitude between -90 and 90 degrees.')
        if longitude < -180 or longitude > 180:
            return HttpResponseBadRequest(
                    'Must provide longitude between -180 and 180 degrees.')
        if uas_heading < 0 or uas_heading > 360:
            return HttpResponseBadRequest(
                    'Must provide heading between 0 and 360 degrees.')

        # Store telemetry
        gps_position = GpsPosition()
        gps_position.latitude = latitude
        gps_position.longitude = longitude
        gps_position.save()
        aerial_position = AerialPosition()
        aerial_position.gps_position = gps_position
        aerial_position.altitude_msl = altitude_msl
        aerial_position.save()
        uas_telemetry = UasTelemetry()
        uas_telemetry.user = request.user
        uas_telemetry.uas_position = aerial_position
        uas_telemetry.uas_heading = uas_heading
        uas_telemetry.save()

        return HttpResponse('UAS Telemetry Successfully Posted.')
    def test_json(self):
        """Tests the JSON serialization method."""
        TEST_LAT = 100.10
        TEST_LONG = 200.20
        TEST_RADIUS = 150.50
        TEST_HEIGHT = 75.30

        gpos = GpsPosition(latitude=TEST_LAT, longitude=TEST_LONG)
        gpos.save()
        obstacle = StationaryObstacle(gps_position=gpos,
                                      cylinder_radius=TEST_RADIUS,
                                      cylinder_height=TEST_HEIGHT)
        json_data = obstacle.json()

        self.assertTrue('latitude' in json_data)
        self.assertEqual(json_data['latitude'], TEST_LAT)
        self.assertTrue('longitude' in json_data)
        self.assertEqual(json_data['longitude'], TEST_LONG)
        self.assertTrue('cylinder_radius' in json_data)
        self.assertEqual(json_data['cylinder_radius'], TEST_RADIUS)
        self.assertTrue('cylinder_height' in json_data)
        self.assertEqual(json_data['cylinder_height'], TEST_HEIGHT)
Esempio n. 56
0
    def setUp(self):
        self.user = User.objects.create_user('testuser', '*****@*****.**',
                                             'testpass')
        self.user.save()

        # Create an active mission.
        pos = GpsPosition()
        pos.latitude = 10
        pos.longitude = 10
        pos.save()
        config = MissionConfig()
        config.is_active = True
        config.home_pos = pos
        config.emergent_last_known_pos = pos
        config.off_axis_target_pos = pos
        config.sric_pos = pos
        config.air_drop_pos = pos
        config.save()

        # Add a couple of stationary obstacles
        obst = self.create_stationary_obstacle(lat=38.142233,
                                               lon=-76.434082,
                                               radius=300,
                                               height=500)
        config.stationary_obstacles.add(obst)

        obst = self.create_stationary_obstacle(lat=38.442233,
                                               lon=-76.834082,
                                               radius=100,
                                               height=750)
        config.stationary_obstacles.add(obst)

        # And a couple of moving obstacles
        obst = self.create_moving_obstacle([
            # (lat,     lon,        alt)
            (38.142233, -76.434082, 300),
            (38.141878, -76.425198, 700),
        ])
        config.moving_obstacles.add(obst)

        obst = self.create_moving_obstacle([
            # (lat,     lon,        alt)
            (38.145405, -76.428310, 100),
            (38.146582, -76.424099, 200),
            (38.144662, -76.427634, 300),
            (38.147729, -76.419185, 200),
            (38.147573, -76.420832, 100),
            (38.148522, -76.419507, 750),
        ])
        config.moving_obstacles.add(obst)

        config.save()

        # Login
        response = self.client.post(login_url, {
            'username': '******',
            'password': '******'
        })
        self.assertEqual(200, response.status_code)
Esempio n. 57
0
    def create_logs(self, user, num=10, start=None, delta=None):
        if start is None:
            start = timezone.now()
        if delta is None:
            delta = datetime.timedelta(seconds=1)

        logs = []

        for i in xrange(num):
            gps_position = GpsPosition(latitude=0, longitude=0)
            gps_position.save()
            uas_position = AerialPosition(gps_position=gps_position,
                                          altitude_msl=0)
            uas_position.save()
            log = UasTelemetry(user=user,
                               uas_position=uas_position,
                               uas_heading=0)
            log.save()
            log.timestamp = start + i * delta
            log.save()
            logs.append(log)

        return logs