* Use Python 3's f strings to format strings.
* Fix spelling of "retrieve" (instead of "retrive")
# Read Credentials from file
if not os.path.isfile(self.credentials_file):
- _LOGGER.error ("Credential File " + self.credentials_file + " not found")
+ _LOGGER.error (f"Credential File {self.credentials_file} not found")
return False
try:
f = ConfigObj(self.credentials_file)
except Exception:
- _LOGGER.error ("Wrong "+ self.credentials_file + " file found")
+ _LOGGER.error (f"Wrong {self.credentials_file} file found")
return False
# Client ID
self.client_id = f.get(CONF_CLIENT_ID)
if not self.client_id:
- _LOGGER.error ("No "+ CONF_CLIENT_ID + " found in the configuration")
+ _LOGGER.error ("No {CONF_CLIENT_ID} found in the configuration")
return False
# Client Secret
self.client_secret = f.get(CONF_CLIENT_SECRET)
if not self.client_secret:
- _LOGGER.error ("No "+ CONF_CLIENT_SECRET + " found in the configuration")
+ _LOGGER.error ("No {CONF_CLIENT_SECRET} found in the configuration")
return False
# Vehicle ID
self.vin = f.get(CONF_VEHICLE_ID)
if not self.vin:
- _LOGGER.error ("No "+ CONF_VEHICLE_ID + " found in the configuration")
+ _LOGGER.error ("No {CONF_VEHICLE_ID} found in the configuration")
return False
# Read Token
self.token = MercedesMeOauth(self.client_id, self.client_secret)
from .query import *\r
\r
URL_OAUTH_BASE = "https://id.mercedes-benz.com/as"\r
-URL_OAUTH_AUTH = URL_OAUTH_BASE + "/authorization.oauth2?response_type=code"\r
-URL_OAUTH_TOKEN = URL_OAUTH_BASE + "/token.oauth2"\r
+URL_OAUTH_AUTH = f"{URL_OAUTH_BASE}/authorization.oauth2?response_type=code"\r
+URL_OAUTH_TOKEN = f"{URL_OAUTH_BASE}/token.oauth2"\r
\r
# Logger\r
_LOGGER = logging.getLogger(__name__)\r
# Token File\r
self.token_file = hass.config.path(TOKEN_FILE)\r
# Base64\r
- b64_str = client_id + ":" + client_secret\r
+ b64_str = f"{client_id}:{client_secret}"\r
b64_bytes = base64.b64encode( b64_str.encode('ascii') )\r
self.base64 = b64_bytes.decode('ascii')\r
# Headers\r
self.headers = {\r
- "Authorization": "Basic " + self.base64,\r
+ "Authorization": f"Basic {self.base64}",\r
"content-type": "application/x-www-form-urlencoded"\r
}\r
\r
########################\r
def CheckToken(self, token):\r
if "reason" in token:\r
- _LOGGER.error ("Error retriving token - " + token["reason"] + " (" + str(token["code"]) + ")")\r
+ _LOGGER.error (f"Error retrieving token - {token['reason']} ({token['code']})")\r
return False\r
if "error" in token:\r
if "error_description" in token:\r
- _LOGGER.error ("Error retriving token: " + token["error_description"])\r
+ _LOGGER.error (f"Error retrieving token: {token['error_description']}")\r
else:\r
- _LOGGER.error ("Error retriving token: " + token["error"])\r
+ _LOGGER.error (f"Error retrieving token: {token['error']}")\r
return False\r
if len(token) == 0:\r
_LOGGER.error ("Empty token found.")\r
)\r
\r
print( "Open the browser and insert this link:\n" )\r
- print(auth_url + "\n")\r
+ print(f"{auth_url}\n")\r
print( "Copy the code in the url:")\r
auth_code = input()\r
\r
- data = "grant_type=authorization_code&code=" + auth_code + "&redirect_uri=" + REDIRECT_URL\r
+ data = f"grant_type=authorization_code&code={auth_code}&redirect_uri={REDIRECT_URL}"\r
token = GetToken(URL_OAUTH_TOKEN, self.headers, data)\r
\r
# Check Token\r
########################\r
def RefreshToken(self):\r
\r
- data = "grant_type=refresh_token&refresh_token=" + self.refresh_token\r
+ data = f"grant_type=refresh_token&refresh_token={self.refresh_token}" \r
token = GetToken(URL_OAUTH_TOKEN, self.headers, data)\r
\r
# Check Token\r
# Set Header
headers = {
"accept": "application/json;charset=utf-8",
- "authorization": "Bearer "+ config.token.access_token
+ "authorization": f"Bearer {config.token.access_token}"
}
# Send Request
try:
data = res.json()
except ValueError:
- _LOGGER.error ("Error retriving token " + str(res.status_code))
+ _LOGGER.error (f"Error retrieving token {res.status_code}")
data = { "reason": "No Data",
"code" : res.status_code
}
@property
def name(self):
"""Return the name of the sensor."""
- return self._vin + "_" + self._name
+ return f"{self._vin}_{self.name}"
@property
def state(self):
resources = None
if not os.path.isfile(self.resources_file):
- # Resources File not present - Retriving new one from server
+ # Resources File not present - Retrieving new one from server
_LOGGER.error ("Resource File missing - Creating a new one.")
found = False
else:
if ( not found ):
# Not valid or file missing
- resources = self.RetriveResourcesList()
+ resources = self.RetrieveResourcesList()
if( resources == None ):
# Not found or wrong
- _LOGGER.error ("Error retriving resource list.")
+ _LOGGER.error ("Error retrieving resource list.")
return False
else:
# import and write
########################
def CheckResources(self, resources):
if "reason" in resources:
- _LOGGER.error ("Error retriving available resources - " + resources["reason"] + " (" + str(resources["code"]) + ")")
+ _LOGGER.error (f"Error retrieving available resources - {resources['reason']} ({resources['code']})")
return False
if "error" in resources:
if "error_description" in resources:
- _LOGGER.error ("Error retriving resources: " + resources["error_description"])
+ _LOGGER.error (f"Error retrieving resources: {resources['error_description']}")
else:
- _LOGGER.error ("Error retriving resources: " + resources["error"])
+ _LOGGER.error (f"Error retrieving resources: {resources['error']}")
return False
if len(resources) == 0:
_LOGGER.error ("Empty resources found.")
return True
########################
- # Retrive Resources List
+ # Retrieve Resources List
########################
- def RetriveResourcesList(self):
- resURL = URL_RES_PREFIX + "/vehicles/" + self.mercedesConfig.vin + "/resources"
+ def RetrieveResourcesList(self):
+ resURL = f"{URL_RES_PREFIX}/vehicles/{self.mercedesConfig.vin}/resources"
resources = GetResource(resURL, self.mercedesConfig)
if not self.CheckResources(resources):
- _LOGGER.error ("Error retriving available resources")
+ _LOGGER.error ("Error retrieving available resources")
return None
else:
return resources
# Print Available Resources
########################
def PrintAvailableResources(self):
- print ("Found %d resources" % len(self.database) + ":")
+ print (f"Found {len(self.database)} resources:")
for res in self.database:
- print (res._name + ": " + URL_RES_PREFIX + res._href)
+ print (f"{res._name}: {URL_RES_PREFIX}{res._href}")
########################
# Print Resources State
def PrintResourcesState(self, valid = True):
for res in self.database:
if((not valid) | res._valid):
- print (res._name + ":")
- print ("\tvalid: " + str(res._valid))
- print ("\tstate: " + res._state)
- print ("\ttimestamp: " + str(res._timestamp))
- print ("\tlast_update: " + str(res._lastupdate))
+ print (f"{res._name}:")
+ print (f"\tvalid: {res._valid}")
+ print (f"\tstate: {res._state}")
+ print (f"\ttimestamp: {res._timestamp}")
########################
# Update Resources State
########################
def UpdateResourcesState(self):
for res in self.database:
- result = GetResource(URL_RES_PREFIX + res._href, self.mercedesConfig)
+ result = GetResource(f"{URL_RES_PREFIX}{res._href}", self.mercedesConfig)
if not "reason" in result:
res.UpdateState(result[res._name]["value"], result[res._name]["timestamp"])
# Write Resource File
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--token', action='store_true', help="Procedure to obtatin the Access Token")
parser.add_argument('-r', '--refresh', action='store_true', help="Procedure to refresh the Access Token")
- parser.add_argument('-s', '--status', action='store_true', help="Retrive the Status of your Vehicle")
- parser.add_argument('-R', '--resources', action='store_true', help="Retrive the list of available resources of your Vehicle")
+ parser.add_argument('-s', '--status', action='store_true', help="Retrieve the Status of your Vehicle")
+ parser.add_argument('-R', '--resources', action='store_true', help="Retrieve the list of available resources of your Vehicle")
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + VERSION)
if len(sys.argv)==1:
#
# Change log:
# 28/09/2020 - 0.1 - First Issue
-# 18/10/2020 - 0.2 - Added the possibility to retrive the list of resources available
+# 18/10/2020 - 0.2 - Added the possibility to retrieve the list of resources available
# 03/12/2020 - 0.3 - Fix in resources list
# Script Name & Version
echo "Arguments:"
echo " -t, --token Procedure to obtatin the Access Token (stored into $TOKEN_FILE)"
echo " -r, --refresh Procedure to refresh the Access Token (stored into $TOKEN_FILE)"
- echo " -f, --fuel Retrive the Fuel Status of your Vehicle"
- echo " -l, --lock Retrive the Lock Status of your Vehicle"
- echo " -s, --status Retrive the General Status of your Vehicle"
- echo " -R, --resources Retrive the list of available resources of your Vehicle"
+ echo " -f, --fuel Retrieve the Fuel Status of your Vehicle"
+ echo " -l, --lock Retrieve the Lock Status of your Vehicle"
+ echo " -s, --status Retrieve the General Status of your Vehicle"
+ echo " -R, --resources Retrieve the list of available resources of your Vehicle"
exit
}
for r in "$@"
do
- echo "Retriving $r:"
+ echo "Retrieving $r:"
curl -X GET "$RES_URL/$r" -H "accept: application/json;charset=utf-8" -H "authorization: Bearer $ACCESS_TOKEN"
echo
done
from query import *
URL_OAUTH_BASE = "https://id.mercedes-benz.com/as"
-URL_OAUTH_AUTH = URL_OAUTH_BASE + "/authorization.oauth2?response_type=code"
-URL_OAUTH_TOKEN = URL_OAUTH_BASE + "/token.oauth2"
+URL_OAUTH_AUTH = f"{URL_OAUTH_BASE}/authorization.oauth2?response_type=code"
+URL_OAUTH_TOKEN = f"{URL_OAUTH_BASE}/token.oauth2"
# Logger
_LOGGER = logging.getLogger(__name__)
# Token File
self.token_file = TOKEN_FILE
# Base64
- b64_str = client_id + ":" + client_secret
+ b64_str = f"{client_id}:{client_secret}"
b64_bytes = base64.b64encode( b64_str.encode('ascii') )
self.base64 = b64_bytes.decode('ascii')
# Headers
self.headers = {
- "Authorization": "Basic " + self.base64,
+ "Authorization": f"Basic {self.base64}",
"content-type": "application/x-www-form-urlencoded"
}
########################
def CheckToken(self, token):
if "reason" in token:
- _LOGGER.error ("Error retriving token - " + token["reason"] + " (" + str(token["code"]) + ")")
+ _LOGGER.error (f"Error retrieving token - {token['reason']} ({token['code']})")
return False
if "error" in token:
if "error_description" in token:
- _LOGGER.error ("Error retriving token: " + token["error_description"])
+ _LOGGER.error (f"Error retrieving token: {token['error_description']}")
else:
- _LOGGER.error ("Error retriving token: " + token["error"])
+ _LOGGER.error (f"Error retrieving token: {token['error']}")
return False
if len(token) == 0:
_LOGGER.error ("Empty token found.")
)
print( "Open the browser and insert this link:\n" )
- print(auth_url + "\n")
+ print(f"{auth_url}\n")
print( "Copy the code in the url:")
auth_code = input()
- data = "grant_type=authorization_code&code=" + auth_code + "&redirect_uri=" + REDIRECT_URL
+ data = f"grant_type=authorization_code&code={auth_code}&redirect_uri={REDIRECT_URL}"
token = GetToken(URL_OAUTH_TOKEN, self.headers, data)
# Check Token
########################
def RefreshToken(self):
- data = "grant_type=refresh_token&refresh_token=" + self.refresh_token
+ data = f"grant_type=refresh_token&refresh_token={self.refresh_token}"
token = GetToken(URL_OAUTH_TOKEN, self.headers, data)
# Check Token
# Set Header
headers = {
"accept": "application/json;charset=utf-8",
- "authorization": "Bearer "+ config.token.access_token
+ "authorization": f"Bearer {config.token.access_token}"
}
# Send Request
try:
data = res.json()
except ValueError:
- _LOGGER.error ("Error retriving token " + str(res.status_code))
+ _LOGGER.error (f"Error retrieving token {res.status_code}")
data = { "reason": "No Data",
"code" : res.status_code
}
def name(self):
"""Return the name of the sensor."""
- return self._vin + "_" + self._name
+ return f"{self._vin}_{self.name}"
def state(self):
"""Return state for the sensor."""
resources = None
if not os.path.isfile(self.resources_file):
- # Resources File not present - Retriving new one from server
+ # Resources File not present - Retrieving new one from server
_LOGGER.error ("Resource File missing - Creating a new one.")
found = False
else:
if ( not found ):
# Not valid or file missing
- resources = self.RetriveResourcesList()
+ resources = self.RetrieveResourcesList()
if( resources == None ):
# Not found or wrong
- _LOGGER.error ("Error retriving resource list.")
+ _LOGGER.error ("Error retrieving resource list.")
return False
else:
# import and write
########################
def CheckResources(self, resources):
if "reason" in resources:
- _LOGGER.error ("Error retriving available resources - " + resources["reason"] + " (" + str(resources["code"]) + ")")
+ _LOGGER.error (f"Error retrieving available resources - {resources['reason']} ({resources['code']})")
return False
if "error" in resources:
if "error_description" in resources:
- _LOGGER.error ("Error retriving resources: " + resources["error_description"])
+ _LOGGER.error (f"Error retrieving resources: {resources['error_description']}")
else:
- _LOGGER.error ("Error retriving resources: " + resources["error"])
+ _LOGGER.error (f"Error retrieving resources: {resources['error']}")
return False
if len(resources) == 0:
_LOGGER.error ("Empty resources found.")
return True
########################
- # Retrive Resources List
+ # Retrieve Resources List
########################
- def RetriveResourcesList(self):
- resURL = URL_RES_PREFIX + "/vehicles/" + self.mercedesConfig.vin + "/resources"
+ def RetrieveResourcesList(self):
+ resURL = f"{URL_RES_PREFIX}/vehicles/{self.mercedesConfig.vin}/resources"
resources = GetResource(resURL, self.mercedesConfig)
if not self.CheckResources(resources):
- _LOGGER.error ("Error retriving available resources")
+ _LOGGER.error ("Error retrieving available resources")
return None
else:
return resources
# Print Available Resources
########################
def PrintAvailableResources(self):
- print ("Found %d resources" % len(self.database) + ":")
+ print (f"Found {len(self.database)} resources:")
for res in self.database:
- print (res._name + ": " + URL_RES_PREFIX + res._href)
+ print (f"{res._name}: {URL_RES_PREFIX}{res._href}")
########################
# Print Resources State
def PrintResourcesState(self, valid = True):
for res in self.database:
if((not valid) | res._valid):
- print (res._name + ":")
- print ("\tvalid: " + str(res._valid))
- print ("\tstate: " + res._state)
- print ("\ttimestamp: " + str(res._timestamp))
- print ("\tlast_update: " + str(res._lastupdate))
+ print (f"{res._name}:")
+ print (f"\tvalid: {res._valid}")
+ print (f"\tstate: {res._state}")
+ print (f"\ttimestamp: {res._timestamp}")
+ print (f"\tlast_update: {res._lastupdate}")
########################
# Update Resources State
########################
def UpdateResourcesState(self):
for res in self.database:
- result = GetResource(URL_RES_PREFIX + res._href, self.mercedesConfig)
+ result = GetResource(f"{URL_RES_PREFIX}{res._href}", self.mercedesConfig)
if not "reason" in result:
res.UpdateState(result[res._name]["value"], result[res._name]["timestamp"])
# Write Resource File