Ejemplo n.º 1
0
    def get_closest_bus_stop(self, bus_info: CdsRouteBus):
        threshold = 0.005
        bus_stop = next(
            (x for x in self.bus_stops
             if bus_info.bus_station_ and x.NAME_ == bus_info.bus_station_),
            None)
        if bus_stop and bus_info.distance(bus_stop) < threshold:
            return bus_stop

        bus_positions = self.last_bus_data[bus_info.name_]
        if not bus_positions:
            bus_positions.append(bus_info.get_bus_position())
        closest_on_route = self.get_closest_bus_stop_checked(
            bus_info.route_name_, bus_positions)

        if closest_on_route and bus_info.distance(
                closest_on_route) < threshold:
            return closest_on_route

        closest_stop = min(self.bus_stops, key=bus_info.distance)
        if closest_stop and bus_info.distance(closest_stop) < threshold:
            return closest_stop

        result = min((bus_stop, closest_on_route, closest_stop),
                     key=bus_info.distance)

        if not bus_info.bus_station_:
            self.logger.debug(f"Empty station: {bus_info.short()} {result}")

        return result
Ejemplo n.º 2
0
    def get_closest_bus_stop(self, bus_info: CdsRouteBus):
        if not bus_info.is_valid_coords():
            return
        threshold = 0.5
        bus_stop = self.bus_stops_dict_name.get(bus_info.bus_station_)
        if bus_stop and bus_info.distance_km(bus_stop):
            return bus_stop
        elif self.now() - bus_info.last_time_ > timedelta(minutes=15):
            return self.get_nearest(bus_info.last_lat_, bus_info.last_lon_)

        bus_positions = self.last_bus_data[bus_info.name_]
        if not bus_positions:
            bus_positions.append(bus_info.get_bus_position())
        closest_on_route = self.get_closest_bus_stop_checked(
            bus_info.route_name_, bus_positions)

        if closest_on_route and bus_info.distance(
                closest_on_route) < threshold:
            return closest_on_route

        closest_stop = self.get_nearest(bus_info.last_lat_, bus_info.last_lon_)
        if closest_stop and bus_info.distance(closest_stop) < threshold:
            return closest_stop

        result = min((bus_stop, closest_on_route, closest_stop),
                     key=bus_info.distance)

        if not bus_info.bus_station_:
            self.logger.debug(f"Empty station: {bus_info.short()} {result}")

        return result
Ejemplo n.º 3
0
 def bus_station(self, bus_info: CdsRouteBus):
     if not bus_info.is_valid_coords():
         self.logger.debug(f"Not valid coords {bus_info}")
         return
     result = self.get_closest_bus_stop(bus_info)
     if not result or not result.NAME_:
         self.logger.debug(f"{result} {bus_info}")
     return result and result.NAME_
Ejemplo n.º 4
0
    def test_closest_bus_stop(self):
        route_bus = CdsRouteBus.make(*[
            51.625537, 39.177478, 16, "2018-02-15T19:57:47", "М617АК136", 834,
            20, "80", 0, "2018-02-15T19:54:56", "Рабочий проспект (из центра)"
        ])

        station = self.cds.get_closest_bus_stop(route_bus)
        logger.info(
            f"{station}; {route_bus.distance_km(station):.4f}  {route_bus.distance(station):.4f}"
        )
Ejemplo n.º 5
0
 def next_test_data(self):
     if self.test_data_files and self.test_data_index >= len(
             self.test_data_files):
         self.test_data_index = 0
     path = self.test_data_files[self.test_data_index]
     self.mocked_now = datetime.strptime(
         path.name, "codd_data_db%y_%m_%d_%H_%M_%S.json")
     with open(path, 'rb') as f:
         long_bus_stops = [CdsRouteBus.make(*i) for i in json.load(f)]
     self.test_data_index += 1
     self.logger.info(f'Loaded {path.name}; {self.mocked_now:%H:%M:%S}')
     return long_bus_stops
