예제 #1
0
    async def test_basic(self):
        tracker1 = Tracker('tracker1')
        tracker2 = Tracker('tracker2')
        await tracker1.new_points([{'time': d('2017/01/01 05:05:00'), 'item': 1}])

        new_points_callback = asynctest.CoroutineMock()
        reset_points_callback = asynctest.CoroutineMock()

        combined = await Combined.start(
            'combined', (tracker1, tracker2),
            new_points_callbacks=(new_points_callback, ),
            reset_points_callbacks=(reset_points_callback, ),
        )

        new_points_callback.assert_called_once_with(combined, [{'time': d('2017/01/01 05:05:00'), 'item': 1}])
        new_points_callback.reset_mock()

        await tracker1.new_points([{'time': d('2017/01/01 05:10:00'), 'item': 2}])
        new_points_callback.assert_called_once_with(combined, [{'time': d('2017/01/01 05:10:00'), 'item': 2}])
        new_points_callback.reset_mock()

        await tracker2.new_points([{'time': d('2017/01/01 05:00:00'), 'item': 3}])
        reset_points_callback.assert_called_once_with(combined)
        new_points_callback.assert_called_once_with(combined, [
            {'time': d('2017/01/01 05:00:00'), 'item': 3},
            {'time': d('2017/01/01 05:05:00'), 'item': 1},
            {'time': d('2017/01/01 05:10:00'), 'item': 2},
        ])
        reset_points_callback.reset_mock()
        new_points_callback.reset_mock()

        combined.stop()
        await asyncio.wait_for(combined.complete(), timeout=0.5)
예제 #2
0
    async def test_with_route_points_same_time(self):
        # test to make sure we don't do division by zero when doing speed calcs.
        tracker = Tracker('test')
        routes = [
            {
                'main':
                True,
                'points': [
                    [-26.300420, 28.049410],
                    [-26.315691, 28.062354],
                    [-26.322250, 28.042440],
                ]
            },
        ]
        event_routes = get_analyse_routes(routes)

        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300824, 28.050185, 1800)
            },
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300824, 28.050200, 1800)
            },
        ))
        # Time is the same for both points.

        tracker.completed.set_result(None)
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 05:00:00'),
                                                     event_routes)
        await analyse_tracker.complete()

        print_points(analyse_tracker.points)
예제 #3
0
async def start_tracker(app, tracker_name, name, event, end):
    tracker = Tracker(f'trackleaders.{tracker_name}')
    monitor_task = asyncio.ensure_future(
        monitor_feed(app, tracker, name, event, end))
    tracker.stop = monitor_task.cancel
    tracker.completed = monitor_task
    return tracker
예제 #4
0
async def start_tracker(app, tracker_name, feed_id, password, start, end):
    tracker = Tracker('garmin_inreach.{}-{}'.format(feed_id, tracker_name))
    monitor_task = asyncio.ensure_future(
        monitor_feed(app, tracker, feed_id, password, start, end))
    tracker.stop = monitor_task.cancel
    tracker.completed = monitor_task
    return tracker
예제 #5
0
    async def test_with_route_alt(self):
        tracker = Tracker('test')
        routes = [
            {
                'points': [
                    [-26.300420, 28.049410],
                    [-26.315685, 28.062377],
                    [-26.381378, 28.067689],
                    [-26.417153, 28.072707],
                ],
            },
            {
                'points': [
                    [-26.315685, 28.062377],
                    [-26.324918, 27.985781],
                    [-26.381378, 28.067689],
                ],
            },
        ]

        process_secondary_route_details(routes)
        event_routes = get_analyse_routes(routes)
        # pprint.pprint(event_routes)

        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300824, 28.050185, 1800)
            },
            {
                'time': d('2017/01/01 06:00:00'),
                'position': (-26.325051, 27.985600, 1800)
            },
            {
                'time': d('2017/01/01 07:00:00'),
                'position': (-26.417149, 28.073087, 1800)
            },
        ))
        tracker.completed.set_result(None)
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 05:00:00'),
                                                     event_routes)
        await analyse_tracker.complete()

        # TODO: does this actually test that we are getting the dist from the alt route?
        points = filter_keys(analyse_tracker.points,
                             keys_to_keep=('dist_route', ))
        print_points(points)
        self.assertSequenceEqual(points, [
            {
                'dist_route': 82.0
            },
            {
                'dist_route': 5256.0
            },
            {
                'dist_route': 13423.0
            },
        ])
