Skip to content

Commit

Permalink
Merge pull request #341 from itchannel/1.56
Browse files Browse the repository at this point in the history
1.56
  • Loading branch information
itchannel authored Oct 13, 2023
2 parents dbdaa35 + 996e757 commit e14cba6
Show file tree
Hide file tree
Showing 7 changed files with 177 additions and 62 deletions.
95 changes: 62 additions & 33 deletions custom_components/fordpass/autonomicData.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,33 @@
import sys
import os
import re
import glob
from datetime import datetime


# Place this script in the /config/custom_components/fordpass folder on your HomeAssistant
# Add the details below
# run from a terminal in the /config/custom_components/fordpass folder: python3 autonomicData.py
# It will create username_status_timestamp.json in the same folder
# Script will automatically redact your VIN, VehicleID, and Geolocation details (lat, long)
# Script will automatically redact your VIN, VehicleID, and Geolocation details (lat, long) by default, but can be turned off

# USER INPUT DATA

# Required: Enter the VIN to query
fp_vin = ""

# Automatically redact json? (True or False) False is only recommended if you would like to save your json for personal use
redaction = True



# Optional: Enter your vehicle year (example: 2023)
vicYear = ""

# Optional: Enter your vehicle model (example: Lightning)
vicModel = ""


#GitHub username to append to the filename
gitHub_username = ""
#FordPass VIN for vehicle to get data from
fp_vin = ""
#Name of the file for the user_fordpass_token.txt from the fordpass-ha integration
fp_token = "_fordpass_token.txt"
# You can turn off print statements if you want to use this script for other purposes (True or False)
verbose = True

def get_autonomic_token(ford_access_token):
url = "https://accounts.autonomic.ai/v1/auth/oidc/token"
Expand All @@ -42,7 +54,7 @@ def get_autonomic_token(ford_access_token):
except requests.exceptions.HTTPError as errh:
print(f"HTTP Error: {errh}")
print(f"Trying refresh token")
get_autonomic_token(ford_refresh_token)
get_autonomic_token(fpRefresh)
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
sys.exit()
Expand Down Expand Up @@ -73,7 +85,8 @@ def get_vehicle_status(vin, access_token):
vehicle_status_data = response.json()

# Redact sensitive information
redact_json(vehicle_status_data, redactionItems)
if redaction:
redact_json(vehicle_status_data, redactionItems)
return vehicle_status_data

except requests.exceptions.HTTPError as errh:
Expand Down Expand Up @@ -106,37 +119,53 @@ def redact_json(data, redaction):
elif isinstance(data, list):
for item in data:
redact_json(item, redaction)


if __name__ == "__main__":
workingDir = "/config/custom_components/fordpass"
if gitHub_username == "":
gitHub_username = 'my'
fordPassDir = "/config/custom_components/fordpass"
existingfordToken = os.path.join(fordPassDir, "*_fordpass_token.txt")
userToken = glob.glob(existingfordToken)

if userToken:
for userTokenMatch in userToken:
with open(userTokenMatch, 'r') as file:
fp_token_data = json.load(file)
fpToken = fp_token_data['access_token']
fpRefresh = fp_token_data['refresh_token']
else:
print(f"Error finding FordPass token text file: {existingfordToken}, {userToken}")
sys.exit()

if fp_vin == "":
print("Please enter your VIN into the python script")
sys.exit()
if fp_token == "":
print("Please enter your FordPass token text file name into the python script")
sys.exit()
elif os.path.isfile(os.path.join(workingDir, fp_token)) == False:
print(f"Error finding FordPass token text file: {os.path.join(workingDir, fp_token)}")
sys.exit()

fp_token = os.path.join(workingDir, fp_token)
# Get FordPass token
with open(fp_token, 'r') as file:
fp_token_data = json.load(file)

ford_access_token = fp_token_data['access_token']
ford_refresh_token = fp_token_data['refresh_token']
if verbose:
print("Starting")
if redaction:
redactionStatus = "_REDACTED"
if verbose:
print("Automatically redacting json")
else:
redactionStatus = ""
if verbose:
print("WARNING: json will contain sensitive information!")
# Exchange Fordpass token for Autonomic Token
autonomic_token = get_autonomic_token(ford_access_token)
autonomic_token = get_autonomic_token(fpToken)
vehicle_status = get_vehicle_status(fp_vin, autonomic_token["access_token"])

current_datetime = datetime.now().strftime("%Y-%m-%d_%H:%M:%S")
fileName = os.path.join(workingDir, f"{gitHub_username}_status_{current_datetime}.json")
if vicYear != "":
vicYear = vicYear.replace(" ", "_") + "-"
if vicModel != "":
vicModel = vicModel.replace(" ", "_")
else:
vicModel = "my"


fileName = os.path.join(fordPassDir, f"{vicYear}{vicModel}_status_{current_datetime}{redactionStatus}.json")

