Ejemplo n.º 1
0
def display_value(value):
    min = datetime.fromtimestamp(value[0], tz=timezone.utc)
    max = datetime.fromtimestamp(value[1], tz=timezone.utc)
    filtered_trips = []
    for trip in trips:
        if min <= trip.start_at <= max:
            filtered_trips.append(trip)
    filtered_chargings = MyPSACC.get_chargings(min, max)
    figures.get_figures(filtered_trips, filtered_chargings)
    consumption = "Average consumption: {:.1f} kW/100km".format(
        float(figures.consumption_df.mean(numeric_only=True)))
    return figures.trips_map, figures.consumption_fig, figures.consumption_fig_by_speed, consumption, figures.table_fig, figures.battery_info
Ejemplo n.º 2
0
 def display_value(value):  # pylint: disable=unused-variable
     mini = datetime.fromtimestamp(value[0], tz=timezone.utc)
     maxi = datetime.fromtimestamp(value[1], tz=timezone.utc)
     filtered_trips = Trips()
     for trip in trips:
         if mini <= trip.start_at <= maxi:
             filtered_trips.append(trip)
     filtered_chargings = Charging.get_chargings(mini, maxi)
     figures.get_figures(filtered_trips, filtered_chargings)
     return figures.trips_map, figures.consumption_fig, figures.consumption_fig_by_speed, \
            figures.consumption_graph_by_temp, create_card(figures.SUMMARY_CARDS), \
            figures.table_fig, figures.battery_table, max_millis, step, marks
Ejemplo n.º 3
0
def display_value(value):
    mini = datetime.fromtimestamp(value[0], tz=timezone.utc)
    maxi = datetime.fromtimestamp(value[1], tz=timezone.utc)
    filtered_trips = Trips()
    for trip in trips:
        if mini <= trip.start_at <= maxi:
            filtered_trips.append(trip)
    filtered_chargings = MyPSACC.get_chargings(mini, maxi)
    figures.get_figures(filtered_trips, filtered_chargings)
    consumption = "Average consumption: {:.1f} kWh/100km".format(float(figures.consumption_df["consumption_km"].mean()))
    return figures.trips_map, figures.consumption_fig, figures.consumption_fig_by_speed, \
           figures.consumption_graph_by_temp, consumption, figures.table_fig, figures.battery_info, \
           figures.battery_table, max_millis, step, marks
Ejemplo n.º 4
0
def update_trips():
    global trips, chargings, cached_layout, min_date, max_date, min_millis, max_millis, step, marks
    logger.info("update_data")
    conn = Database.get_db(update_callback=False)
    Database.add_altitude_to_db(conn)
    conn.close()
    min_date = None
    max_date = None
    try:
        assert len(myp.vehicles_list) > 0
        car = myp.vehicles_list[0]  # todo handle multiple car
        figures.get_figures(car)
        trips_by_vin = Trips.get_trips(Cars([car]))
        trips = trips_by_vin[car.vin]
        assert len(trips) > 0
        min_date = trips[0].start_at
        max_date = trips[-1].start_at
    except (AssertionError, KeyError):
        logger.debug("No trips yet")
    try:
        chargings = Charging.get_chargings()
        assert len(chargings) > 0
        if min_date:
            min_date = min(min_date, chargings[0]["start_at"])
            max_date = max(max_date, chargings[-1]["start_at"])
        else:
            min_date = chargings[0]["start_at"]
            max_date = chargings[-1]["start_at"]
    except AssertionError:
        logger.debug("No chargings yet")
        if min_date is None:
            return
    # update for slider
    try:
        logger.debug("min_date:%s - max_date:%s", min_date, max_date)
        min_millis = web.utils.unix_time_millis(min_date)
        max_millis = web.utils.unix_time_millis(max_date)
        step = (max_millis - min_millis) / 100
        marks = web.utils.get_marks_from_start_end(min_date, max_date)
        cached_layout = None  # force regenerate layout
        figures.get_figures(car)
    except (ValueError, IndexError):
        logger.error("update_trips (slider): %s", exc_info=True)
    except AttributeError:
        logger.debug("position table is probably empty :", exc_info=True)
    return