예제 #6
0
파일: analyse.py 프로젝트: garyvdm/trackers
    async def start(
        cls,
        org_tracker,
        analyse_start_time,
        routes,
        track_break_time=timedelta(minutes=30),
        track_break_dist=10000,
        find_closest_cache=None,
        processing_lock=None,
    ):
        self = cls('analysed.{}'.format(org_tracker.name))
        self.org_tracker = org_tracker
        self.analyse_start_time = analyse_start_time
        self.routes = routes
        self.track_break_time = track_break_time
        self.track_break_dist = track_break_dist
        if find_closest_cache:
            find_closest_cache.func = find_closest_point_pair_routes
            find_closest_cache.key = find_closest_point_pair_routes_cache_key
            find_closest_cache.unpack = partial(
                find_closest_point_pair_routes_unpack, routes)
            find_closest_cache.pack = find_closest_point_pair_routes_pack
            self.find_closest = find_closest_cache
        else:
            self.find_closest = find_closest_point_pair_routes

        self.processing_lock = processing_lock if processing_lock else asyncio.Lock(
        )

        self.completed = asyncio.ensure_future(self._completed())

        self.off_route_tracker = Tracker(f'offroute.{self.name}',
                                         completed=self.completed)
        self.pre_post_tracker = Tracker(f'prepost.{self.name}',
                                        completed=self.completed)
        self.not_pre_post_observable = Observable(self.logger)

        self.reset()
        self.do_est_finish_fut = None

        self.process_initial_points_fut = asyncio.ensure_future(
            self.process_initial_points())
        self.process_initial_points_fut.add_done_callback(
            general_fut_done_callback)

        return self
예제 #7
0
    async def test(self):
        new_points_callback = asynctest.CoroutineMock()
        tracker = Tracker('test', new_points_callbacks=(new_points_callback, ))
        tracker.stop = lambda: tracker.completed.set_result(None)

        await tracker.new_points([{'foo': 'bar'}])
        new_points_callback.assert_called_once_with(tracker, [{'foo': 'bar'}])

        tracker.stop()
        await tracker.complete()
        self.assertTrue(tracker.completed.done())
예제 #8
0
    async def test_with_end(self):
        org_tracker = Tracker('test')
        await org_tracker.new_points([
            {'i': 0, 'time': datetime.datetime(2017, 1, 1, 5, 55)},
            {'i': 1, 'time': datetime.datetime(2017, 1, 1, 6, 5)},
        ])
        org_tracker.completed.set_result(None)

        tracker = await cropped_tracker_start(org_tracker, {'end': datetime.datetime(2017, 1, 1, 6, 0)})
        await tracker.complete()
        self.assertEqual(len(tracker.points), 1)
        self.assertEqual(tracker.points[0]['i'], 0)
    async def test_reset_and_change(self):
        tracker = Tracker('test')
        ih_tracker = await index_and_hash_tracker(tracker)

        await tracker.new_points((
            {
                'position': (-26.300822, 28.049444, 1800)
            },
            {
                'position': (-26.302245, 28.051139, 1800)
            },
        ))

        pprint.pprint(ih_tracker.points)
        self.assertSequenceEqual(ih_tracker.points, [
            {
                'position': (-26.300822, 28.049444, 1800),
                'index': 0,
                'hash': 'sISs'
            },
            {
                'position': (-26.302245, 28.051139, 1800),
                'index': 1,
                'hash': '9VOm'
            },
        ])

        await tracker.reset_points()
        self.assertSequenceEqual(ih_tracker.points, [])

        await tracker.new_points((
            {
                'position': (-27.280315, 27.969365, 1800)
            },
            {
                'position': (-27.282870, 27.970620, 1800)
            },
        ))

        pprint.pprint(ih_tracker.points)
        self.assertSequenceEqual(ih_tracker.points,
                                 [{
                                     'hash': 'X60A',
                                     'index': 0,
                                     'position': (-27.280315, 27.969365, 1800)
                                 }, {
                                     'hash': 'W9tZ',
                                     'index': 1,
                                     'position': (-27.28287, 27.97062, 1800)
                                 }])

        tracker.completed.set_result(None)
        await ih_tracker.complete()