Ejemplo n.º 6
0
    def load_all_cds_buses(self) -> List[CdsRouteBus]:
        def make_names_lower(x):
            return {k.lower(): v for (k, v) in x.iteritems()}

        self.logger.debug('Execute fetch all from DB')
        start = time.time()
        try:
            with fdb.TransactionContext(
                    self.cds_db.trans(
                        fdb.ISOLATION_LEVEL_READ_COMMITED_RO)) as tr:
                cur = tr.cursor()
                cur.execute(
                    '''SELECT bs.NAME_ AS BUS_STATION_, rt.NAME_ AS ROUTE_NAME_,  o.NAME_, o.OBJ_ID_, o.LAST_TIME_,
                    o.LAST_LON_, o.LAST_LAT_, o.LAST_SPEED_, o.LAST_STATION_TIME_, o.PROJ_ID_
                    FROM OBJECTS O JOIN BUS_STATIONS bs
                    ON o.LAST_ROUT_ = bs.ROUT_ AND o.LAST_STATION_ = bs.NUMBER_
                    JOIN ROUTS rt ON o.LAST_ROUT_ = rt.ID_
                    WHERE obj_output_=0''')
                self.logger.debug('Finish execution')
                result = cur.fetchallmap()
                tr.commit()
                cur.close()
                end = time.time()
                self.logger.info(
                    f"Finish fetch data. Elapsed: {end - start:.2f}")
        except fdb.fbcore.DatabaseError as db_error:
            self.logger.error(db_error)
            try:
                self.cds_db = fdb.connect(host=CDS_HOST,
                                          database=CDS_DB_PATH,
                                          user=CDS_USER,
                                          password=CDS_PASS,
                                          charset='WIN1251')
                self.cds_db.default_tpb = fdb.ISOLATION_LEVEL_READ_COMMITED_RO
            except Exception as general_error:
                self.logger.error(general_error)
            return []

        result = [CdsRouteBus(**make_names_lower(x)) for x in result]
        result.sort(key=lambda s: s.last_time_, reverse=True)
        end = time.time()
        self.logger.info(f"Finish proccess. Elapsed: {end - start:.2f}")
        return result
Ejemplo n.º 7
0
    def load_all_cds_buses(self) -> List[CdsRouteBus]:
        def make_names_lower(x):
            return {k.lower(): v for (k, v) in x.iteritems()}

        self.logger.debug('Execute fetch all from DB')
        start = time.time()
        try:
            with fdb.TransactionContext(
                    self.cds_db_project.trans(
                        fdb.ISOLATION_LEVEL_READ_COMMITED_RO)) as tr:
                cur = tr.cursor()
                cur.execute(
                    '''SELECT bs.NAME_ AS BUS_STATION_, rt.NAME_ AS ROUTE_NAME_,  o.NAME_, o.OBJ_ID_, o.LAST_TIME_,
                    o.LAST_LON_, o.LAST_LAT_, o.LAST_SPEED_, o.LAST_STATION_TIME_, o.PROJ_ID_,
                     coalesce(o.lowfloor, 0) as low_floor, coalesce(o.VEHICLE_TYPE_, 0) as bus_type,
                      coalesce(obj_output_, 0) as obj_output 
                    FROM OBJECTS O LEFT JOIN BUS_STATIONS bs
                    ON o.LAST_ROUT_ = bs.ROUT_ AND o.LAST_STATION_ = bs.NUMBER_
                    LEFT JOIN ROUTS rt ON o.LAST_ROUT_ = rt.ID_''')
                self.logger.debug('Finish execution')
                result = cur.fetchallmap()
                tr.commit()
                cur.close()
                end = time.time()
                self.logger.info(
                    f"Finish fetch data. Elapsed: {end - start:.2f}")
        except fdb.fbcore.DatabaseError as db_error:
            self.logger.error(db_error)
            self.try_reconnect()
            return []

        result = [CdsRouteBus(**make_names_lower(x)) for x in result]
        result.sort(key=lambda s: s.last_time_, reverse=True)
        end = time.time()
        self.logger.info(f"Finish proccess. Elapsed: {end - start:.2f}")
        return result