# Write the updated JSON data to the file
# Write the redacted JSON data to the file
with open(fileName, 'w') as file:
json.dump(vehicle_status, file, indent=4)
print("done")
if verbose:
print(f"File saved: {fileName}")
print("Note: json file will be deleted if fordpass-ha is updated")
5 changes: 4 additions & 1 deletion custom_components/fordpass/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"battery": {"icon": "mdi:car-battery"},
"oil": {"icon": "mdi:oil"},
"tirePressure": {"icon": "mdi:car-tire-alert"},
"gps": {"icon": "mdi:radar"},
# "gps": {"icon": "mdi:radar"},
"alarm": {"icon": "mdi:bell"},
"ignitionStatus": {"icon": "hass:power"},
"doorStatus": {"icon": "mdi:car-door"},
Expand All @@ -45,6 +45,9 @@
"elVehCharging": {"icon": "mdi:ev-station"},
"speed": {"icon": "mdi:speedometer"},
"indicators": {"icon": "mdi:engine-outline"},
"coolantTemp" : {"icon": "mdi:coolant-temperature", "state_class": "measurement", "device_class": "temperature"},
"outsideTemp" : {"icon": "mdi:thermometer", "state_class": "measurement", "device_class": "temperature"},
"engineOilTemp" : {"icon": "mdi:oil-temperature", "state_class": "measurement", "device_class": "temperature"},
# "deepSleepInProgress": {
# "icon": "mdi:power-sleep",
# "name": "Deep Sleep Mode Active",
Expand Down
12 changes: 9 additions & 3 deletions custom_components/fordpass/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entry = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]

# Added a check to see if the car supports GPS
if entry.data["metrics"]["position"] is not None:
if "position" in entry.data["metrics"] and entry.data["metrics"]["position"] is not None:
async_add_entities([CarTracker(entry, "gps")], True)
else:
_LOGGER.debug("Vehicle does not support GPS")
Expand Down Expand Up @@ -59,8 +59,14 @@ def device_id(self):

@property
def extra_state_attributes(self):
"""No extra attributes to return"""
return None
atts = {}
if "alt" in self.coordinator.data["metrics"]["position"]["value"]["location"]:
atts["Altitude"] = self.coordinator.data["metrics"]["position"]["value"]["location"]["alt"]
if "gpsCoordinateMethod" in self.coordinator.data["metrics"]["position"]["value"]:
atts["gpsCoordinateMethod"] = self.coordinator.data["metrics"]["position"]["value"]["gpsCoordinateMethod"]
if "gpsDimension" in self.coordinator.data["metrics"]["position"]["value"]:
atts["gpsDimension"] = self.coordinator.data["metrics"]["position"]["value"]["gpsDimension"]
return atts

@property
def icon(self):
Expand Down
15 changes: 11 additions & 4 deletions custom_components/fordpass/fordpass_new.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,11 @@ def __acquire_token(self):
if self.save_token:
if os.path.isfile(self.token_location):
data = self.read_token()
self.token = data["access_token"]
self.refresh_token = data["refresh_token"]
self.expires_at = data["expiry_date"]
self.auto_token = data["auto_token"]
self.auto_expires_at = data["auto_expiry"]
else:
data = {}
data["access_token"] = self.token
Expand All @@ -249,15 +254,13 @@ def __acquire_token(self):
data["expiry_date"] = self.expires_at
data["auto_token"] = self.auto_token
data["auto_expiry"] = self.auto_expires_at
self.token = data["access_token"]
self.expires_at = data["expiry_date"]
_LOGGER.debug(self.auto_token)
_LOGGER.debug(self.auto_expires_at)
if self.auto_token is None or self.auto_expires_at is None:
self.auth()
pass
self.auto_token = data["auto_token"]
self.auto_expires_at = data["auto_expiry"]
# self.auto_token = data["auto_token"]
# self.auto_expires_at = data["auto_expiry"]
if self.expires_at:
if time.time() >= self.expires_at:
_LOGGER.debug("No token, or has expired, requesting new token")
Expand Down Expand Up @@ -407,6 +410,8 @@ def messages(self):
return result["result"]["messages"]
# _LOGGER.debug(result)
_LOGGER.debug(response.text)
if response.status_code == 401:
self.auth()
response.raise_for_status()
return None

Expand Down Expand Up @@ -444,6 +449,8 @@ def vehicles(self):
_LOGGER.debug(result)
return result
_LOGGER.debug(response.text)
if response.status_code == 401:
self.auth()
response.raise_for_status()
return None

Expand Down
2 changes: 1 addition & 1 deletion custom_components/fordpass/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
"loggers": ["custom_components.fordpass"],
"requirements": [],
"ssdp": [],
"version": "0.1.54",
"version": "0.1.56",
"zeroconf": []
}
Loading

0 comments on commit e14cba6

Please sign in to comment.