예제 #10
0
async def start_replay_tracker(org_tracker,
                               event_start_time,
                               replay_start,
                               offset=timedelta(0),
                               speed_multiply=2000):
    replay_tracker = Tracker('replay.{}'.format(org_tracker.name))
    replay_task = asyncio.ensure_future(
        replay(replay_tracker, org_tracker, event_start_time, replay_start,
               offset, speed_multiply))
    replay_tracker.stop = replay_task.cancel
    replay_tracker.completed = replay_task
    return replay_tracker
예제 #11
0
async def filter_inaccurate_tracker_start(org_tracker, tracker_data):
    filtered_tracker = Tracker('filter_inaccurate.{}'.format(org_tracker.name),
                               org_tracker.completed)
    filtered_tracker.stop = org_tracker.stop
    filtered_tracker.org_tracker = org_tracker

    await filter_inaccurate_tracker_newpoints(filtered_tracker, org_tracker,
                                              org_tracker.points)
    org_tracker.new_points_observable.subscribe(
        functools.partial(filter_inaccurate_tracker_newpoints,
                          filtered_tracker))
    return filtered_tracker
예제 #12
0
    async def test_with_route(self):
        tracker = Tracker('test')
        routes = [
            {
                'main':
                True,
                'points': [
                    [-26.300420, 28.049410],
                    [-26.315691, 28.062354],
                    [-26.322250, 28.042440],
                ]
            },
        ]
        event_routes = get_analyse_routes(routes)

        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300824, 28.050185, 1800)
            },
            {
                'time': d('2017/01/01 05:01:00'),
                'position': (-26.322167, 28.042920, 1800)
            },
        ))
        tracker.completed.set_result(None)
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 05:00:00'),
                                                     event_routes)
        await analyse_tracker.complete()

        points = filter_keys(analyse_tracker.points,
                             keys_to_remove=('time', 'position'))
        print_points(points)
        self.assertSequenceEqual(points, [
            {
                'track_id': 0,
                'dist': 82.0,
                'dist_from_last': 82.0,
                'dist_route': 82.0
            },
            {
                'track_id': 0,
                'dist': 4198.0,
                'dist_from_last': 4116.0,
                'dist_route': 4198.0,
                'speed_from_last': 247.0,
                'time_from_last': timedelta(0, 60),
                'finished_time': d('2017/01/01 05:01:00'),
                'rider_status': 'Finished',
            },
        ])
예제 #13
0
async def start_event_tracker(app, event, rider_name, tracker_data, start,
                              end):
    tracker = Tracker('mapmytracks.{}'.format(tracker_data['name']))
    monitor_task = asyncio.ensure_future(
        monitor_user(
            app['trackers.mapmytracks_session'], tracker_data['name'], start,
            end,
            os.path.join(app['trackers.settings']['cache_path'], event.name,
                         'mapmytracks'), tracker,
            set(tracker_data.get('exclude', ()))))
    tracker.stop = monitor_task.cancel
    tracker.completed = monitor_task
    return tracker
