diff --git a/docs/psa_api.md b/docs/psa_api.md index 9f4841b8..f1fa7502 100644 --- a/docs/psa_api.md +++ b/docs/psa_api.md @@ -46,3 +46,13 @@ 12. Lock (1)/Unlock (0) the doors http://localhost:5000/lock_door/YOURVIN/1 or 0 + +13. Get config + + http://localhost:5000/settings + +14. Change config parameter in config.ini + + http://localhost:5000/settings/electricity_config?night_price=0.2 + + http://127.0.0.1:5000/settings/general?currency=%C2%A3 diff --git a/psa_car_controller/web/tools/utils.py b/psa_car_controller/web/tools/utils.py index db3c09f5..b53ff69e 100644 --- a/psa_car_controller/web/tools/utils.py +++ b/psa_car_controller/web/tools/utils.py @@ -1,3 +1,4 @@ +import typing from datetime import datetime, timedelta import dash_bootstrap_components as dbc @@ -88,3 +89,12 @@ def diff_dashtable(data, data_previous, row_id_name="row_id"): } ) return changes + + +def convert_to_number_if_number_else_return_str(value: str) -> typing.Union[float, int, str]: + if value.isnumeric(): + return int(value) + try: + return float(value) + except ValueError: + return value diff --git a/psa_car_controller/web/view/api.py b/psa_car_controller/web/view/api.py index 4f0bb259..6393b413 100644 --- a/psa_car_controller/web/view/api.py +++ b/psa_car_controller/web/view/api.py @@ -1,14 +1,31 @@ +import logging + from flask import jsonify, request, Response as FlaskResponse from pydantic import BaseModel from psa_car_controller.common.utils import RateLimitException from psa_car_controller.psacc.application.car_controller import PSACarController +from psa_car_controller.psacc.repository.db import Database from psa_car_controller.web.app import app import json + +from psa_car_controller.web.tools.utils import convert_to_number_if_number_else_return_str + +logger = logging.getLogger(__name__) + STYLE_CACHE = None APP = PSACarController() + +def json_response(json: str, status=200): + return app.response_class( + response=json, + status=status, + mimetype='application/json' + ) + + @app.route('/get_vehicles') def get_vehicules(): response = app.response_class( @@ -149,3 +166,19 @@ def lock_door(vin, lock): return jsonify(APP.myp.remote_client.lock_door(vin, lock)) except RateLimitException: return jsonify({"error": "Locks rate limit exceeded"}) + + +@app.route('/settings/') +def settings_section(section: str): + config_section: BaseModel = getattr(APP.config, section.capitalize()) + for key, value in request.args.items(): + typed_value = convert_to_number_if_number_else_return_str(value) + setattr(config_section, key, typed_value) + APP.config.write_config() + return json_response(config_section.json()) + + +@app.route('/settings') +def settings(): + return json_response(APP.config.json()) +