Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions examples/allVehicles.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@


def main():
""" Simple example showing how to retrieve all vehciles from the account """
""" Simple example showing how to retrieve all vehicles from the account """
parser = argparse.ArgumentParser(
prog='allVehciles',
description='Example retrieving all vehciles in the account')
prog='allVehicles',
description='Example retrieving all vehicles in the account')
parser.add_argument('-u', '--username', help='Username of Volkswagen id', required=True)
parser.add_argument('-p', '--password', help='Password of Volkswagen id', required=True)

Expand Down
6 changes: 3 additions & 3 deletions examples/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
def main():
""" Simple example showing how to work with events """
parser = argparse.ArgumentParser(
prog='allVehciles',
description='Example retrieving all vehciles in the account')
prog='allVehicles',
description='Example retrieving all vehicles in the account')
parser.add_argument('-u', '--username', help='Username of Volkswagen id', required=True)
parser.add_argument('-p', '--password', help='Password of Volkswagen id', required=True)

Expand All @@ -32,7 +32,7 @@ def onWeConnectEvent(element, flags):
"""Simple callback example

Args:
element (AddressableObject): Object for which an event occured
element (AddressableObject): Object for which an event occurred
flags (AddressableLeaf.ObserverEvent): Information about the type of the event
"""
if isinstance(element, addressable.AddressableAttribute):
Expand Down
6 changes: 3 additions & 3 deletions examples/savePictures.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
def main():
""" Simple example showing how to save pictures """
parser = argparse.ArgumentParser(
prog='allVehciles',
description='Example retrieving all vehciles in the account')
prog='allVehicles',
description='Example retrieving all vehicles in the account')
parser.add_argument('-u', '--username', help='Username of Volkswagen id', required=True)
parser.add_argument('-p', '--password', help='Password of Volkswagen id', required=True)
parser.add_argument('-o', '--outputDir', help='Output directory', required=True)
Expand All @@ -20,7 +20,7 @@ def saveElement(element, flags):
"""Simple callback for saving the pictures

Args:
element (AddressableObject): Object for which an event occured
element (AddressableObject): Object for which an event occurred
flags (AddressableLeaf.ObserverEvent): Information about the type of the event
"""
del flags
Expand Down
26 changes: 13 additions & 13 deletions tests/test_addressable.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def observe4():
for observerEntry, observer in zip(observerEntries, observers):
assert observerEntry[0] == observer

# Now request only a subset of registred observers
# Now request only a subset of registered observers
observerEntries = addressableLeaf.getObserverEntries(flags=addressable.AddressableLeaf.ObserverEvent.VALUE_CHANGED)
assert len(observerEntries) == 2

Expand Down Expand Up @@ -95,7 +95,7 @@ def test_AddressableLeafParents():
assert addressableLeaf.enabled is True

recursiveChildren = parentAddressableLeaf.getRecursiveChildren()
assert len(recursiveChildren) == 2 # This is two as it is the oarent as well as the child
assert len(recursiveChildren) == 2 # This is two as it is the parent as well as the child
leafChildren = parentAddressableLeaf.getLeafChildren()
assert len(leafChildren) == 1

Expand All @@ -111,19 +111,19 @@ def test_AddressableLeafAdresses():
addressableLeaf = addressable.AddressableLeaf(localAddress='child', parent=parentAddressableLeaf)

getterAddress = addressableLeaf.localAddress
localAdress = addressableLeaf.getLocalAddress()
globalAdress = addressableLeaf.getGlobalAddress()
localAddress = addressableLeaf.getLocalAddress()
globalAddress = addressableLeaf.getGlobalAddress()

assert getterAddress == localAdress
assert localAdress == 'child'
assert globalAdress == 'parent/child'
assert getterAddress == localAddress
assert localAddress == 'child'
assert globalAddress == 'parent/child'

addressableLeaf.localAddress = 'newChild'

localAdress = addressableLeaf.getLocalAddress()
globalAdress = addressableLeaf.getGlobalAddress()
assert localAdress == 'newChild'
assert globalAdress == 'parent/newChild'
localAddress = addressableLeaf.getLocalAddress()
globalAddress = addressableLeaf.getGlobalAddress()
assert localAddress == 'newChild'
assert globalAddress == 'parent/newChild'


def test_AddressableLeafParent():
Expand Down Expand Up @@ -163,7 +163,7 @@ def test_AddressableByAddressString():
assert root.getByAddressString('/') == root


def test_AdressableAttribute():
def test_AddressableAttribute():
attribute = addressable.AddressableAttribute(localAddress='test', parent=None, value=None, valueType=str, lastUpdateFromCar=None)
assert attribute.value is None