예제 #14
0
async def cropped_tracker_start(org_tracker, tracker_data):
    cropped_tracker = Tracker('cropped.{}'.format(org_tracker.name),
                              org_tracker.completed)
    cropped_tracker.stop = org_tracker.stop
    cropped_tracker.org_tracker = org_tracker

    await cropped_tracker_newpoints(cropped_tracker, tracker_data.get('start'),
                                    tracker_data.get('end'), org_tracker,
                                    org_tracker.points)
    org_tracker.new_points_observable.subscribe(
        functools.partial(cropped_tracker_newpoints, cropped_tracker,
                          tracker_data.get('start'), tracker_data.get('end')))
    return cropped_tracker
예제 #15
0
async def setup():
    global tracker, event_routes

    with open('test_analyse_tracker_routes.json') as f:
        routes = json.load(f)

    event_routes = get_analyse_routes(routes)

    tracker = Tracker('perf_test_source')
    with open('test_analyse_tracker_perf_data.json') as f:
        points = json.load(f)
    for point in points:
        point['time'] = datetime.datetime.fromtimestamp(point['time'])
    await tracker.new_points(points)
예제 #16
0
async def index_and_hash_tracker(org_tracker, hasher=None):
    ih_tracker = Tracker('indexed_and_hashed.{}'.format(org_tracker.name),
                         org_tracker.completed)
    ih_tracker.stop = org_tracker.stop
    ih_tracker.org_tracker = org_tracker
    if hasher is None:
        hasher = hashlib.sha1()
    ih_tracker.hasher = hasher

    await index_and_hash_tracker_org_newpoints(ih_tracker, org_tracker,
                                               org_tracker.points)
    org_tracker.new_points_observable.subscribe(
        functools.partial(index_and_hash_tracker_org_newpoints, ih_tracker))
    org_tracker.reset_points_observable.subscribe(
        functools.partial(index_and_hash_tracker_org_reset_points, ih_tracker))

    return ih_tracker
예제 #17
0
    async def test(self):
        org_tracker = Tracker('test')
        await org_tracker.new_points([
            {'i': 0, 'time': datetime.datetime(2017, 1, 1, 6, 0)},
            {'i': 1, 'time': datetime.datetime(2017, 1, 1, 6, 5)},
        ])
        org_tracker.completed.set_result(None)

        new_points_callback = asynctest.CoroutineMock()

        event_start = datetime.datetime(2017, 1, 1, 6, 0)
        now = datetime.datetime.now() + datetime.timedelta(seconds=0.01)
        replay_tracker = await start_replay_tracker(org_tracker, event_start, now)
        replay_tracker.new_points_observable.subscribe(new_points_callback)

        await replay_tracker.complete()

        self.assertEqual(new_points_callback.call_count, 2)
예제 #18
0
    async def test_break_tracks(self):
        tracker = Tracker('test')
        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300822, 28.049444, 1800)
            },
            {
                'time': d('2017/01/01 05:01:00'),
                'position': (-26.302245, 28.051139, 1800)
            },
            {
                'time': d('2017/01/01 05:30:00'),
                'position': (-27.280315, 27.969365, 1800)
            },
            {
                'time': d('2017/01/01 05:31:00'),
                'position': (-27.282870, 27.970620, 1800)
            },
        ))
        tracker.completed.set_result(None)
        analyse_tracker = await AnalyseTracker.start(
            tracker,
            d('2017/01/01 05:00:00'), [],
            track_break_time=timedelta(minutes=20))
        await analyse_tracker.complete()

        points = filter_keys(analyse_tracker.points,
                             keys_to_keep=('track_id', ))
        print_points(points)
        self.assertSequenceEqual(points, [
            {
                'track_id': 0
            },
            {
                'track_id': 0
            },
            {
                'track_id': 1
            },
            {
                'track_id': 1
            },
        ])
