code clean

This commit is contained in:
Florian Bezannier
2021-04-21 11:44:46 +02:00
parent 98baca6601
commit 40a7f20d72
28 changed files with 382 additions and 309 deletions
+2 -2
View File
@@ -4,8 +4,8 @@ from datetime import datetime
import requests
from Car import Car
from MyLogger import logger
from libs.car import Car
from mylogger import logger
class Abrp:
+11 -7
View File
@@ -1,9 +1,9 @@
import threading
import locale
import dash
import dash_bootstrap_components as dbc
from flask import Flask
import locale
from werkzeug import run_simple
@@ -12,23 +12,26 @@ try:
except ImportError:
from werkzeug import DispatcherMiddleware
from ChargeControl import ChargeControls
from MyLogger import logger
from MyPSACC import MyPSACC
from charge_control import ChargeControls
from mylogger import logger
from my_psacc import MyPSACC
# pylint: disable=invalid-name
app = None
dash_app = None
dispatcher = None
# noinspection PyTypeChecker
myp:MyPSACC = None
myp: MyPSACC = None
# noinspection PyTypeChecker
chc: ChargeControls = None
def start_app(title, base_path, debug: bool, host, port):
global app, dash_app, dispatcher
try:
lang = locale.getlocale()[0].split("_")[0]
locale.setlocale(locale.LC_TIME, ".".join(locale.getlocale())) #make sure LC_TIME is set
locale.setlocale(locale.LC_TIME, ".".join(locale.getlocale())) # make sure LC_TIME is set
locale_url = [f"https://cdn.plot.ly/plotly-locale-{lang}-latest.js"]
except (IndexError, locale.Error):
locale_url = None
@@ -44,9 +47,10 @@ def start_app(title, base_path, debug: bool, host, port):
dash_app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP], external_scripts=locale_url, title=title,
server=app, requests_pathname_prefix=requests_pathname_prefix)
# keep this line
import web.views
import web.views # pylint: disable=unused-import,import-outside-toplevel
return run_simple(host, port, application, use_reloader=False, use_debugger=debug)
def save_config(my_peugeot: MyPSACC, name):
my_peugeot.save_config(name)
threading.Timer(30, save_config, args=[my_peugeot, name]).start()
+8 -6
View File
@@ -1,13 +1,14 @@
import sqlite3
from datetime import datetime
import pytz
from typing import Callable
import pytz
from MyLogger import logger
from mylogger import logger
callback_fct: Callable[[], None] = lambda: None
default_db_file = 'info.db'
DEFAULT_DB_FILE = 'info.db'
# pylint: disable=invalid-name
db_initialized = False
@@ -37,7 +38,8 @@ def backup(conn):
def init_db(conn):
global db_initialized
conn.execute("CREATE TABLE IF NOT EXISTS position (Timestamp DATETIME PRIMARY KEY, VIN TEXT, longitude REAL, "
"latitude REAL, mileage REAL, level INTEGER, level_fuel INTEGER, moving BOOLEAN, temperature INTEGER);")
"latitude REAL, mileage REAL, level INTEGER, level_fuel INTEGER, moving BOOLEAN,"
" temperature INTEGER);")
make_backup = False
try:
conn.execute("ALTER TABLE position ADD level_fuel INTEGER;")
@@ -61,7 +63,7 @@ def init_db(conn):
db_initialized = True
def get_db(db_file=default_db_file):
def get_db(db_file=DEFAULT_DB_FILE):
sqlite3.register_converter("DATETIME", convert_datetime_from_bytes)
conn = sqlite3.connect(db_file, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
conn.row_factory = sqlite3.Row
@@ -104,4 +106,4 @@ def set_chargings_price(conn, start_at, price):
conn.commit()
if not update:
logger.error("Can't find line to update in the database")
return update
return update
+16 -13
View File
@@ -6,18 +6,18 @@ import numpy as np
from dash_core_components import Graph
from dash_table.Format import Format, Scheme, Symbol
from dateutil.relativedelta import relativedelta
from pandas import DataFrame
import plotly.express as px
import plotly.graph_objects as go
from Trip import Trips
from pandas import DataFrame
from pandas import options as pandas_options
import dash_html_components as html
from trip import Trips
from libs.elec_price import ElecPrice
def unix_time_millis(dt):
return int(dt.timestamp())
def unix_time_millis(date):
return int(date.timestamp())
def get_marks_from_start_end(start, end):
@@ -44,6 +44,7 @@ def get_marks_from_start_end(start, end):
return None
# pylint: disable=invalid-name
consumption_fig = None
consumption_df = None
trips_map = None
@@ -56,6 +57,7 @@ battery_info = dbc.Alert("No data to show", color="danger")
battery_table = None
# pylint: disable=too-many-locals
def get_figures(trips: Trips, charging: list[dict]):
global consumption_fig, consumption_df, trips_map, consumption_fig_by_speed, table_fig, info, battery_info, \
battery_table, consumption_graph_by_temp
@@ -73,7 +75,7 @@ def get_figures(trips: Trips, charging: list[dict]):
trips_map = px.line_mapbox(lat=lats, lon=lons, hover_name=names,
mapbox_style="stamen-terrain", zoom=12)
# table
nb_format = Format(precision=2, scheme=Scheme.fixed, symbol=Symbol.yes)
nb_format = Format(precision=2, scheme=Scheme.fixed, symbol=Symbol.yes) # pylint: disable=no-member
table_fig = dash_table.DataTable(
id='trips-table',
sort_action='native',
@@ -132,12 +134,13 @@ def get_figures(trips: Trips, charging: list[dict]):
data=[{"name": "Average emission:", "value": "{:.1f} g/km".format(co2_per_km)},
{"name": " ", "value:": "{:.1f} g/kWh".format(co2_per_kw)},
{"name": "Average charge speed:", "value": "{:.3f} kW".format(charge_speed)}])
battery_info = html.Div(children=[html.Tr(
[
html.Td('Average emission:', rowSpan=2),
html.Td("{:.1f} g/km".format(co2_per_km)),
]
),
battery_info = html.Div(children=[
html.Tr(
[
html.Td('Average emission:', rowSpan=2),
html.Td("{:.1f} g/km".format(co2_per_km)),
]
),
html.Tr(
[
"{:.1f} g/kWh".format(co2_per_kw),
@@ -152,7 +155,7 @@ def get_figures(trips: Trips, charging: list[dict]):
html.Tr(
[
html.Td('Average Price:', rowSpan=2),
html.Td("{:.2f} {}/100km".format(price_kw*kw_per_km, ElecPrice.currency)),
html.Td("{:.2f} {}/100km".format(price_kw * kw_per_km, ElecPrice.currency)),
]
),
html.Tr(
@@ -175,7 +178,7 @@ def get_figures(trips: Trips, charging: list[dict]):
{'id': 'kw', 'name': 'consumption', 'type': 'numeric',
'format': deepcopy(nb_format).symbol_suffix(" kWh").precision(2)},
{'id': 'price', 'name': 'price', 'type': 'numeric',
'format': deepcopy(nb_format).symbol_suffix(" "+ElecPrice.currency).precision(2)}],
'format': deepcopy(nb_format).symbol_suffix(" " + ElecPrice.currency).precision(2)}],
data=charging,
editable=True
)
+33 -29
View File
@@ -3,16 +3,16 @@ import traceback
from datetime import datetime, timezone
import dash_bootstrap_components as dbc
from dash.dependencies import Output, Input, MATCH, State
from dash.exceptions import PreventUpdate
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq
import pandas as pd
from dash.exceptions import PreventUpdate
from MyLogger import logger
from flask import jsonify, request, Response as FlaskResponse
from Trip import Trips
from mylogger import logger
from trip import Trips
from libs.charging import Charging
from web import figures
@@ -20,6 +20,8 @@ from web import figures
from web.app import app, dash_app, myp, chc
from web.db import set_chargings_price, get_db, set_db_callback
# pylint: disable=invalid-name
RESPONSE = "-response"
EMPTY_DIV = "empty-div"
ABRP_SWITCH = 'abrp-switch'
@@ -38,7 +40,7 @@ def diff_dashtable(data, data_previous, row_id_name="row_id"):
mask = df.ne(df_previous)
df_diff = df[mask].dropna(how="all", axis="columns").dropna(how="all", axis="rows")
changes = []
for idx, row in df_diff.iterrows():
for row in df_diff.items():
row_id = row.name
row.dropna(inplace=True)
for change in row.iteritems():
@@ -88,13 +90,13 @@ def display_value(value):
State("battery-table", "data_previous"),
],
)
def capture_diffs(ts, data, data_previous):
if ts is None:
def capture_diffs(timestamp, data, data_previous):
if timestamp is None:
raise PreventUpdate
diff_data = diff_dashtable(data, data_previous, "start_at")
for el in diff_data:
if el['column_name'] == 'price':
if not set_chargings_price(get_db(), el['start_at'], el['current_value']):
for changed_line in diff_data:
if changed_line['column_name'] == 'price':
if not set_chargings_price(get_db(), changed_line['start_at'], changed_line['current_value']):
logger.error("Can't find line to update in the database")
return ""
@@ -171,7 +173,7 @@ def get_position(vin):
# Set a battery threshold and schedule an hour to stop the charge
@app.route('/charge_control')
def charge_control():
def get_charge_control():
logger.info(request)
vin = request.args['vin']
charge_control = chc.get(vin)
@@ -245,6 +247,7 @@ def __get_control_tabs():
label = car.vin
else:
label = car.label
# pylint: disable=not-callable
tabs.append(dbc.Tab(label=label, id="tab-" + car.vin, children=[
daq.ToggleSwitch(
id={'role': ABRP_SWITCH, 'vin': car.vin},
@@ -262,23 +265,25 @@ def serve_layout():
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],
),
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="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]),
@@ -287,9 +292,8 @@ def serve_layout():
dbc.Tab(label="Control", tab_id="control", children=dbc.Tabs(id="control-tabs",
children=__get_control_tabs()))
],
id="tabs",
active_tab="summary",
),
id="tabs",
active_tab="summary"),
html.Div(id=EMPTY_DIV),
])])
except (IndexError, TypeError, NameError):