diff --git a/libs/charging.py b/libs/charging.py index 5ac92d6..519e08c 100644 --- a/libs/charging.py +++ b/libs/charging.py @@ -39,20 +39,19 @@ class Charging: Database.clean_battery(conn) @staticmethod - def record_charging(car, charging_status, charge_date: datetime, level, latitude, longitude, country_code, - charging_mode): + def record_charging(car, charging_status, charge_date: datetime, level, latitude, # pylint: disable=too-many-locals + longitude, country_code, charging_mode, charging_rate, autonomy): conn = Database.get_db() charge_date = charge_date.replace(microsecond=0) if charging_status == "InProgress": stop_at, start_at = conn.execute("SELECT stop_at, start_at FROM battery WHERE VIN=? ORDER BY start_at " "DESC limit 1", (car.vin,)).fetchone() or [False, None] - if stop_at is None: - try: - conn.execute("INSERT INTO battery_curve(start_at,VIN,date,level) VALUES(?,?,?,?)", - (start_at, car.vin, charge_date, level)) - except IntegrityError: - logger.debug("level already stored") - else: + try: + conn.execute("INSERT INTO battery_curve(start_at,VIN,date,level,rate,autonomy) VALUES(?,?,?,?,?,?)", + (start_at, car.vin, charge_date, level, charging_rate, autonomy)) + except IntegrityError: + logger.debug("level already stored") + if stop_at is not None: conn.execute("INSERT INTO battery(start_at,start_level,charging_mode,VIN) VALUES(?,?,?,?)", (charge_date, level, charging_mode, car.vin)) Ecomix.get_data_from_co2_signal(latitude, longitude, country_code) diff --git a/my_psacc.py b/my_psacc.py index 30e05e8..afce5fd 100644 --- a/my_psacc.py +++ b/my_psacc.py @@ -483,8 +483,10 @@ class MyPSACC: try: charging_status = car.status.get_energy('Electric').charging.status charging_mode = car.status.get_energy('Electric').charging.charging_mode + charging_rate = car.status.get_energy('Electric').charging.charging_rate + autonomy = car.status.get_energy('Electric').autonomy Charging.record_charging(car, charging_status, charge_date, level, latitude, longitude, self.country_code, - charging_mode) + charging_mode, charging_rate, autonomy) logger.debug("charging_status:%s ", charging_status) except AttributeError: logger.error("charging status not available from api") diff --git a/test/test_unit.py b/test/test_unit.py index 60ab5ad..c3141ea 100644 --- a/test/test_unit.py +++ b/test/test_unit.py @@ -12,7 +12,7 @@ from libs.elec_price import ElecPrice from my_psacc import MyPSACC from ecomix import Ecomix from libs.car_model import CarModel -from mylogger import my_logger +from mylogger import my_logger, logger from otp.otp import load_otp, save_otp from charge_control import ChargeControls from trip import Trips @@ -129,10 +129,10 @@ class TestUnit(unittest.TestCase): list(map(dict, conn.execute('PRAGMA database_list').fetchall())) vin = "VR3UHZKXZL" car = Car(vin, "id", "Peugeot") - Charging.record_charging(car, "InProgress", date0, 50, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "InProgress", date1, 75, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "InProgress", date2, 85, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "InProgress", date3, 90, latitude, longitude, "FR", "slow") + Charging.record_charging(car, "InProgress", date0, 50, latitude, longitude, "FR", "slow",20,60) + Charging.record_charging(car, "InProgress", date1, 75, latitude, longitude, "FR", "slow",20,60) + Charging.record_charging(car, "InProgress", date2, 85, latitude, longitude, "FR", "slow",20,60) + Charging.record_charging(car, "InProgress", date3, 90, latitude, longitude, "FR", "slow",20,60) res = Database.get_battery_curve(Database.get_db(), date0, vin) assert len(res) == 3 @@ -148,8 +148,8 @@ class TestUnit(unittest.TestCase): 'occurence': {'day': ['Sat']}}]}}, 'energy': [{'updatedAt': '2021-02-23T22:29:03Z', 'type': 'Fuel', 'level': 0}, {'updatedAt': '2021-04-01T16:17:01Z', 'type': 'Electric', 'level': 70, 'autonomy': 192, - 'charging': {'plugged': False, 'status': 'Disconnected', 'remainingTime': 'PT0S', - 'chargingRate': 0, 'chargingMode': 'No', 'nextDelayedTime': 'PT21H30M'}}], + 'charging': {'plugged': True, 'status': 'InProgress', 'remainingTime': 'PT0S', + 'chargingRate': 20, 'chargingMode': 'Slow', 'nextDelayedTime': 'PT21H30M'}}], 'createdAt': '2021-04-01T16:17:01Z', 'battery': {'voltage': 99, 'current': 0, 'createdAt': '2021-04-01T16:17:01Z'}, 'kinetic': {'createdAt': '2021-03-29T05:16:10Z', 'moving': False}, @@ -196,11 +196,11 @@ class TestUnit(unittest.TestCase): Charging.elec_price = ElecPrice.read_config() start_level = 40 end_level = 85 - Charging.record_charging(car, "InProgress", date0, start_level, latitude, longitude, None, "slow") - Charging.record_charging(car, "InProgress", date1, 70, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "InProgress", date1, 70, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "InProgress", date2, 80, latitude, longitude, "FR", "slow") - Charging.record_charging(car, "Stopped", date3, end_level, latitude, longitude, "FR", "slow") + 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) @@ -213,6 +213,7 @@ class TestUnit(unittest.TestCase): '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} diff --git a/web/db.py b/web/db.py index 2a2e526..03557c5 100644 --- a/web/db.py +++ b/web/db.py @@ -15,7 +15,7 @@ from libs.utils import get_temp NEW_BATTERY_COLUMNS = [["price", "INTEGER"], ["charging_mode", "TEXT"]] NEW_POSITION_COLUMNS = [["level_fuel", "INTEGER"], ["altitude", "INTEGER"]] - +NEW_BATTERY_CURVE_COLUMNS = [["rate", "INTEGER"], ["autonomy", "INTEGER"]] def convert_sql_res(rows): return list(map(dict, rows)) @@ -72,7 +72,7 @@ class Database: if sys.version_info < (3, 7): logger.warning("Can't do database backup, please upgrade to python 3.7") else: - back_conn = sqlite3.connect("info_backup.db") + back_conn = sqlite3.connect(f"info_backup_{datetime.now()}.db") conn.backup(back_conn) back_conn.close() @@ -92,7 +92,10 @@ class Database: "start_level INTEGER, end_level INTEGER, co2 INTEGER, kw INTEGER);") conn.execute("""CREATE TABLE IF NOT EXISTS battery_curve (start_at DATETIME, VIN TEXT, date DATETIME, level INTEGER, UNIQUE(start_at, VIN, level));""") - for table, columns in [["position", NEW_POSITION_COLUMNS], ["battery", NEW_BATTERY_COLUMNS]]: + table_to_update = [["position", NEW_POSITION_COLUMNS], + ["battery", NEW_BATTERY_COLUMNS], + ["battery_curve", NEW_BATTERY_CURVE_COLUMNS]] + for table, columns in table_to_update: for column, column_type in columns: try: conn.execute(f"ALTER TABLE {table} ADD {column} {column_type};") @@ -125,9 +128,9 @@ class Database: @staticmethod def clean_battery(conn): # delete charging longer than 17h - conn.execute("DElETE FROM battery WHERE JULIANDAY(stop_at)-JULIANDAY(start_at)>0.7;") + #conn.execute("DElETE FROM battery WHERE JULIANDAY(stop_at)-JULIANDAY(start_at)>0.7;") # delete charging not finished longer than 17h - conn.execute("DELETE from battery where stop_at is NULL and JULIANDAY()-JULIANDAY(start_at)>0.7;") + #conn.execute("DELETE from battery where stop_at is NULL and JULIANDAY()-JULIANDAY(start_at)>0.7;") #delete little charge conn.execute("DELETE FROM battery WHERE start_level >= end_level-1;")