Skip to content

Commit

Permalink
feat: Action status tracking (#170)
Browse files Browse the repository at this point in the history
* fix: reduce force refreshing when not needed

* fix: black styling

* fix: remove lang typo

* fix: black

* feat: track action status to reduce force updates and sleep usage

* fix: improve variable name and minor cleanup

* fix: black action

* Update KiaUvoApiCA.py

Co-authored-by: dahlb <[email protected]>
Co-authored-by: cdnninja <[email protected]>
  • Loading branch information
3 people authored Nov 24, 2021
1 parent e4eda4b commit 47ca3a1
Show file tree
Hide file tree
Showing 6 changed files with 94 additions and 93 deletions.
3 changes: 0 additions & 3 deletions custom_components/kia_uvo/HyundaiBlueLinkAPIUSA.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,6 @@ def stop_climate(self, token: Token):
)
_LOGGER.debug(f"{DOMAIN} - Stop engine response: {response.text}")

def check_action_status(self, token: Token, pAuth, transactionId):
pass

def start_charge(self, token: Token):
pass

Expand Down
45 changes: 21 additions & 24 deletions custom_components/kia_uvo/KiaUvoAPIUSA.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,7 @@

from .const import (
DOMAIN,
BRANDS,
BRAND_HYUNDAI,
BRAND_KIA,
DATE_FORMAT,
VEHICLE_LOCK_ACTION,
)
from .KiaUvoApiImpl import KiaUvoApiImpl
from .Token import Token
Expand Down Expand Up @@ -91,6 +87,9 @@ def __init__(
super().__init__(
username, password, region, brand, use_email_with_geocode_api, pin
)
self.last_action_tracked = True
self.last_action_xid = None
self.last_action_completed = False

# Randomly generate a plausible device id on startup
self.device_id = (
Expand Down Expand Up @@ -157,7 +156,7 @@ def login(self) -> Token:
username = self.username
password = self.password

### Sign In with Email and Password and Get Authorization Code ###
# Sign In with Email and Password and Get Authorization Code

url = self.API_URL + "prof/authUser"

Expand All @@ -176,7 +175,7 @@ def login(self) -> Token:
)
_LOGGER.debug(f"got session id {session_id}")

### Get Vehicles ###
# Get Vehicles
url = self.API_URL + "ownr/gvl"
headers = self.api_headers()
headers["sid"] = session_id
Expand Down Expand Up @@ -303,19 +302,17 @@ def update_vehicle_status(self, token: Token):
token=token, url=url, json_body=body
)

def check_action_status(self, token: Token, xid: str):
time.sleep(15)
completed = False
while not completed:
time.sleep(10)
url = self.API_URL + "cmm/gts"
body = {"xid": xid}
response = self.post_request_with_logging_and_active_session(
token=token, url=url, json_body=body
)
response_json = response.json()
completed = all(v == 0 for v in response_json["payload"].values())
return completed
def check_last_action_status(self, token: Token):
url = self.API_URL + "cmm/gts"
body = {"xid": self.last_action_xid}
response = self.post_request_with_logging_and_active_session(
token=token, url=url, json_body=body
)
response_json = response.json()
self.last_action_completed = all(
v == 0 for v in response_json["payload"].values()
)
return self.last_action_completed

def lock_action(self, token: Token, action):
_LOGGER.debug(f"Action for lock is: {action}")
Expand All @@ -330,7 +327,7 @@ def lock_action(self, token: Token, action):
token=token, url=url
)

self.check_action_status(token, response.headers["Xid"])
self.last_action_xid = response.headers["Xid"]