예제 #19
0
    async def test_stop(self):
        tracker = Tracker('test')
        tracker.stop = lambda: tracker.completed.cancel()

        t1 = datetime.datetime.now()
        await tracker.new_points(({
            'time': t1,
            'position': (-26.300822, 28.049444, 1800)
        }, ))
        break_time = datetime.timedelta(seconds=1)
        analyse_tracker = await AnalyseTracker.start(
            tracker, d('2017/01/01 05:00:00'), [], track_break_time=break_time)

        await asyncio.sleep(0.05)
        analyse_tracker.stop()
        try:
            await analyse_tracker.complete()
        except asyncio.CancelledError:
            pass
예제 #20
0
async def static_start_event_tracker(app, event, rider_name, tracker_data,
                                     start, end):
    tracker = Tracker('static.{}'.format(tracker_data['name']))
    path = os.path.join('events', event.name, tracker_data['name'])
    data = TreeReader(app['trackers.data_repo']).get(path).data
    points = {
        'json': lambda data: json.loads(data.decode()),
        'msgpack': lambda data: msgpack.loads(data, raw=False)
    }[tracker_data.get('format', 'json')](data)
    for point in points:
        if 'time' in point:
            point['time'] = datetime.fromtimestamp(point['time'])
        if 'server_time' in point:
            point['server_time'] = datetime.fromtimestamp(point['server_time'])
        if 'finished_time' in point:
            point['finished_time'] = datetime.fromtimestamp(
                point['finished_time'])

    await tracker.new_points(points)
    tracker.completed.set_result(None)
    return tracker
예제 #21
0
    async def test_get_predicted_position(self):
        tracker = Tracker('test')
        routes = [
            {
                'main':
                True,
                'points': [
                    [-27.881250000, 27.919840000],
                    [-27.862210000, 27.917000000],
                    [-27.743550000, 27.942480000],
                    [-27.843790000, 28.164510000],
                    [-27.945580000, 28.044930000],
                ]
            },
        ]
        event_routes = get_analyse_routes(routes)

        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-27.880490000, 27.917450000, 1800)
            },
            {
                'time': d('2017/01/01 05:01:00'),
                'position': (-27.843790000, 28.164510000, 1800)
            },
        ))
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 05:00:00'),
                                                     event_routes)
        print_points(analyse_tracker.points)

        predicted_point = analyse_tracker.get_predicted_position(
            d('2017/01/01 05:01:30'))
        pprint.pprint(predicted_point)

        tracker.completed.set_result(None)
        await analyse_tracker.complete()
예제 #22
0
    async def test_reset(self):
        tracker = Tracker('test')
        await tracker.new_points((
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300822, 28.049444, 1800)
            },
            {
                'time': d('2017/01/01 05:01:00'),
                'position': (-26.302245, 28.051139, 1800)
            },
            # {'time': d('2017/01/01 05:30:00'), 'position': (-27.280315, 27.969365, 1800)},
            # {'time': d('2017/01/01 05:31:00'), 'position': (-27.282870, 27.970620, 1800)},
        ))
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 05:00:00'),
                                                     [])
        await analyse_tracker.process_initial_points_fut

        print_points(analyse_tracker.points)
        self.assertSequenceEqual(analyse_tracker.points, [
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-26.300822, 28.049444, 1800),
                'track_id': 0
            },
            {
                'time': d('2017/01/01 05:01:00'),
                'position': (-26.302245, 28.051139, 1800),
                'track_id': 0,
                'dist': 231.0,
                'dist_from_last': 231.0,
                'speed_from_last': 13.9,
                'time_from_last': timedelta(0, 60)
            },
        ])

        await tracker.reset_points()
        self.assertSequenceEqual(analyse_tracker.points, [])

        await tracker.new_points((
            {
                'time': d('2017/01/01 05:30:00'),
                'position': (-27.280315, 27.969365, 1800)
            },
            {
                'time': d('2017/01/01 05:31:00'),
                'position': (-27.282870, 27.970620, 1800)
            },
        ))
        print_points(analyse_tracker.points)
        self.assertSequenceEqual(analyse_tracker.points, [
            {
                'time': d('2017/01/01 05:30:00'),
                'position': (-27.280315, 27.969365, 1800),
                'track_id': 0
            },
            {
                'time': d('2017/01/01 05:31:00'),
                'position': (-27.28287, 27.97062, 1800),
                'track_id': 0,
                'dist': 309.0,
                'dist_from_last': 309.0,
                'speed_from_last': 18.6,
                'time_from_last': timedelta(0, 60)
            },
        ])

        tracker.completed.set_result(None)
        await analyse_tracker.complete()