Ejemplo n.º 5
0
def serve_layout():
    global cached_layout
    if cached_layout is None:
        logger.debug("Create new layout")
        try:
            figures.get_figures(trips, chargings)
            data_div = html.Div([dcc.RangeSlider(
                id='date-slider',
                min=min_millis,
                max=max_millis,
                step=step,
                marks=marks,
                value=[min_millis, max_millis],
            ),
                html.Div([
                    dbc.Tabs([
                        dbc.Tab(label="Summary", tab_id="summary", children=[
                            html.H2(id="consumption",
                                    children=figures.info),
                            dcc.Graph(figure=figures.consumption_fig, id="consumption_fig"),
                            dcc.Graph(figure=figures.consumption_fig_by_speed, id="consumption_fig_by_speed"),
                            figures.consumption_graph_by_temp
                        ]),
                        dbc.Tab(label="Trips", tab_id="trips", id="tab_trips", children=[figures.table_fig]),
                        dbc.Tab(label="Battery", tab_id="battery", id="tab_battery", children=[figures.battery_info]),
                        dbc.Tab(label="Charge", tab_id="charge", id="tab_charge", children=[figures.battery_table]),
                        dbc.Tab(label="Map", tab_id="map", children=[
                            dcc.Graph(figure=figures.trips_map, id="trips_map", style={"height": '90vh'})]),
                    ],
                        id="tabs",
                        active_tab="summary",
                    ),
                    html.Div(id="tab-content", className="p-4"),
                ])])

        except (IndexError, TypeError):
            logger.debug("Failed to generate figure, there is probably not enough data yet %s", traceback.format_exc())
            data_div = ERROR_DIV
        cached_layout = dbc.Container(fluid=True, children=[html.H1('My car info'), data_div])
    return cached_layout
Ejemplo n.º 6
0
    def test_record_position_charging(self):
        get_new_test_db()
        ElecPrice.CONFIG_FILENAME = DATA_DIR + "config.ini"
        car = self.vehicule_list[0]
        record_position()
        Database.add_altitude_to_db(Database.get_db())
        data = json.loads(Database.get_recorded_position())
        assert data["features"][1]["geometry"]["coordinates"] == [float(longitude), float(latitude)]
        trips = Trips.get_trips(self.vehicule_list)[car.vin]
        trip = trips[0]
        map(trip.add_temperature, [10, 13, 15])
        res = trip.get_info()
        assert compare_dict(res, {'consumption_km': 24.21052631578947,
                                  'start_at': date0,
                                  'consumption_by_temp': None,
                                  'positions': {'lat': [latitude], 'long': [longitude]},
                                  'duration': 40.0, 'speed_average': 28.5, 'distance': 19.0, 'mileage': 30.0,
                                  'altitude_diff': 2, 'id': 1, 'consumption': 4.6})

        Charging.elec_price = ElecPrice.read_config()
        start_level = 40
        end_level = 85
        Charging.record_charging(car, "InProgress", date0, start_level, latitude, longitude, None, "slow", 20, 60)
        Charging.record_charging(car, "InProgress", date1, 70, latitude, longitude, "FR", "slow", 20, 60)
        Charging.record_charging(car, "InProgress", date1, 70, latitude, longitude, "FR", "slow", 20, 60)
        Charging.record_charging(car, "InProgress", date2, 80, latitude, longitude, "FR", "slow", 20, 60)
        Charging.record_charging(car, "Stopped", date3, end_level, latitude, longitude, "FR", "slow", 20, 60)
        chargings = Charging.get_chargings()
        co2 = chargings[0]["co2"]
        assert isinstance(co2, float)
        assert compare_dict(chargings, [{'start_at': date0,
                                         'stop_at': date3,
                                         'VIN': 'VR3UHZKX',
                                         'start_level': 40,
                                         'end_level': 85,
                                         'co2': co2,
                                         'kw': 20.7,
                                         'price': 3.84,
                                         'charging_mode': 'slow'}])
        print()
        assert get_figures(car)
        row = {"start_at": date0.strftime('%Y-%m-%dT%H:%M:%S.000Z'),
               "stop_at": date3.strftime('%Y-%m-%dT%H:%M:%S.000Z'), "start_level": start_level, "end_level": end_level}
        assert get_battery_curve_fig(row, car) is not None
        assert get_altitude_fig(trip) is not None