Ejemplo n.º 8
0
    def load_all_cds_buses(self) -> List[CdsRouteBus]:
        def make_names_lower(x):
            return {k.lower(): v for (k, v) in x.items()}

        self.logger.debug('Execute fetch all from DB')
        start = time.time()
        try:
            with transaction(self.cds_db_project.transaction_manager()) as tr:
                cur = tr.cursor()
                cur.execute(
                    '''SELECT bs.NAME_ AS BUS_STATION_, rt.NAME_ AS ROUTE_NAME_,  o.NAME_, o.OBJ_ID_, o.LAST_TIME_,
                    o.LAST_LON_, o.LAST_LAT_, o.LAST_SPEED_, o.LAST_STATION_TIME_, o.PROJ_ID_,
                     coalesce(o.lowfloor, 0) as low_floor, coalesce(o.VEHICLE_TYPE_, 0) as bus_type,
                      coalesce(obj_output_, 0) as obj_output,
                      coalesce(azmth_, 0) as azimuth,
                      coalesce(o."BortName", '') as bort_name
                    FROM OBJECTS O LEFT JOIN BUS_STATIONS bs
                    ON o.LAST_ROUT_ = bs.ROUT_ AND o.LAST_STATION_ = bs.NUMBER_
                    LEFT JOIN ROUTS rt ON o.LAST_ROUT_ = rt.ID_''')
                self.logger.debug('Finish execution')
                result = fetch_cursor_map(cur)
                end = time.time()
                self.logger.info(
                    f"Finish fetch data. Elapsed: {end - start:.2f}")
        except firebird.driver.DatabaseError as db_error:
            self.logger.error(db_error)
            self.try_reconnect()
            return []

        obl_result = []
        try:
            if self.load_obl_objects:
                with transaction(self.cds_db_data.transaction_manager()) as tr:
                    cur = tr.cursor()
                    cur.execute(
                        '''SELECT bs.NAME AS BUS_STATION_, rt.NAME_ AS ROUTE_NAME_,  o.block_number as OBJ_ID_,  
                        CAST(o.block_number as VARCHAR(10)) as NAME_, o.LAST_TIME as LAST_TIME_,
                        o.LON as LAST_LON_, o.LAT as LAST_LAT_, 0 as LAST_SPEED_, NULL as LAST_STATION_TIME_, NULL as PROJ_ID_,
                         0 as low_floor,
                            0 as bus_type,
                          0 as obj_output,
                          coalesce(o.azimuth, 0) as azimuth,
                          coalesce(o."BortName", '') as bort_name
                        FROM OBL_OBJECTS O LEFT JOIN BS
                        ON o.bs_id = bs.ID
                        LEFT JOIN ROUTS rt ON o.route_id = rt.ID_''')
                    self.logger.debug('Finish execution')
                    obl_result = fetch_cursor_map(cur)
                    end = time.time()
                    self.logger.info(
                        f"Finish fetch data. Elapsed: {end - start:.2f}")
        except firebird.driver.DatabaseError as db_error:
            if self.load_obl_objects:
                self.load_obl_objects = False
                self.logger.error(db_error)
                self.try_reconnect()

        result = [
            CdsRouteBus(**make_names_lower(x)) for x in result + obl_result
        ]
        result.sort(key=lambda s: s.last_time_, reverse=True)
        end = time.time()
        self.logger.info(f"Finish proccess. Elapsed: {end - start:.2f}")
        return result
Ejemplo n.º 9
0
 def filtered(d: CdsRouteBus):
     return d.filter_by_name(search_result.bus_filter)