]> git.giorgioravera.it Git - mercedes_me_api.git/commitdiff
Use f strings, fix spelling of retrieve
authorDaniel Rheinbay <danielrheinbay@gmail.com>
Sun, 6 Dec 2020 21:53:48 +0000 (22:53 +0100)
committerGiorgio Ravera <giorgio.ravera@gmail.com>
Thu, 17 Dec 2020 10:13:31 +0000 (11:13 +0100)
* Use Python 3's f strings to format strings.
* Fix spelling of "retrieve" (instead of "retrive")

config.py
custom_components/mercedesmeapi/oauth.py
custom_components/mercedesmeapi/query.py
custom_components/mercedesmeapi/resources.py
mercedes_me_api.py
mercedes_me_api.sh
oauth.py
query.py
resources.py

index e20dce9e681cb2ded23e8c9aa8bd59c4c0d18bd2..a728330323cc3218fa144fec0d067ccb70398d4d 100644 (file)
--- a/config.py
+++ b/config.py
@@ -36,27 +36,27 @@ class MercedesMeConfig:
 
         # 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)
index ac50638fbb893036155c0ea7bbb2fbcf823b1591..b7fd4df8d7d351ee2cd46487814dea9823e32795 100644 (file)
@@ -14,8 +14,8 @@ from .const import *
 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
@@ -39,12 +39,12 @@ class MercedesMeOauth:
         # 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
@@ -105,13 +105,13 @@ class MercedesMeOauth:
     ########################\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
@@ -137,11 +137,11 @@ class MercedesMeOauth:
         )\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
@@ -160,7 +160,7 @@ class MercedesMeOauth:
     ########################\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
index c945be315af11d4105a01088d429654e4c246299..6a148ee3d9d1ba8a7bc8280ffa615ae9dc763e75 100644 (file)
@@ -22,7 +22,7 @@ def GetResource(resourceURL, config):
     # Set Header
     headers = {
         "accept": "application/json;charset=utf-8", 
-        "authorization": "Bearer "+ config.token.access_token
+        "authorization": f"Bearer {config.token.access_token}"
     }
 
     # Send Request
@@ -69,7 +69,7 @@ def GetToken(tokenURL, headers, data):
     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 
         }
index a6fbece4a6f8d88692c35c877697d6a2dd47c905..8a7b62967c907a73c535f4e4ded9f69191f5142f 100644 (file)
@@ -66,7 +66,7 @@ class MercedesMeResource (Entity):
     @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):
@@ -107,7 +107,7 @@ class MercedesMeResources:
         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:
@@ -124,10 +124,10 @@ class MercedesMeResources:
 
         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
@@ -144,13 +144,13 @@ class MercedesMeResources:
     ########################
     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.")
@@ -158,13 +158,13 @@ class MercedesMeResources:
         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
@@ -195,9 +195,9 @@ class MercedesMeResources:
     # 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
@@ -205,18 +205,17 @@ class MercedesMeResources:
     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
index 3a7ef69e5419e638cc9fa522fae4e4707aef532a..a24f91d3c60e80280495817bfcd14abef0fcae7a 100644 (file)
@@ -31,8 +31,8 @@ def ParseInput():
     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:
index 3b64e013bd92bd72ad0e50e0023616dec155cf1a..f37dcb8f8451ec793e583b4ee45ba8d3dd466174 100755 (executable)
@@ -6,7 +6,7 @@
 #
 # 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
@@ -55,10 +55,10 @@ function usage ()
   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
 }
 
@@ -162,7 +162,7 @@ function printStatus ()
 
   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
index 650c8de399b8e2e1725399758b8c3b28113415cf..d0f405d0c7023ae3d5b78679cafb40de2667dd81 100644 (file)
--- a/oauth.py
+++ b/oauth.py
@@ -14,8 +14,8 @@ from const import *
 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__)
@@ -39,12 +39,12 @@ class MercedesMeOauth:
         # 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"
         }
 
@@ -104,13 +104,13 @@ class MercedesMeOauth:
     ########################
     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.")
@@ -136,11 +136,11 @@ class MercedesMeOauth:
         )
 
         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
@@ -159,7 +159,7 @@ class MercedesMeOauth:
     ########################
     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
index 733c6bd8bcfe701fcb9bde6eec62a7cef90ef06b..72d05742f14fe56ce44d2d2fa370678ea059fd45 100644 (file)
--- a/query.py
+++ b/query.py
@@ -22,7 +22,7 @@ def GetResource(resourceURL, config):
     # Set Header
     headers = {
         "accept": "application/json;charset=utf-8", 
-        "authorization": "Bearer "+ config.token.access_token
+        "authorization": f"Bearer {config.token.access_token}"
     }
 
     # Send Request
@@ -69,7 +69,7 @@ def GetToken(tokenURL, headers, data):
     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 
         }
index 3dcdd573eec88b24981d7a4cc3bf3bb7a1ceea31..d56e9470b669339809f673592f1805c25a4c993e 100644 (file)
@@ -63,7 +63,7 @@ class MercedesMeResource:
 
     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."""
@@ -106,7 +106,7 @@ class MercedesMeResources:
         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:
@@ -123,10 +123,10 @@ class MercedesMeResources:
 
         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
@@ -143,13 +143,13 @@ class MercedesMeResources:
     ########################
     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.")
@@ -157,13 +157,13 @@ class MercedesMeResources:
         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
@@ -194,9 +194,9 @@ class MercedesMeResources:
     # 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
@@ -204,18 +204,18 @@ class MercedesMeResources:
     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