Expand All @@ -174,7 +174,7 @@ def test_AdressableAttribute():
attribute.value = 'newValue'


def test_AdressableObjectLeafChildren():
def test_AddressableObjectLeafChildren():
addressableObject = addressable.AddressableObject(localAddress='parent', parent=None)
childAddressableLeaf1 = addressable.AddressableAttribute(localAddress='child1', parent=addressableObject, value=None, valueType=str, lastUpdateFromCar=None)
childAddressableLeaf2 = addressable.AddressableAttribute(localAddress='child2', parent=addressableObject, value=None, valueType=str, lastUpdateFromCar=None)
Expand Down
6 changes: 3 additions & 3 deletions weconnect/addressable.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
LOG: logging.Logger = logging.getLogger("weconnect")


class AddressableLeaf():
class AddressableLeaf:
def __init__(
self,
localAddress: str,
Expand Down Expand Up @@ -268,7 +268,7 @@ def saveToFile(self, filename: str) -> None: # noqa: C901
htmlfile.write('<pre/></body></html>')
else:
htmlfile.write(str(self))
elif filename.endswith(('.json')):
elif filename.endswith('.json'):
with open(filename, mode='w', encoding='utf8') as textfile:
if SUPPORT_IMAGES and SUPPORT_ASCII_IMAGES and isinstance(self.value, Image.Image):
raise ValueError('Attribute is an image and cannot be converted to json')
Expand Down Expand Up @@ -540,7 +540,7 @@ def saveToFile(self, filename: str) -> None: # noqa: C901
elif filename.endswith(('.htm', '.HTM', '.html', '.HTML')):
with open(filename, mode='w', encoding='utf8'):
raise ValueError('Object cannot be saved as HTML')
elif filename.endswith(('.json')):
elif filename.endswith('.json'):
with open(filename, mode='w', encoding='utf8') as textfile:
textfile.write(self.toJSON() + '\n')
elif filename.endswith(('.png', '.PNG')):
Expand Down
4 changes: 2 additions & 2 deletions weconnect/auth/my_cupra_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
elif loginFormResponse.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
else:
raise APICompatibilityError('Retrieving credentials page was not successfull,'
raise APICompatibilityError('Retrieving credentials page was not successful,'
f' status code: {loginFormResponse.status_code}')

# Find login form on page to obtain inputs
Expand Down Expand Up @@ -117,7 +117,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
if login2Response.status_code != requests.codes['ok']: # pylint: disable=E1101
if login2Response.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
raise APICompatibilityError('Retrieving credentials page was not successfull,'
raise APICompatibilityError('Retrieving credentials page was not successful,'
f' status code: {login2Response.status_code}')

credentialsTemplateRegex = r'<script>\s+window\._IDK\s+=\s+\{\s' \
Expand Down
10 changes: 5 additions & 5 deletions weconnect/auth/openid_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def token(self):
@token.setter
def token(self, newToken):
if newToken is not None:
# If new token e.g. after refresh is missing expires_in we assume it is the same than before
# If new token e.g. after refresh is missing expires_in we assume it is the same as before
if 'expires_in' not in newToken:
if self._token is not None and 'expires_in' in self._token:
newToken['expires_in'] = self._token['expires_in']
Expand Down Expand Up @@ -226,22 +226,22 @@ def addToken(self, uri, body=None, headers=None, access_type=AccessType.ACCESS,

if token is None:
if access_type == AccessType.ID:
if not (self.idToken):
if not self.idToken:
raise MissingTokenError(description="Missing id token.")
token = self.idToken
elif access_type == AccessType.REFRESH:
if not (self.refreshToken):
if not self.refreshToken:
raise MissingTokenError(description="Missing refresh token.")
token = self.refreshToken
else:
if not self.authorized:
self.login()
if not (self.accessToken):
if not self.accessToken:
raise MissingTokenError(description="Missing access token.")
if self.expired:
raise TokenExpiredError()
token = self.accessToken

headers = addBearerAuthHeader(token, headers)

return (uri, headers, body)
return uri, headers, body
8 changes: 4 additions & 4 deletions weconnect/auth/session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
LOG = logging.getLogger("weconnect")


class SessionUser():
class SessionUser:
def __init__(self, username: str, password: str) -> None:
self.username = username
self.password = password
Expand All @@ -32,7 +32,7 @@ def __str__(self) -> str:
return self.value


class SessionManager():
class SessionManager:
def __init__(self, tokenstorefile=None) -> None:
if tokenstorefile is not None:
try:
Expand All @@ -48,8 +48,8 @@ def __init__(self, tokenstorefile=None) -> None:
self.tokenstore = {}
self.sessions = {}

def generateHash(service: Service, sessionuser: SessionUser) -> str:
hashstr = service.value + str(sessionuser)
def generateHash(self: Service, sessionuser: SessionUser) -> str:
hashstr = self.value + str(sessionuser)
return hashlib.sha512(hashstr.encode()).hexdigest()

def getSession(self, service: Service, sessionuser: SessionUser) -> Session:
Expand Down
16 changes: 8 additions & 8 deletions weconnect/auth/we_charge_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
elif loginFormResponse.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
else:
raise APICompatibilityError('Retrieving credentials page was not successfull,'
raise APICompatibilityError('Retrieving credentials page was not successful,'
f' status code: {loginFormResponse.status_code}')
# Find login form on page to obtain inputs
emailFormRegex = r'<form.+id=\"emailPasswordForm\".*action=\"(?P<formAction>[^\"]+)\"[^>]*>' \
Expand Down Expand Up @@ -127,7 +127,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
if login2Response.status_code != requests.codes['ok']: # pylint: disable=E1101
if login2Response.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
raise AuthentificationError('Retrieving credentials page was not successfull,'
raise AuthentificationError('Retrieving credentials page was not successful,'
f' status code: {login2Response.status_code}')

credentialsTemplateRegex = r'<script>\s+window\._IDK\s+=\s+\{\s' \
Expand Down Expand Up @@ -243,8 +243,8 @@ def fetchTokens(
loginHeadersForm['accept'] = 'application/json'
loginHeadersForm["x-api-key"] = "yabajourasW9N8sm+9F/oP=="

urlParams = [(('redirect_uri', self.redirect_uri)),
(('code', self.token["code"]))]
urlParams = [('redirect_uri', self.redirect_uri),
('code', self.token["code"])]
token_url = add_params_to_uri(token_url, urlParams)

tokenResponse = self.get(token_url, headers=loginHeadersForm, allow_redirects=False, access_type=AccessType.ID)
Expand Down Expand Up @@ -280,8 +280,8 @@ def refreshTokens(
if headers is None:
headers = self.headers

urlParams = [(('redirect_uri', self.redirect_uri)),
(('refresh_token', refresh_token))]
urlParams = [('redirect_uri', self.redirect_uri),
('refresh_token', refresh_token)]

token_url = add_params_to_uri(token_url, urlParams)

Expand Down Expand Up @@ -317,8 +317,8 @@ def addToken(self, uri, body=None, headers=None, access_type=AccessType.ACCESS,
uri, headers, body = super(WeChargeSession, self).addToken(uri, body=body, headers=headers, access_type=access_type, **kwargs)

if access_type == AccessType.ACCESS:
if not (self.wcAccessToken):
if not self.wcAccessToken:
raise ValueError("Missing wc access token.")
headers['wc_access_token'] = self.wcAccessToken

return (uri, headers, body)
return uri, headers, body
8 changes: 4 additions & 4 deletions weconnect/auth/we_connect_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ def authorizationUrl(self, url, state=None, **kwargs):
if state is not None:
raise AuthentificationError('Do not provide state')

params = [(('redirect_uri', self.redirect_uri)),
(('nonce', generate_nonce()))]
params = [('redirect_uri', self.redirect_uri),
('nonce', generate_nonce())]

authUrl = add_params_to_uri('https://emea.bff.cariad.digital/user-login/v1/authorize', params)

Expand Down Expand Up @@ -131,7 +131,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
elif loginFormResponse.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
else:
raise APICompatibilityError('Retrieving credentials page was not successfull,'
raise APICompatibilityError('Retrieving credentials page was not successful,'
f' status code: {loginFormResponse.status_code}')

# Find login form on page to obtain inputs
Expand Down Expand Up @@ -167,7 +167,7 @@ def doWebAuth(self, authorizationUrl): # noqa: C901
if login2Response.status_code != requests.codes['ok']: # pylint: disable=E1101
if login2Response.status_code == requests.codes['internal_server_error']:
raise RetrievalError('Temporary server error during login')
raise APICompatibilityError('Retrieving credentials page was not successfull,'
raise APICompatibilityError('Retrieving credentials page was not successful,'
f' status code: {login2Response.status_code}')

credentialsTemplateRegex = r'<script>\s+window\._IDK\s+=\s+\{\s' \
Expand Down
2 changes: 1 addition & 1 deletion weconnect/elements/capability_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def update(self, fromDict, ignoreAttributes=None):
self.capabilities.clear()
self.capabilities.enabled = False

super().update(fromDict=fromDict, ignoreAttributes=(ignoreAttributes))
super().update(fromDict=fromDict, ignoreAttributes=ignoreAttributes)

def __str__(self):
string = super().__str__()
Expand Down
2 changes: 1 addition & 1 deletion weconnect/elements/charging_care_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ def update(self, fromDict, ignoreAttributes=None):
def __str__(self):
string = super().__str__()
if self.batteryCareMode.enabled:
string += f'\n\tBattery Care Mode: {self.batteryCareMode.value.value}' # pylint: disable=no-member # this is a fales positive
string += f'\n\tBattery Care Mode: {self.batteryCareMode.value.value}' # pylint: disable=no-member # this is a false positive
return string
2 changes: 1 addition & 1 deletion weconnect/elements/charging_profiles.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def update(self, fromDict): # noqa: C901
self.id.fromDict(fromDict, 'id')
self.localAddress = str(self.id.value)
else:
LOG.error('Charging Proile is missing id attribute')
LOG.error('Charging Profile is missing id attribute')

self.name.fromDict(fromDict, 'name')
self.maxChargingCurrent.fromDict(fromDict, 'maxChargingCurrent')
Expand Down
6 changes: 3 additions & 3 deletions weconnect/elements/charging_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,13 @@ def update(self, fromDict, ignoreAttributes=None):
def __str__(self):
string = super().__str__()
if self.maxChargeCurrentAC.enabled:
string += f'\n\tMaximum Charge Current AC: {self.maxChargeCurrentAC.value.value}' # pylint: disable=no-member # this is a fales positive
string += f'\n\tMaximum Charge Current AC: {self.maxChargeCurrentAC.value.value}' # pylint: disable=no-member # this is a false positive
if self.maxChargeCurrentAC_A.enabled:
string += f'\n\tMaximum Charge Current AC: {self.maxChargeCurrentAC_A.value}'
if self.autoUnlockPlugWhenCharged.enabled:
string += f'\n\tAuto Unlock When Charged: {self.autoUnlockPlugWhenCharged.value.value}' # pylint: disable=no-member # this is a fales positive
string += f'\n\tAuto Unlock When Charged: {self.autoUnlockPlugWhenCharged.value.value}' # pylint: disable=no-member # this is a false positive
if self.autoUnlockPlugWhenChargedAC.enabled:
string += f'\n\tAuto Unlock When Charged AC: {self.autoUnlockPlugWhenChargedAC.value.value}' # pylint: disable=no-member # this is a fales positive
string += f'\n\tAuto Unlock When Charged AC: {self.autoUnlockPlugWhenChargedAC.value.value}' # pylint: disable=no-member # this is a false positive
if self.targetSOC_pct.enabled:
string += f'\n\tTarget SoC: {self.targetSOC_pct.value} %'
return string
12 changes: 3 additions & 9 deletions weconnect/elements/controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,7 @@ def __setAuxiliaryHeatingChange(self, value): # noqa: C901

url = f'https://emea.bff.cariad.digital/vehicle/v1/vehicles/{self.vehicle.vin.value}/auxiliaryheating/{control.value}'

data = {}
data['spin'] = spin
data['duration_min'] = duration
data = {'spin': spin, 'duration_min': duration}

controlResponse = self.vehicle.weConnect.session.post(url, json=data, allow_redirects=True)
if controlResponse.status_code != requests.codes['ok']:
Expand Down Expand Up @@ -317,8 +315,7 @@ def __setAccessControlChange(self, value): # noqa: C901

url = f'https://emea.bff.cariad.digital/vehicle/v1/vehicles/{self.vehicle.vin.value}/access/{control.value}'

data = {}
data['spin'] = spin
data = {'spin': spin}
controlResponse = self.vehicle.weConnect.session.post(url, json=data, allow_redirects=True)
if controlResponse.status_code != requests.codes['ok']:
errorDict = controlResponse.json()
Expand Down Expand Up @@ -361,10 +358,7 @@ def __setHonkAndFlashControlChange(self, value): # noqa: C901
or self.vehicle.domains['parking']['parkingPosition'].latitude.value is None:
raise ControlError('Could not control honkandflash due to unavailability of parking position of the vehicle')

data = {}
data['duration_s'] = duration
data['mode'] = mode
data['userPosition'] = {}
data = {'duration_s': duration, 'mode': mode, 'userPosition': {}}
data['userPosition']['latitude'] = self.vehicle.domains['parking']['parkingPosition'].latitude.value
data['userPosition']['longitude'] = self.vehicle.domains['parking']['parkingPosition'].longitude.value

Expand Down
Loading