fix save charge control config

This commit is contained in:
Florian Bezannier
2020-12-26 12:40:11 +01:00
parent e401754d8e
commit 25368293ca
6 changed files with 67 additions and 57 deletions
+38 -39
View File
@@ -9,45 +9,6 @@ from MyPSACC import MyPSACC
from MyLogger import logger
from psa_connectedcar.rest import ApiException
class ChargeControls:
def __init__(self):
self.list: dict = {}
self._confighash = None
def save_config(self, name="charge_config.json", force=False):
chd = {}
for key, el in self.list.items():
chd[el.vin] = {"percentage_threshold": el.percentage_threshold, "stop_hour": el._stop_hour}
config_str = json.dumps(chd, sort_keys=True, indent=4).encode('utf-8')
new_hash = md5(config_str).hexdigest()
if force or self._confighash != new_hash :
with open(name, "wb") as f:
f.write(config_str)
self._confighash = new_hash
logger.info("save config change")
def load_config(psacc:MyPSACC, name="charge_config.json"):
with open(name, "r") as f:
str = f.read()
chd = json.loads(str)
charge_control_list = ChargeControls()
for vin, el in chd.items():
charge_control_list.list[vin] = ChargeControl(psacc,vin,**el)
return charge_control_list
def get(self,vin):
try:
return self.list[vin]
except KeyError:
return None
def start(self):
for vin, charge_control in self.list.items():
charge_control.start()
class ChargeControl:
periodicity = 120
MQTT_TIMEOUT = 60
@@ -125,3 +86,41 @@ class ChargeControl:
return chd
class ChargeControls:
def __init__(self):
self.list: dict = {}
self._confighash = None
def save_config(self, name="charge_config.json", force=False):
chd = {}
for key, el in self.list.items():
chd[el.vin] = {"percentage_threshold": el.percentage_threshold, "stop_hour": el._stop_hour}
config_str = json.dumps(chd, sort_keys=True, indent=4).encode('utf-8')
new_hash = md5(config_str).hexdigest()
if force or self._confighash != new_hash :
with open(name, "wb") as f:
f.write(config_str)
self._confighash = new_hash
logger.info("save config change")
def load_config(psacc:MyPSACC, name="charge_config.json"):
with open(name, "r") as f:
str = f.read()
chd = json.loads(str)
charge_control_list = ChargeControls()
for vin, el in chd.items():
charge_control_list.list[vin] = ChargeControl(psacc,vin,**el)
return charge_control_list
def get(self,vin) -> ChargeControl:
try:
return self.list[vin]
except KeyError:
return None
def start(self):
for vin, charge_control in self.list.items():
charge_control.start()
+18 -10
View File
@@ -413,16 +413,24 @@ class MyPSACC:
date = res.last_position.properties.updated_at
mileage = res.timed_odometer.mileage
level = res.energy[0]["level"]
try:
conn = get_db()
conn.execute("INSERT INTO position(Timestamp,VIN,longitude,latitude,mileage,level) VALUES(?,?,?,?,?,?)",
(date, vin, longitude, latitude, mileage, level))
conn.commit()
logger.info(f"new position recorded for {vin}")
except sqlite3.IntegrityError:
logger.debug("position already saved")
finally:
conn.close()
charging_status = res.energy[0]['charging']['status']
if mileage == 0: # fix a bug of the api
logger.error(f"The api return a wrong mileage for {vin} : {mileage}")
else:
try:
conn = get_db()
conn.execute("INSERT INTO position(Timestamp,VIN,longitude,latitude,mileage,level) VALUES(?,?,?,?,?,?)",
(date, vin, longitude, latitude, mileage, level))
conn.commit()
logger.info(f"new position recorded for {vin}")
except sqlite3.IntegrityError:
logger.debug("position already saved")
finally:
conn.close()
if charging_status is "InProgress":
#create a new line
pass
elif charging_status is "Stopped" or "Finnished"
@staticmethod
def get_recorded_position():
+2 -1
View File
@@ -7,6 +7,7 @@ import locale
from werkzeug import run_simple, DispatcherMiddleware
from ChargeControl import ChargeControls
from MyLogger import logger
from MyPSACC import MyPSACC
@@ -38,7 +39,7 @@ def start_app(title, base_path, debug: bool, host, port):
myp = None
chc = None
chc: ChargeControls = None
def save_config(my_peugeot: MyPSACC):
+4 -4
View File
@@ -1,18 +1,18 @@
import json
import sqlite3
import traceback
from datetime import datetime, timezone
import dash_bootstrap_components as dbc
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
from MyLogger import logger
from flask import jsonify, request, Response as FlaskResponse
from MyPSACC import MyPSACC
from web import figures
from web.app import app, dash_app, myp, chc, save_config
from web.app import app, dash_app, myp, chc
import web.db
trips = None
@@ -86,11 +86,11 @@ def charge_control():
charge_control = chc.get(vin)
if charge_control is None:
return jsonify("error: VIN not in list")
if 'hour' in request.args or 'minute' in request.args:
if 'hour' in request.args and 'minute' in request.args:
charge_control.set_stop_hour([int(request.args["hour"]), int(request.args["minute"])])
if 'percentage' in request.args:
charge_control.percentage_threshold = int(request.args['percentage'])
myp.save_config()
chc.save_config()
return jsonify(charge_control.get_dict())
+4 -3
View File
@@ -19,9 +19,10 @@ def get_db():
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE IF NOT EXISTS position (Timestamp DATETIME PRIMARY KEY, VIN TEXT, longitude REAL, "
"latitude REAL, mileage REAL, level INTEGER);")
conn.execute("CREATE TABLE IF NOT EXISTS battery (start_at DATETIME PRIMARY KEY,stop_at DATETIME, start_level, "
"end_level)")
conn.create_function("update_trips", 0, update_callback)
conn.execute(
"CREATE TEMP TRIGGER IF NOT EXISTS update_trigger AFTER INSERT ON position BEGIN SELECT update_trips(); END;")
conn.commit()
conn.execute("CREATE TEMP TRIGGER IF NOT EXISTS update_trigger AFTER INSERT ON position BEGIN "
"SELECT update_trips(); END;")
conn.commit()
return conn
+1
View File
@@ -68,6 +68,7 @@ def get_figures(trips: List[Trip]):
table_fig = dash_table.DataTable(
id='trips-table',
sort_action='native',
sort_by=[{'column_id': 'start_at', 'direction': 'desc'}],
columns=[{'id': 'start_at', 'name': 'start at', 'type': 'datetime'},
{'id': 'duration', 'name': 'duration', 'type': 'numeric',
'format': deepcopy(nb_format).symbol_suffix(" min").precision(0)},