Ejemplo n.º 7
0
    try:
        trips = MyPSACC.get_trips()
        chargings = MyPSACC.get_chargings()
    except:
        logger.error("update_trips: " + traceback.format_exc())


try:
    web.db.callback_fct = update_trips
    update_trips()
    min_date = trips[0].start_at
    max_date = trips[-1].start_at
    min_millis = figures.unix_time_millis(min_date)
    max_millis = figures.unix_time_millis(max_date)
    step = (max_millis - min_millis) / 100
    figures.get_figures(trips, chargings)
    data_div = html.Div([
        dcc.RangeSlider(
            id='date-slider',
            min=min_millis,
            max=max_millis,
            step=step,
            marks=figures.get_marks_from_start_end(min_date, max_date),
            value=[min_millis, max_millis],
        ),
        html.Div([
            dbc.Tabs(
                [
                    dbc.Tab(
                        label="Summary",
                        tab_id="summary",
Ejemplo n.º 8
0
def serve_layout():
    global cached_layout
    if cached_layout is None:
        logger.debug("Create new layout")
        try:
            figures.get_figures(trips, chargings)
            summary_tab = [dbc.Container(dbc.Row(id="summary-cards",
                                                 children=create_card(figures.SUMMARY_CARDS)), fluid=True),
                           dcc.Graph(figure=figures.consumption_fig, id="consumption_fig"),
                           dcc.Graph(figure=figures.consumption_fig_by_speed, id="consumption_fig_by_speed"),
                           figures.consumption_graph_by_temp]
            maps = dcc.Graph(figure=figures.trips_map, id="trips_map", style={"height": '90vh'})
            create_callback()
            range_slider = dcc.RangeSlider(
                id='date-slider',
                min=min_millis,
                max=max_millis,
                step=step,
                marks=marks,
                value=[min_millis, max_millis],
            )
        except (IndexError, TypeError, NameError):
            summary_tab = figures.ERROR_DIV
            maps = figures.ERROR_DIV
            logger.warning("Failed to generate figure, there is probably not enough data yet", exc_info_debug=True)
            range_slider = html.Div()
        data_div = html.Div([
            range_slider,
            html.Div([
                dbc.Tabs([
                    dbc.Tab(label="Summary", tab_id="summary", children=summary_tab),
                    dbc.Tab(label="Trips", tab_id="trips", id="tab_trips",
                            children=[html.Div(id="tab_trips_fig", children=figures.table_fig),
                                      dbc.Modal(
                                          [
                                              dbc.ModalHeader("Altitude"),
                                              dbc.ModalBody(html.Div(
                                                  id="tab_trips_popup_graph")),
                                              dbc.ModalFooter(
                                                  dbc.Button("Close",
                                                             id="tab_trips_popup-close",
                                                             className="ml-auto")
                                              ),
                                          ],
                                          id="tab_trips_popup",
                                          size="xl",
                                      )
                                      ]),
                    dbc.Tab(label="Charge", tab_id="charge", id="tab_charge",
                            children=[figures.battery_table,
                                      dbc.Modal(
                                          [
                                              dbc.ModalHeader(
                                                  "Charging speed"),
                                              dbc.ModalBody(html.Div(
                                                  id="tab_battery_popup_graph")),
                                              dbc.ModalFooter(
                                                  dbc.Button("Close",
                                                             id="tab_battery_popup-close",
                                                             className="ml-auto")
                                              ),
                                          ],
                                          id="tab_battery_popup",
                                          size="xl",
                                      )
                                      ]),
                    dbc.Tab(label="Map", tab_id="map", children=[maps]),
                    dbc.Tab(label="Control", tab_id="control", children=dbc.Tabs(id="control-tabs",
                                                                                 children=__get_control_tabs()))],
                    id="tabs",
                    active_tab="summary",
                    persistence=True),
                html.Div(id=EMPTY_DIV),
                html.Div(id=EMPTY_DIV + "1")
            ])])
        cached_layout = dbc.Container(fluid=True, children=[html.H1('My car info'), data_div])
    return cached_layout