def start_climate(
self, token: Token, set_temp, duration, defrost, climate, heating
Expand Down Expand Up @@ -358,26 +355,26 @@ def start_climate(
response = self.post_request_with_logging_and_active_session(
token=token, url=url, json_body=body
)
self.check_action_status(token, response.headers["Xid"])
self.last_action_xid = response.headers["Xid"]

def stop_climate(self, token: Token):
url = self.API_URL + "rems/stop"
response = self.get_request_with_logging_and_active_session(
token=token, url=url
)
self.check_action_status(token, response.headers["Xid"])
self.last_action_xid = response.headers["Xid"]

def start_charge(self, token: Token):
url = self.API_URL + "evc/charge"
body = {"chargeRatio": 100}
response = self.post_request_with_logging_and_active_session(
token=token, url=url, json_body=body
)
self.check_action_status(token, response.headers["Xid"])
self.last_action_xid = response.headers["Xid"]

def stop_charge(self, token: Token):
url = self.API_URL + "evc/cancel"
response = self.get_request_with_logging_and_active_session(
token=token, url=url
)
self.check_action_status(token, response.headers["Xid"])
self.last_action_xid = response.headers["Xid"]
68 changes: 32 additions & 36 deletions custom_components/kia_uvo/KiaUvoApiCA.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,14 @@

from datetime import timedelta, datetime
import json
import push_receiver
import random
import requests
from urllib.parse import parse_qs, urlparse
import uuid
import time

from .const import (
DOMAIN,
BRANDS,
BRAND_HYUNDAI,
BRAND_KIA,
DATE_FORMAT,
VEHICLE_LOCK_ACTION,
)
from .KiaUvoApiImpl import KiaUvoApiImpl
from .Token import Token
Expand All @@ -37,6 +31,11 @@ def __init__(
username, password, region, brand, use_email_with_geocode_api, pin
)

self.last_action_tracked = True
self.last_action_xid = None
self.last_action_completed = False
self.last_action_pin_auth = None

if BRANDS[brand] == BRAND_KIA:
self.BASE_URL: str = "kiaconnect.ca"
elif BRANDS[brand] == BRAND_HYUNDAI:
Expand Down Expand Up @@ -64,7 +63,7 @@ def login(self) -> Token:
username = self.username
password = self.password

### Sign In with Email and Password and Get Authorization Code ###
# Sign In with Email and Password and Get Authorization Code

url = self.API_URL + "lgn"
data = {"loginId": username, "password": password}
Expand All @@ -78,7 +77,7 @@ def login(self) -> Token:
_LOGGER.debug(f"{DOMAIN} - Access Token Value {access_token}")
_LOGGER.debug(f"{DOMAIN} - Refresh Token Value {refresh_token}")

### Get Vehicles ###
# Get Vehicles
url = self.API_URL + "vhcllst"
headers = self.API_HEADERS
headers["accessToken"] = access_token
Expand Down Expand Up @@ -181,7 +180,7 @@ def get_location(self, token: Token):
raise Exception("No Location Located")

except:
_LOGGER.warn(f"{DOMAIN} - Get vehicle location failed")
_LOGGER.warning(f"{DOMAIN} - Get vehicle location failed")
response = None
return response
else:
Expand Down Expand Up @@ -229,11 +228,10 @@ def lock_action(self, token: Token, action):
)
response_headers = response.headers
response = response.json()
action_status = self.check_action_status(
token, headers["pAuth"], response_headers["transactionId"]
)
self.last_action_xid = response_headers["transactionId"]
self.last_action_pin_auth = headers["pAuth"]

_LOGGER.debug(f"{DOMAIN} - Received lock_action response {action_status}")
_LOGGER.debug(f"{DOMAIN} - Received lock_action response")

def start_climate(
self, token: Token, set_temp, duration, defrost, climate, heating
Expand Down Expand Up @@ -267,9 +265,9 @@ def start_climate(
response_headers = response.headers
response = response.json()

action_status = self.check_action_status(
token, headers["pAuth"], response_headers["transactionId"]
)
self.last_action_xid = response_headers["transactionId"]
self.last_action_pin_auth = headers["pAuth"]

_LOGGER.debug(f"{DOMAIN} - Received start_climate response {response}")

def start_climate_ev(
Expand Down Expand Up @@ -307,9 +305,8 @@ def start_climate_ev(
response_headers = response.headers
response = response.json()

action_status = self.check_action_status(
token, headers["pAuth"], response_headers["transactionId"]
)
self.last_action_xid = response_headers["transactionId"]
self.last_action_pin_auth = headers["pAuth"]
_LOGGER.debug(f"{DOMAIN} - Received start_climate_ev response {response}")

def stop_climate(self, token: Token):
Expand All @@ -325,11 +322,10 @@ def stop_climate(self, token: Token):
response_headers = response.headers
response = response.json()

action_status = self.check_action_status(
token, headers["pAuth"], response_headers["transactionId"]
)
self.last_action_xid = response_headers["transactionId"]
self.last_action_pin_auth = headers["pAuth"]

_LOGGER.debug(f"{DOMAIN} - Received stop_climate response {action_status}")
_LOGGER.debug(f"{DOMAIN} - Received stop_climate response")

def stop_climate_ev(self, token: Token):
url = self.API_URL + "evc/rfoff"
Expand All @@ -344,28 +340,28 @@ def stop_climate_ev(self, token: Token):
response_headers = response.headers
response = response.json()

action_status = self.check_action_status(
token, headers["pAuth"], response_headers["transactionId"]
)
self.last_action_xid = response_headers["transactionId"]
self.last_action_pin_auth = headers["pAuth"]

_LOGGER.debug(f"{DOMAIN} - Received stop_climate response {action_status}")
_LOGGER.debug(f"{DOMAIN} - Received stop_climate response")

def check_action_status(self, token: Token, pAuth, transactionId):
def check_last_action_status(self, token: Token):
url = self.API_URL + "rmtsts"
headers = self.API_HEADERS
headers["accessToken"] = token.access_token
headers["vehicleId"] = token.vehicle_id
headers["transactionId"] = transactionId
headers["pAuth"] = pAuth
time.sleep(2)
headers["transactionId"] = self.last_action_xid
headers["pAuth"] = self.last_action_pin_auth
response = requests.post(url, headers=headers)
response = response.json()

if response["result"]["transaction"]["apiStatusCode"] == "null":
action_status = self.check_action_status(token, pAuth, transactionId)
return action_status
else:
return response["result"]["transaction"]["apiStatusCode"]
self.last_action_completed = (
response["result"]["transaction"]["apiStatusCode"] != "null"
)
if self.last_action_completed:
action_status = response["result"]["transaction"]["apiStatusCode"]
_LOGGER.debug(f"{DOMAIN} - Last action_status: {action_status}")
return self.last_action_completed

def start_charge(self, token: Token):
url = self.API_URL + "evc/rcstrt"
Expand Down
10 changes: 4 additions & 6 deletions custom_components/kia_uvo/KiaUvoApiImpl.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import logging

from datetime import datetime
from datetime import tzinfo
import push_receiver
import random
import requests
import uuid
from urllib.parse import parse_qs, urlparse

from homeassistant.util import dt as dt_util

Expand All @@ -33,13 +27,17 @@ def __init__(
self.stamps = None
self.region = region
self.brand = brand
self.last_action_tracked = False

def login(self) -> Token:
pass

def get_cached_vehicle_status(self, token: Token):
pass

def check_last_action_status(self, token: Token):
pass

def get_geocoded_location(self, lat, lon):
email_parameter = ""
if self.use_email_with_geocode_api == True:
Expand Down
Loading

0 comments on commit 47ca3a1

Please sign in to comment.