예제 #23
0
    async def test_with_circular_route(self):
        tracker = Tracker('test')
        routes = [
            {
                'main':
                True,
                'points': [
                    [-27.88125, 27.91984],
                    [-27.86221, 27.91700],
                    [-27.74355, 27.94248],
                    [-27.84379, 28.16451],
                    [-27.94558, 28.04493],
                    [-27.88049, 27.91745],
                    [-27.86044, 27.91808],
                    [-27.77983, 27.74638],
                    [-27.90019, 27.66862],
                    [-28.04381, 27.96971],
                    [-27.93335, 28.02870],
                    [-27.88125, 27.91984],
                ],
                'split_at_dist': [35000, 115000],
                'split_point_range':
                10000,
                'circular_range':
                50000,
            },
        ]
        event_routes = get_analyse_routes(routes)

        await tracker.new_points((
            {
                'time': d('2017/01/01 01:05:00'),
                'position': (-27.88049, 27.91745, 1800)
            },
            {
                'time': d('2017/01/01 02:00:00'),
                'position': (-27.84379, 28.16451, 1800)
            },
            {
                'time': d('2017/01/01 03:00:00'),
                'position': (-27.94558, 28.04493, 1800)
            },
            {
                'time': d('2017/01/01 04:00:00'),
                'position': (-27.88125, 27.91984, 1800)
            },
            {
                'time': d('2017/01/01 05:00:00'),
                'position': (-27.77983, 27.74638, 1800)
            },
            {
                'time': d('2017/01/01 06:00:00'),
                'position': (-28.04381, 27.96971, 1800)
            },
            {
                'time': d('2017/01/01 07:00:00'),
                'position': (-27.88049, 27.91745, 1800)
            },
        ))
        tracker.completed.set_result(None)
        analyse_tracker = await AnalyseTracker.start(tracker,
                                                     d('2017/01/01 01:00:00'),
                                                     event_routes)
        await analyse_tracker.complete()

        points = filter_keys(analyse_tracker.points, ('dist_route', ))
        print_points(points)
        self.assertSequenceEqual(points, [
            {
                'dist_route': 114.0
            },
            {
                'dist_route': 40054.0
            },
            {
                'dist_route': 56359.0
            },
            {
                'dist_route': 70588.0
            },
            {
                'dist_route': 92187.0
            },
            {
                'dist_route': 141196.0
            },
            {
                'dist_route': 166916.0
            },
        ])
