mirror of
https://github.com/Dielee/volvo2mqtt.git
synced 2026-07-22 02:13:01 +02:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
016a0193e2 | ||
|
|
c3a798e397 | ||
|
|
89417696bd | ||
|
|
d55dc25647 | ||
|
|
1d193270a4 | ||
|
|
f03ff8953c | ||
|
|
2e95e71661 | ||
|
|
126cc37269 | ||
|
|
cb10fe07c3 | ||
|
|
f3244ccdc0 | ||
|
|
1223853208 | ||
|
|
1f0c52b5a7 | ||
|
|
161c02fc11 | ||
|
|
be4a1b6791 |
@@ -1,3 +1,35 @@
|
||||
## v1.9.0
|
||||
### 🚀 Features:
|
||||
|
||||
- Add check for supported commands
|
||||
- Add Engine start/stop and Engine runtime minutes for supported cars
|
||||
|
||||
## v1.8.19
|
||||
### 🐛 Bug Fixes:
|
||||
|
||||
- Fix Estimated Charging Time not changing to zero #133
|
||||
|
||||
## v1.8.18
|
||||
### 🐛 Bug Fixes:
|
||||
|
||||
- Fix Backend State Sensor returning `null`
|
||||
|
||||
## v1.8.17
|
||||
### 🚀 Features:
|
||||
|
||||
- Move vehicle and vehicle details to v2 endpoint
|
||||
|
||||
### 🐛 Bug Fixes:
|
||||
|
||||
- Fix Battery Charge Level icon update
|
||||
|
||||
## v1.8.16
|
||||
### 🚀 Features:
|
||||
|
||||
- Add `Average energy consumption`, `Distance to empty battery` and `Washer fluid level` sensors
|
||||
- Support force update for `Backend state` Sensor
|
||||
- Use cached requests for fuel endpoint
|
||||
|
||||
## v1.8.15
|
||||
### 🚀 Features:
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
name: "Volvo2Mqtt"
|
||||
description: "Volvo AAOS MQTT bridge"
|
||||
version: "1.8.15"
|
||||
version: "1.9.0"
|
||||
slug: "volvo2mqtt"
|
||||
init: false
|
||||
url: "https://github.com/Dielee/volvo2mqtt"
|
||||
|
||||
+20
-13
@@ -1,10 +1,10 @@
|
||||
from config import settings
|
||||
|
||||
VERSION = "v1.8.15"
|
||||
VERSION = "v1.9.0"
|
||||
|
||||
OAUTH_URL = "https://volvoid.eu.volvocars.com/as/token.oauth2"
|
||||
VEHICLES_URL = "https://api.volvocars.com/connected-vehicle/v1/vehicles"
|
||||
VEHICLE_DETAILS_URL = "https://api.volvocars.com/connected-vehicle/v1/vehicles/{0}"
|
||||
VEHICLES_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles"
|
||||
VEHICLE_DETAILS_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}"
|
||||
WINDOWS_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/windows"
|
||||
CLIMATE_START_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/commands/climatization-start"
|
||||
CLIMATE_STOP_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/commands/climatization-stop"
|
||||
@@ -16,12 +16,14 @@ ODOMETER_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0
|
||||
LOCATION_STATE_URL = "https://api.volvocars.com/location/v1/vehicles/{0}/location"
|
||||
TYRE_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/tyres"
|
||||
ENGINE_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/engine-status"
|
||||
BATTERY_CHARGE_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/fuel"
|
||||
FUEL_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/fuel"
|
||||
FUEL_BATTERY_STATE_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/fuel"
|
||||
STATISTICS_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/statistics"
|
||||
ENGINE_DIAGNOSTICS_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/engine"
|
||||
VEHICLE_DIAGNOSTICS_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/diagnostics"
|
||||
API_BACKEND_STATUS = "https://oip-dev-bff.euwest1.production.volvo.care/api/v1/backend-status"
|
||||
API_BACKEND_STATUS_URL = "https://oip-dev-bff.euwest1.production.volvo.care/api/v1/backend-status"
|
||||
SUPPORTED_COMMANDS_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/commands"
|
||||
ENGINE_START_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/commands/engine-start"
|
||||
ENGINE_STOP_URL = "https://api.volvocars.com/connected-vehicle/v2/vehicles/{0}/commands/engine-stop"
|
||||
|
||||
units = {
|
||||
"en_GB": {
|
||||
@@ -79,7 +81,7 @@ icon_states = {
|
||||
|
||||
supported_entities = [
|
||||
{"name": "Battery Charge Level", "domain": "sensor", "device_class": "battery", "id": "battery_charge_level", "unit": "%", "icon": "car-battery", "url": RECHARGE_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Battery Charge Level", "domain": "sensor", "device_class": "battery", "id": "battery_charge_level", "unit": "%", "icon": "car-battery", "url": BATTERY_CHARGE_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Battery Charge Level", "domain": "sensor", "device_class": "battery", "id": "battery_charge_level", "unit": "%", "icon": "car-battery", "url": FUEL_BATTERY_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Electric Range", "domain": "sensor", "id": "electric_range", "unit": "km" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["electric_range"]["unit"], "icon": "map-marker-distance", "url": RECHARGE_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Estimated Charging Time", "domain": "sensor", "id": "estimated_charging_time", "unit": "minutes", "icon": "timer-sync-outline", "url": RECHARGE_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Charging System Status", "domain": "sensor", "id": "charging_system_status", "icon": "ev-station", "url": RECHARGE_STATE_URL},
|
||||
@@ -100,24 +102,29 @@ supported_entities = [
|
||||
{"name": "Engine Hood", "domain": "binary_sensor", "device_class": "door", "id": "engine_hood", "icon": "car-door-lock", "url": LOCK_STATE_URL},
|
||||
{"name": "Tank Lid", "domain": "binary_sensor", "device_class": "door", "id": "tank_lid", "icon": "car-door-lock", "url": LOCK_STATE_URL},
|
||||
{"name": "Sunroof", "domain": "binary_sensor", "device_class": "door", "id": "sunroof", "icon": "car-door-lock", "url": WINDOWS_STATE_URL},
|
||||
{"name": "Air Conditioning", "domain": "switch", "id": "climate_status", "icon": "air-conditioner"},
|
||||
{"name": "Lock state", "domain": "lock", "id": "lock_status", "icon": "lock", "url": LOCK_STATE_URL},
|
||||
{"name": "Air Conditioning", "domain": "switch", "id": "climate_status", "icon": "air-conditioner", "commands": ["CLIMATIZATION_START", "CLIMATIZATION_STOP"]},
|
||||
{"name": "Engine State", "domain": "switch", "id": "engine_state", "icon": "engine", "url": ENGINE_STATE_URL ,"commands": ["ENGINE_START", "ENGINE_STOP"]},
|
||||
{"name": "Leave in", "domain": "number", "id": "engine_runtime", "unit": "minutes", "icon": "timer-sand", "commands": ["ENGINE_START", "ENGINE_STOP"], "min": 1, "max": 15, "mode": "box"},
|
||||
{"name": "Engine State", "domain": "binary_sensor", "device_class": "running", "id": "engine_state", "icon": "engine", "url": ENGINE_STATE_URL},
|
||||
{"name": "Lock state", "domain": "lock", "id": "lock_status", "icon": "lock", "url": LOCK_STATE_URL, "commands": ["LOCK", "UNLOCK"]},
|
||||
{"name": "Force Update Data", "domain": "button", "id": "update_data", "icon": "update", "url": ""},
|
||||
{"name": "Location", "domain": "device_tracker", "id": "location", "icon": "map-marker-radius", "url": LOCATION_STATE_URL},
|
||||
{"name": "Tire Front Left", "domain": "sensor", "id": "tyre_front_left", "icon": "car-tire-alert", "url": TYRE_STATE_URL},
|
||||
{"name": "Tire Front Right", "domain": "sensor", "id": "tyre_front_right", "icon": "car-tire-alert", "url": TYRE_STATE_URL},
|
||||
{"name": "Tire Rear Left", "domain": "sensor", "id": "tyre_rear_left", "icon": "car-tire-alert", "url": TYRE_STATE_URL},
|
||||
{"name": "Tire Rear Right", "domain": "sensor", "id": "tyre_rear_right", "icon": "car-tire-alert", "url": TYRE_STATE_URL},
|
||||
{"name": "Engine State", "domain": "binary_sensor", "device_class": "running", "id": "engine_state", "icon": "engine", "url": ENGINE_STATE_URL},
|
||||
{"name": "Fuel Level", "domain": "sensor", "id": "fuel_level", "unit": "liters", "icon": "fuel", "url": FUEL_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Fuel Level", "domain": "sensor", "id": "fuel_level", "unit": "liters", "icon": "fuel", "url": FUEL_BATTERY_STATE_URL, "state_class": "measurement"},
|
||||
{"name": "Average Fuel Consumption", "domain": "sensor", "id": "average_fuel_consumption", "unit": "liters", "icon": "fuel", "url": STATISTICS_URL},
|
||||
{"name": "Distance to Empty", "domain": "sensor", "id": "distance_to_empty", "unit": "km" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["distance_to_empty"]["unit"], "icon": "map-marker-distance", "url": STATISTICS_URL, "state_class": "measurement"},
|
||||
{"name": "Average Energy Consumption", "domain": "sensor", "id": "average_energy_consumption", "unit": "kwh", "icon": "car-electric", "url": STATISTICS_URL},
|
||||
{"name": "Distance to Empty Tank", "domain": "sensor", "id": "distance_to_empty_tank", "unit": "km" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["distance_to_empty"]["unit"], "icon": "map-marker-distance", "url": STATISTICS_URL, "state_class": "measurement"},
|
||||
{"name": "Distance to Empty Battery", "domain": "sensor", "id": "distance_to_empty_battery", "unit": "km" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["distance_to_empty"]["unit"], "icon": "map-marker-distance", "url": STATISTICS_URL, "state_class": "measurement"},
|
||||
{"name": "Average Speed", "domain": "sensor", "id": "average_speed", "unit": "km/h" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["average_speed"]["unit"], "icon": "speedometer", "url": STATISTICS_URL, "state_class": "measurement"},
|
||||
{"name": "Hours to Service", "domain": "sensor", "id": "hours_to_service", "unit": "hour", "icon": "wrench-clock", "url": VEHICLE_DIAGNOSTICS_URL},
|
||||
{"name": "Distance to Service", "domain": "sensor", "id": "km_to_service", "unit": "km" if not units.get(settings["babelLocale"]) else units[settings["babelLocale"]]["distance_to_service"]["unit"], "icon": "wrench-clock", "url": VEHICLE_DIAGNOSTICS_URL},
|
||||
{"name": "Time to Service", "domain": "sensor", "id": "time_to_service", "icon": "wrench-clock", "url": VEHICLE_DIAGNOSTICS_URL},
|
||||
{"name": "Service warning status", "domain": "sensor", "id": "service_warning_status", "icon": "alert-outline", "url": VEHICLE_DIAGNOSTICS_URL},
|
||||
{"name": "Washer Fluid Level warning", "domain": "sensor", "id": "washer_fluid_warning", "icon": "alert-outline", "url": VEHICLE_DIAGNOSTICS_URL},
|
||||
{"name": "API Backend status", "domain": "sensor", "id": "api_backend_status", "icon": "alert"}
|
||||
]
|
||||
|
||||
old_entity_ids = ["months_to_service", "service_warning_trigger"]
|
||||
old_entity_ids = ["months_to_service", "service_warning_trigger", "distance_to_empty"]
|
||||
|
||||
+47
-7
@@ -10,7 +10,7 @@ from datetime import datetime
|
||||
from babel.dates import format_datetime
|
||||
from config import settings
|
||||
from const import CLIMATE_START_URL, CLIMATE_STOP_URL, CAR_LOCK_URL, \
|
||||
CAR_UNLOCK_URL, availability_topic, icon_states, old_entity_ids
|
||||
CAR_UNLOCK_URL, ENGINE_START_URL, ENGINE_STOP_URL, availability_topic, icon_states, old_entity_ids
|
||||
|
||||
mqtt_client: mqtt.Client
|
||||
subscribed_topics = []
|
||||
@@ -20,6 +20,7 @@ climate_timer = {}
|
||||
engine_status = {}
|
||||
devices = {}
|
||||
active_schedules = {}
|
||||
engine_runtime = 1
|
||||
|
||||
|
||||
def connect():
|
||||
@@ -70,14 +71,14 @@ def send_car_images(vin, data, device):
|
||||
if entity["id"] == "exterior_image":
|
||||
mqtt_client.publish(
|
||||
url_topic,
|
||||
data["images"]["exteriorDefaultUrl"],
|
||||
data["images"]["exteriorImageUrl"],
|
||||
retain=True
|
||||
)
|
||||
|
||||
if entity["id"] == "interior_image":
|
||||
mqtt_client.publish(
|
||||
url_topic,
|
||||
data["images"]["interiorDefaultUrl"],
|
||||
data["images"]["internalImageUrl"],
|
||||
retain=True
|
||||
)
|
||||
|
||||
@@ -114,6 +115,15 @@ def on_message(client, userdata, msg):
|
||||
elif "update_data" in msg.topic:
|
||||
if payload == "PRESS":
|
||||
update_car_data(True)
|
||||
elif "engine_runtime" in msg.topic:
|
||||
global engine_runtime
|
||||
engine_runtime = int(payload)
|
||||
logging.debug("Updated engine runtime to " + str(engine_runtime) + " minutes!")
|
||||
elif "engine_state" in msg.topic:
|
||||
if payload == "ON":
|
||||
start_engine(vin)
|
||||
elif payload == "OFF":
|
||||
stop_engine(vin)
|
||||
elif "schedule" in msg.topic:
|
||||
try:
|
||||
d = json.loads(payload)
|
||||
@@ -211,6 +221,23 @@ def start_climate(vin):
|
||||
update_car_data()
|
||||
|
||||
|
||||
def start_engine(vin):
|
||||
body = {"runtimeMinutes": engine_runtime}
|
||||
# Start the api call in another thread for HA performance
|
||||
Thread(target=volvo.api_call, args=(ENGINE_START_URL, "POST", vin, None, None, None, body)).start()
|
||||
|
||||
# Set and update switch status
|
||||
update_car_data(False, {"entity_id": "engine_state", "vin": vin, "state": "ON"})
|
||||
|
||||
|
||||
def stop_engine(vin):
|
||||
# Start the api call in another thread for HA performance
|
||||
Thread(target=volvo.api_call, args=(ENGINE_STOP_URL, "POST", vin)).start()
|
||||
|
||||
# Set and update switch status
|
||||
update_car_data(False, {"entity_id": "engine_state", "vin": vin, "state": "OFF"})
|
||||
|
||||
|
||||
def update_loop():
|
||||
create_ha_devices()
|
||||
while True:
|
||||
@@ -226,7 +253,7 @@ def update_car_data(force_update=False, overwrite={}):
|
||||
last_data_update = format_datetime(datetime.now(util.TZ), format="medium", locale=settings["babelLocale"])
|
||||
for vin in volvo.vins:
|
||||
for entity in volvo.supported_endpoints[vin]:
|
||||
if entity["domain"] == "button":
|
||||
if entity["domain"] in ["button", "number"]:
|
||||
continue
|
||||
|
||||
ov_entity_id = ""
|
||||
@@ -244,7 +271,10 @@ def update_car_data(force_update=False, overwrite={}):
|
||||
elif entity["id"] == "active_schedules":
|
||||
state = active_schedules[vin]
|
||||
elif entity["id"] == "api_backend_status":
|
||||
state = volvo.backend_status
|
||||
if force_update:
|
||||
state = volvo.get_backend_status()
|
||||
else:
|
||||
state = volvo.backend_status
|
||||
else:
|
||||
if entity["id"] == ov_entity_id and vin == ov_vin:
|
||||
state = ov_state
|
||||
@@ -256,7 +286,7 @@ def update_car_data(force_update=False, overwrite={}):
|
||||
else:
|
||||
topic = f"homeassistant/{entity['domain']}/{vin}_{entity['id']}/state"
|
||||
|
||||
if state:
|
||||
if state or state == 0:
|
||||
mqtt_client.publish(
|
||||
topic,
|
||||
json.dumps(state) if isinstance(state, dict) or isinstance(state, list) else state
|
||||
@@ -267,8 +297,12 @@ def update_car_data(force_update=False, overwrite={}):
|
||||
def update_ha_device(entity, vin, state):
|
||||
icon_config = icon_states.get(entity["id"])
|
||||
if icon_config and state:
|
||||
logging.debug("Entity " + entity["id"] + " state " + str(state))
|
||||
if isinstance(state, float):
|
||||
icon = util.get_icon_between(icon_config, state)
|
||||
elif state.replace(".", "").isnumeric():
|
||||
state = float(state)
|
||||
icon = util.get_icon_between(icon_config, state)
|
||||
else:
|
||||
icon = icon_config[state]
|
||||
else:
|
||||
@@ -337,11 +371,17 @@ def create_ha_devices():
|
||||
|
||||
if entity.get("domain") == "device_tracker" or entity.get("id") == "active_schedules":
|
||||
config["json_attributes_topic"] = f"homeassistant/{entity['domain']}/{vin}_{entity['id']}/attributes"
|
||||
elif entity.get("domain") in ["switch", "lock", "button"]:
|
||||
elif entity.get("domain") in ["switch", "lock", "button", "number"]:
|
||||
command_topic = f"homeassistant/{entity['domain']}/{vin}_{entity['id']}/command"
|
||||
config["command_topic"] = command_topic
|
||||
subscribed_topics.append(command_topic)
|
||||
mqtt_client.subscribe(command_topic)
|
||||
|
||||
if entity["domain"] == "number":
|
||||
config["min"] = entity["min"]
|
||||
config["max"] = entity["max"]
|
||||
config["mode"] = entity["mode"]
|
||||
|
||||
elif entity.get("domain") == "image":
|
||||
config["url_topic"] = f"homeassistant/{entity['domain']}/{vin}_{entity['id']}/image_url"
|
||||
|
||||
|
||||
+83
-24
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
import logging
|
||||
import requests
|
||||
import mqtt
|
||||
@@ -11,8 +12,9 @@ from babel.dates import format_datetime
|
||||
from json import JSONDecodeError
|
||||
from const import charging_system_states, charging_connection_states, door_states, window_states, \
|
||||
OAUTH_URL, VEHICLES_URL, VEHICLE_DETAILS_URL, RECHARGE_STATE_URL, CLIMATE_START_URL, \
|
||||
WINDOWS_STATE_URL, LOCK_STATE_URL, TYRE_STATE_URL, supported_entities, BATTERY_CHARGE_STATE_URL, \
|
||||
STATISTICS_URL, ENGINE_DIAGNOSTICS_URL, API_BACKEND_STATUS, engine_states
|
||||
WINDOWS_STATE_URL, LOCK_STATE_URL, TYRE_STATE_URL, supported_entities, FUEL_BATTERY_STATE_URL, \
|
||||
STATISTICS_URL, ENGINE_DIAGNOSTICS_URL, API_BACKEND_STATUS_URL, SUPPORTED_COMMANDS_URL, \
|
||||
ENGINE_STATE_URL, engine_states
|
||||
|
||||
session = requests.Session()
|
||||
session.headers = {
|
||||
@@ -27,6 +29,7 @@ vins = []
|
||||
supported_endpoints = {}
|
||||
cached_requests = {}
|
||||
vcc_api_keys = []
|
||||
supported_commands = []
|
||||
backend_status = ""
|
||||
|
||||
|
||||
@@ -54,8 +57,9 @@ def authorize():
|
||||
|
||||
get_vcc_api_keys()
|
||||
get_vehicles()
|
||||
get_supported_commands()
|
||||
check_supported_endpoints()
|
||||
Thread(target=get_backend_status).start()
|
||||
Thread(target=backend_status_loop).start()
|
||||
else:
|
||||
message = auth.json()
|
||||
raise Exception(message["error_description"])
|
||||
@@ -90,6 +94,19 @@ def refresh_auth():
|
||||
refresh_token = data["refresh_token"]
|
||||
|
||||
|
||||
def get_supported_commands():
|
||||
global supported_commands
|
||||
for vin in vins:
|
||||
commands = session.get(SUPPORTED_COMMANDS_URL.format(vin))
|
||||
data = commands.json()
|
||||
if commands.status_code == 200:
|
||||
for command in data["data"]:
|
||||
supported_commands.append(command["command"])
|
||||
else:
|
||||
logging.error("Error getting supported commands: " + str(commands.status_code) + ". " + str(data["error"].get("message")))
|
||||
logging.debug("Supported commands: " + str(supported_commands))
|
||||
|
||||
|
||||
def get_vehicles():
|
||||
global vins
|
||||
if not settings.volvoData["vin"]:
|
||||
@@ -102,9 +119,8 @@ def get_vehicles():
|
||||
else:
|
||||
raise Exception("No vehicle in account " + settings.volvoData["username"] + " found.")
|
||||
else:
|
||||
error = vehicles.json()
|
||||
raise Exception(
|
||||
"Error getting vehicles: " + str(vehicles.status_code) + ". " + str(error["error"].get("message")))
|
||||
"Error getting vehicles: " + str(vehicles.status_code) + ". " + str(data["error"].get("message")))
|
||||
else:
|
||||
if isinstance(settings.volvoData["vin"], list):
|
||||
# If setting is a list, copy
|
||||
@@ -243,21 +259,43 @@ def check_supported_endpoints():
|
||||
for vin in vins:
|
||||
supported_endpoints[vin] = []
|
||||
for entity in supported_entities:
|
||||
if entity["id"] == "battery_charge_level" and entity["url"] == BATTERY_CHARGE_STATE_URL \
|
||||
if entity["id"] == "battery_charge_level" and entity["url"] == FUEL_BATTERY_STATE_URL \
|
||||
and any("battery_charge_level" in d["id"] for d in supported_endpoints[vin]):
|
||||
# If battery charge level could be found in recharge-api, skip the second battery charge sensor
|
||||
continue
|
||||
|
||||
if entity.get('url'):
|
||||
state = api_call(entity["url"], "GET", vin, entity["id"])
|
||||
if entity["id"] == "engine_state" and entity["url"] == ENGINE_STATE_URL \
|
||||
and any("engine_state" in d["id"] for d in supported_endpoints[vin]):
|
||||
# If engine state is supported with commands, skip engine state sensor, as switch
|
||||
# represents the actual engine state
|
||||
continue
|
||||
|
||||
if entity["domain"] in ["switch", "lock", "number"]:
|
||||
state = check_supported_command(entity["commands"])
|
||||
else:
|
||||
state = ""
|
||||
if entity.get('url'):
|
||||
state = api_call(entity["url"], "GET", vin, entity["id"])
|
||||
else:
|
||||
state = ""
|
||||
|
||||
if state is not None:
|
||||
logging.info("Success! " + entity["name"] + " is supported by your vehicle.")
|
||||
logging.info("Success! " + entity["name"] + " (" + entity["domain"] + ") is supported by your vehicle.")
|
||||
supported_endpoints[vin].append(entity)
|
||||
else:
|
||||
logging.info("Failed, " + entity["name"] + " is unfortunately not supported by your vehicle.")
|
||||
logging.info("Failed, " + entity["name"] + " (" + entity["domain"] + ") is unfortunately not supported by your vehicle.")
|
||||
|
||||
|
||||
def check_supported_command(entity_commands):
|
||||
commands_supported = True
|
||||
for entity_command in entity_commands:
|
||||
if entity_command not in supported_commands:
|
||||
commands_supported = False
|
||||
break
|
||||
|
||||
if commands_supported:
|
||||
return ""
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
def initialize_scheduler(vins):
|
||||
@@ -316,26 +354,37 @@ def check_engine_status(vin):
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def get_backend_status():
|
||||
global backend_status
|
||||
def backend_status_loop():
|
||||
while True:
|
||||
response = session.get(API_BACKEND_STATUS, timeout=15)
|
||||
try:
|
||||
data = response.json()
|
||||
backend_status = data["message"] if util.keys_exists(data, "message") else "No warnings"
|
||||
except JSONDecodeError as e:
|
||||
backend_status = "No warnings"
|
||||
|
||||
get_backend_status()
|
||||
# Update every hour
|
||||
time.sleep(3600)
|
||||
|
||||
|
||||
def api_call(url, method, vin, sensor_id=None, force_update=False, key_change=False):
|
||||
def get_backend_status():
|
||||
global backend_status
|
||||
response = session.get(API_BACKEND_STATUS_URL, timeout=15)
|
||||
try:
|
||||
data = response.json()
|
||||
if util.keys_exists(data, "message"):
|
||||
if data["message"]:
|
||||
backend_status = data["message"]
|
||||
else:
|
||||
backend_status = "NO_WARNING"
|
||||
else:
|
||||
backend_status = "NO_WARNING"
|
||||
|
||||
except JSONDecodeError as e:
|
||||
backend_status = "NO_WARNING"
|
||||
return backend_status
|
||||
|
||||
|
||||
def api_call(url, method, vin, sensor_id=None, force_update=False, key_change=False, body=None):
|
||||
if datetime.now(util.TZ) >= token_expires_at:
|
||||
refresh_auth()
|
||||
|
||||
if url in [RECHARGE_STATE_URL, WINDOWS_STATE_URL, LOCK_STATE_URL, TYRE_STATE_URL,
|
||||
STATISTICS_URL, ENGINE_DIAGNOSTICS_URL]:
|
||||
STATISTICS_URL, ENGINE_DIAGNOSTICS_URL, FUEL_BATTERY_STATE_URL]:
|
||||
# Minimize API calls for endpoints with multiple values
|
||||
response = cached_request(url, method, vin, force_update, key_change)
|
||||
if response is None:
|
||||
@@ -351,7 +400,7 @@ def api_call(url, method, vin, sensor_id=None, force_update=False, key_change=Fa
|
||||
elif method == "POST":
|
||||
logging.debug("Starting " + method + " call against " + url)
|
||||
try:
|
||||
response = session.post(url.format(vin), timeout=20)
|
||||
response = session.post(url.format(vin), data=json.dumps(body), timeout=20)
|
||||
except requests.exceptions.RequestException as e:
|
||||
logging.error("Error getting data: " + str(e))
|
||||
return None
|
||||
@@ -553,12 +602,18 @@ def parse_api_data(data, sensor_id=None):
|
||||
"latitude": raw_data["coordinates"][1],
|
||||
"gps_accuracy": 1}
|
||||
return coordinates
|
||||
elif sensor_id == "distance_to_empty":
|
||||
elif sensor_id == "distance_to_empty_tank":
|
||||
if util.keys_exists(data, "distanceToEmptyTank"):
|
||||
distance_to_empty = int(data["distanceToEmptyTank"]["value"])
|
||||
if distance_to_empty > 0:
|
||||
return util.convert_metric_values(data["distanceToEmptyTank"]["value"])
|
||||
return None
|
||||
elif sensor_id == "distance_to_empty_battery":
|
||||
if util.keys_exists(data, "distanceToEmptyBattery"):
|
||||
distance_to_empty = int(data["distanceToEmptyBattery"]["value"])
|
||||
if distance_to_empty > 0:
|
||||
return util.convert_metric_values(data["distanceToEmptyBattery"]["value"])
|
||||
return None
|
||||
elif sensor_id == "hours_to_service":
|
||||
return data["engineHoursToService"]["value"] if util.keys_exists(data, "engineHoursToService") else None
|
||||
elif sensor_id == "km_to_service":
|
||||
@@ -574,5 +629,9 @@ def parse_api_data(data, sensor_id=None):
|
||||
return None
|
||||
elif sensor_id == "service_warning_status":
|
||||
return data["serviceWarning"]["value"] if util.keys_exists(data, "serviceWarning") else None
|
||||
elif sensor_id == "average_energy_consumption":
|
||||
return data["averageEnergyConsumption"]["value"] if util.keys_exists(data, "averageEnergyConsumption") else None
|
||||
elif sensor_id == "washer_fluid_warning":
|
||||
return data["washerFluidLevelWarning"]["value"] if util.keys_exists(data, "washerFluidLevelWarning") else None
|
||||
else:
|
||||
return None
|
||||
|
||||
Reference in New Issue
Block a user