예제 #24
0
    async def test_tracker_points_show_and_change(self):
        step_sleep_time = 0.5

        async with AsyncExitStack() as stack:
            session = self.browser_session
            app, client_errors, server_errors = await stack.enter_async_context(
                tracker_web_server_fixture())

            mock_tracker = Tracker('mock_tracker')

            async def start_mock_event_tracker(app, event, rider_name,
                                               tracker_data, start, end):
                return mock_tracker

            app['start_event_trackers'] = {
                'mock': start_mock_event_tracker,
            }
            url = await stack.enter_async_context(
                web_server_fixture(self.loop, app))

            app['trackers.events']['test_event'] = event = Event(
                app, 'test_event',
                yaml.load("""
                    title: Test Event
                    event_start: 2017-01-01 05:00:00
                    live: True
                    riders:
                        - name: Foo Bar
                          name_short: Foo
                          tracker: {type: mock}
                    markers: []
                    batch_update_interval: 0.1
                    predicted_update_interval: 5
                    bounds: {'north': -26.300822, 'south': -27.28287, 'east': 28.051139, 'west': 27.969365}
                """), [])
            await on_new_event(event)
            # await event.start_trackers()
            await session.get(f'{url}/test_event')
            await wait_condition(ws_ready_is, session, True)
            await asyncio.sleep(step_sleep_time)

            await mock_tracker.new_points([
                {
                    'time': d('2017/01/01 05:00:00'),
                    'position': (-26.300822, 28.049444, 1800)
                },
                {
                    'time': d('2017/01/01 05:01:00'),
                    'position': (-26.351581, 28.100281, 1800)
                },
            ])
            await asyncio.sleep(step_sleep_time)
            # await session.execute_script('console.log(riders_client_items["Foo Bar"].marker);')
            # await asyncio.sleep(100)
            self.assertFalse(await session.execute_script(
                'return riders_client_items["Foo Bar"].marker === null;'))
            self.assertEqual(
                await session.execute_script(
                    'return riders_client_items["Foo Bar"].paths.riders_off_route.length;'
                ), 1)
            self.assertEqual(
                await session.execute_script(
                    'return riders_client_items["Foo Bar"].paths.riders_off_route[0].getPath().length;'
                ), 2)

            await mock_tracker.reset_points()
            await asyncio.sleep(step_sleep_time)
            # await asyncio.sleep(100)
            self.assertTrue(await session.execute_script(
                'return riders_client_items["Foo Bar"].marker === null;'))
            self.assertEqual(
                await session.execute_script(
                    'return riders_client_items["Foo Bar"].paths.riders_off_route.length;'
                ), 0)

            await mock_tracker.new_points([
                {
                    'time': d('2017/01/01 05:30:00'),
                    'position': (-26.351581, 28.100281, 1800)
                },
                {
                    'time': d('2017/01/01 05:31:00'),
                    'position': (-27.282870, 27.970620, 1800)
                },
            ])
            await asyncio.sleep(step_sleep_time)
            # await asyncio.sleep(100)
            self.assertFalse(await session.execute_script(
                'return riders_client_items["Foo Bar"].marker === null;'))
            self.assertEqual(
                await session.execute_script(
                    'return riders_client_items["Foo Bar"].paths.riders_off_route.length;'
                ), 1)
            self.assertEqual(
                await session.execute_script(
                    'return riders_client_items["Foo Bar"].paths.riders_off_route[0].getPath().length;'
                ), 2)

        self.check_no_errors(client_errors, server_errors)
예제 #25
0
 async def start_mock_event_tracker(app, event, rider_name,
                                    tracker_data, start, end):
     tracker = Tracker('mock_tracker')
     tracker.completed.set_result(None)
     return tracker
예제 #26
0
파일: traccar.py 프로젝트: garyvdm/trackers
async def start_tracker(app, tracker_name, server_name, device_unique_id,
                        start, end):
    device_unique_id = str(device_unique_id)
    await ensure_login(app, server_name)
    server = app['trackers.traccar_servers'][server_name]
    server_url = server['url']
    session = server['session']

    devices_response = await session.get(f'{server_url}/api/devices',
                                         params={'all': 'true'})
    devices = await devices_response.json()
    try:
        device = more_itertools.first(
            (device for device in devices
             if device['uniqueId'] == device_unique_id))
        device_id = device['id']
        if device['name'] == device['uniqueId']:
            # Update name on traccar
            set_name_response = await session.put(
                f'{server_url}/api/devices/{device_id}',
                json={
                    'name': tracker_name,
                    'uniqueId': device['uniqueId'],
                    'id': device['id']
                })
            await set_name_response.json()
    except ValueError:
        get_device_response = await session.post(f'{server_url}/api/devices',
                                                 json={
                                                     'uniqueId':
                                                     device_unique_id,
                                                     'name': tracker_name
                                                 })
        device_id = (await get_device_response.json())['id']

    tracker = Tracker('traccar.{}.{}-{}'.format(server_name, device_unique_id,
                                                tracker_name))

    try:
        await session.post(f'{server_url}/api/permissions',
                           json={
                               'userId': server['user_id'],
                               'deviceId': device_id
                           })
    except Exception as e:
        tracker.logger.error(f'Error in set permissions: {e}')

    tracker.server = server
    tracker.device_id = device_id
    tracker.start = (start if start else
                     (datetime.datetime.now() -
                      datetime.timedelta(days=2)).replace(microsecond=0))
    tracker.end = end
    tracker.seen_ids = seen_ids = set()

    initial_query_end = (end if end else
                         (datetime.datetime.now() +
                          datetime.timedelta(days=1)).replace(microsecond=0))
    positions_response = await session.get(
        f'{server_url}/api/positions',
        params={
            'deviceId': device_id,
            'from': tracker.start.astimezone(dateutil.tz.UTC).isoformat(),
            'to': initial_query_end.astimezone(dateutil.tz.UTC).isoformat()
        },
        headers={'Accept': 'application/json'})
    positions = await positions_response.json()
    points = [traccar_position_translate(position) for position in positions]
    seen_ids.update([position['id'] for position in positions])
    tracker.position_recived = functools.partial(tracker_position_received,
                                                 tracker)
    server['position_received_observables'][device_id].subscribe(
        tracker.position_recived)
    await tracker.new_points(points)

    tracker.finished = asyncio.Event()
    tracker.stop = functools.partial(tracker_stop, tracker)
    tracker.completed = asyncio.ensure_future(tracker.finished.wait())
    tracker.completed.add_done_callback(
        functools.partial(tracker_on_completed, tracker))
    if end:
        asyncio.get_event_loop().call_at(
            asyncio.get_event_loop().time() - time.time() + end.timestamp(),
            tracker.finished.set)
    return tracker
예제 #27
0
    async def test_from_tracker(self):
        tracker = Tracker('test')

        new_update_callback = asynctest.CoroutineMock()

        blocked_list = BlockedList.from_tracker(
            tracker, new_update_callbacks=(new_update_callback, ))

        await tracker.new_points(source[:9])
        self.assertEqual(
            blocked_list.full, {
                'blocks': [{
                    'end_hash': 'cTTc',
                    'end_index': 7,
                    'start_index': 0
                }],
                'partial_block': [{
                    'hash': 'xtbb',
                    'index': 8,
                    'x': 's'
                }]
            })
        new_update_callback.assert_called_once_with(
            blocked_list, {
                'blocks': [{
                    'end_hash': 'cTTc',
                    'end_index': 7,
                    'start_index': 0
                }],
                'partial_block': [{
                    'hash': 'xtbb',
                    'index': 8,
                    'x': 's'
                }]
            })
        new_update_callback.reset_mock()

        await tracker.reset_points()
        self.assertEqual(blocked_list.full, {
            'blocks': [],
            'partial_block': []
        })
        new_update_callback.assert_called_once_with(blocked_list, {
            'blocks': [],
            'partial_block': []
        })
        new_update_callback.reset_mock()

        await tracker.new_points(source[10:11])
        self.assertEqual(
            blocked_list.full, {
                'blocks': [],
                'partial_block': [{
                    'x': 'm',
                    'index': 10,
                    'hash': 'KCgI'
                }]
            })
        new_update_callback.assert_called_once_with(
            blocked_list,
            {'add_block': [{
                'x': 'm',
                'index': 10,
                'hash': 'KCgI'
            }]})

        tracker.completed.set_result(None)
        await tracker.complete()