podpointclient 1.7.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- podpointclient/__init__.py +0 -0
- podpointclient/charge.py +130 -0
- podpointclient/charge_mode.py +7 -0
- podpointclient/charge_override.py +42 -0
- podpointclient/client.py +419 -0
- podpointclient/connectivity_status.py +206 -0
- podpointclient/endpoints.py +35 -0
- podpointclient/errors.py +42 -0
- podpointclient/factories.py +108 -0
- podpointclient/helpers/__init__.py +1 -0
- podpointclient/helpers/api_wrapper.py +197 -0
- podpointclient/helpers/auth.py +276 -0
- podpointclient/helpers/functions.py +42 -0
- podpointclient/helpers/session.py +58 -0
- podpointclient/pod.py +453 -0
- podpointclient/schedule.py +48 -0
- podpointclient/user.py +255 -0
- podpointclient/version.py +3 -0
- podpointclient-1.7.0.dist-info/METADATA +129 -0
- podpointclient-1.7.0.dist-info/RECORD +23 -0
- podpointclient-1.7.0.dist-info/WHEEL +5 -0
- podpointclient-1.7.0.dist-info/licenses/LICENSE +21 -0
- podpointclient-1.7.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Connectivity State class, represents a 'Connectivity State' from the podpoint apis"""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime, timedelta
|
|
4
|
+
from typing import Dict, Any, List
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from .helpers.functions import lazy_convert_to_datetime, lazy_iso_format_datetime
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
# {
|
|
10
|
+
# "ppid": "PSL-266056",
|
|
11
|
+
# "evses": [{
|
|
12
|
+
# "id": 1,
|
|
13
|
+
# "connectivityState": {
|
|
14
|
+
# "protocol": "POW",
|
|
15
|
+
# "connectivityStatus": "ONLINE",
|
|
16
|
+
# "signalStrength": -68,
|
|
17
|
+
# "lastMessageAt": "2024-04-05T18:36:29Z",
|
|
18
|
+
# "connectionStartedAt": "2024-04-05T18:26:26.819Z",
|
|
19
|
+
# "connectionQuality": 3
|
|
20
|
+
# },
|
|
21
|
+
# "connectors": [{
|
|
22
|
+
# "id": 1,
|
|
23
|
+
# "door": "A",
|
|
24
|
+
# "chargingState": "SUSPENDED_EV"
|
|
25
|
+
# }],
|
|
26
|
+
# "architecture": "arch3",
|
|
27
|
+
# "energyOfferStatus": {
|
|
28
|
+
# "isOfferingEnergy": true,
|
|
29
|
+
# "reason": "CHARGE_SCHEDULE",
|
|
30
|
+
# "until": null,
|
|
31
|
+
# "randomDelay": null,
|
|
32
|
+
# "doNotCache": false
|
|
33
|
+
# }
|
|
34
|
+
# }],
|
|
35
|
+
# "connectedComponents": ["evses"]
|
|
36
|
+
# }
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class Evse:
|
|
40
|
+
"""Represents a Location within a charge from pod point"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, data: Dict[str, Any]):
|
|
43
|
+
self.id: int = data.get('id', None)
|
|
44
|
+
self.architecture: str = data.get('architecture', None)
|
|
45
|
+
|
|
46
|
+
connectivity_state_data = data.get('connectivityState', {})
|
|
47
|
+
self.connectivity_state = self.ConnectivityState(data=connectivity_state_data)
|
|
48
|
+
|
|
49
|
+
connectors_data = data.get('connectors', [])
|
|
50
|
+
self.connectors = []
|
|
51
|
+
for connector in connectors_data:
|
|
52
|
+
self.connectors.append(self.Connector(data=connector))
|
|
53
|
+
|
|
54
|
+
energy_offer_status_data = data.get('energyOfferStatus', {})
|
|
55
|
+
self.energy_offer_status = self.EnergyOfferStatus(data=energy_offer_status_data)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def dict(self):
|
|
59
|
+
return {
|
|
60
|
+
"id": self.id,
|
|
61
|
+
"architecture": self.architecture,
|
|
62
|
+
"connectivityState": self.connectivity_state.dict,
|
|
63
|
+
"connectors": [connector.dict for connector in self.connectors],
|
|
64
|
+
"energyOfferStatus": self.energy_offer_status.dict
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class ConnectivityState:
|
|
69
|
+
"""Represents a Location within a charge from pod point"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, data: Dict[str, Any]):
|
|
72
|
+
self.protocol: str = data.get('protocol', None)
|
|
73
|
+
self.connectivity_status: str = data.get('connectivityStatus', None)
|
|
74
|
+
self.signal_strength:int = data.get('signalStrength', None)
|
|
75
|
+
self.last_message_at: datetime = lazy_convert_to_datetime(data.get('lastMessageAt', None))
|
|
76
|
+
self.connection_started_at: datetime = lazy_convert_to_datetime(data.get('connectionStartedAt', None))
|
|
77
|
+
self.connection_quality: int = data.get('connectionQuality', None)
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def dict(self):
|
|
81
|
+
return {
|
|
82
|
+
"protocol": self.protocol,
|
|
83
|
+
"connectivityStatus": self.connectivity_status,
|
|
84
|
+
"signalStrength": self.signal_strength,
|
|
85
|
+
"lastMessageAt": lazy_iso_format_datetime(self.last_message_at),
|
|
86
|
+
"connectionStartedAt": lazy_iso_format_datetime(self.connection_started_at),
|
|
87
|
+
"connectionQuality": self.connection_quality
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
def to_json(self):
|
|
91
|
+
"""JSON representation of a ConnectivityState object"""
|
|
92
|
+
return json.dumps(self.dict, ensure_ascii=False)
|
|
93
|
+
|
|
94
|
+
@dataclass
|
|
95
|
+
class Connector:
|
|
96
|
+
"""Represents a Location within a charge from pod point"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, data: Dict[str, Any]):
|
|
99
|
+
self.id: int = data.get('id', None)
|
|
100
|
+
self.door: str = data.get('door', None)
|
|
101
|
+
self.charging_state: str = data.get('chargingState', None)
|
|
102
|
+
|
|
103
|
+
@property
|
|
104
|
+
def dict(self):
|
|
105
|
+
return {
|
|
106
|
+
"id": self.id,
|
|
107
|
+
"door": self.door,
|
|
108
|
+
"chargingState": self.charging_state
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
def to_json(self):
|
|
112
|
+
"""JSON representation of a ConnectivityState object"""
|
|
113
|
+
return json.dumps(self.dict, ensure_ascii=False)
|
|
114
|
+
|
|
115
|
+
def to_json(self):
|
|
116
|
+
"""JSON representation of a ConnectivityState object"""
|
|
117
|
+
return json.dumps(self.dict, ensure_ascii=False)
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class EnergyOfferStatus:
|
|
121
|
+
"""Represents a Location within a charge from pod point"""
|
|
122
|
+
|
|
123
|
+
def __init__(self, data: Dict[str, Any]):
|
|
124
|
+
self.is_offering_energy: bool = data.get('isOfferingEnergy', None)
|
|
125
|
+
self.reason: str = data.get('reason', None)
|
|
126
|
+
self.until: datetime = lazy_convert_to_datetime(data.get('until', None))
|
|
127
|
+
self.random_delay = data.get('randomDelay', None)
|
|
128
|
+
self.do_not_cache: bool = data.get('doNotCache', None)
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def dict(self):
|
|
132
|
+
return {
|
|
133
|
+
"isOfferingEnergy": self.is_offering_energy,
|
|
134
|
+
"reason": self.reason,
|
|
135
|
+
"until": lazy_iso_format_datetime(self.until),
|
|
136
|
+
"randomDelay": self.random_delay,
|
|
137
|
+
"doNotCache": self.do_not_cache
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
def to_json(self):
|
|
141
|
+
"""JSON representation of a ConnectivityState object"""
|
|
142
|
+
return json.dumps(self.dict, ensure_ascii=False)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class ConnectivityStatus:
|
|
146
|
+
"""Representation of a Connectivity State from pod point"""
|
|
147
|
+
|
|
148
|
+
def __init__(self, data: Dict[str, Any]):
|
|
149
|
+
self.ppid: int = data.get('ppid', None)
|
|
150
|
+
self.connected_components: List[str] = data.get('connectedComponents', [])
|
|
151
|
+
|
|
152
|
+
self.evses: List[Evse] = []
|
|
153
|
+
for evse in data.get('evses', []):
|
|
154
|
+
self.evses.append(Evse(data=evse))
|
|
155
|
+
|
|
156
|
+
@property
|
|
157
|
+
def dict(self) -> Dict[str, Any]:
|
|
158
|
+
return {
|
|
159
|
+
"ppid": self.ppid,
|
|
160
|
+
"connected_components": self.connected_components,
|
|
161
|
+
"evses": [evse.dict for evse in self.evses]
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def _first_evse(self):
|
|
166
|
+
return self.evses[0] if self.evses else None
|
|
167
|
+
|
|
168
|
+
@property
|
|
169
|
+
def connectivity_status(self):
|
|
170
|
+
"""Return the connectivity status of the first evse"""
|
|
171
|
+
evse = self._first_evse
|
|
172
|
+
if evse is None or evse.connectivity_state is None:
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
return evse.connectivity_state.connectivity_status
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def last_message_at(self):
|
|
179
|
+
"""Return the last message at of the first evse"""
|
|
180
|
+
evse = self._first_evse
|
|
181
|
+
if evse is None or evse.connectivity_state is None:
|
|
182
|
+
return None
|
|
183
|
+
|
|
184
|
+
return evse.connectivity_state.last_message_at
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def charging_state(self):
|
|
188
|
+
"""Return the charging state of the first evse"""
|
|
189
|
+
evse = self._first_evse
|
|
190
|
+
if evse is None or not evse.connectors or evse.connectors[0] is None:
|
|
191
|
+
return None
|
|
192
|
+
|
|
193
|
+
return evse.connectors[0].charging_state
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def offering_energy(self):
|
|
197
|
+
"""Return the offering energy of the first evse"""
|
|
198
|
+
evse = self._first_evse
|
|
199
|
+
if evse is None or evse.energy_offer_status is None:
|
|
200
|
+
return None
|
|
201
|
+
|
|
202
|
+
return evse.energy_offer_status.is_offering_energy
|
|
203
|
+
|
|
204
|
+
def to_json(self):
|
|
205
|
+
"""JSON representation of a ConnectivityState object"""
|
|
206
|
+
return json.dumps(self.dict, ensure_ascii=False)
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Endpoints from PodPoint"""
|
|
2
|
+
|
|
3
|
+
AUTH = '/auth'
|
|
4
|
+
SESSIONS = '/sessions'
|
|
5
|
+
USERS = '/users'
|
|
6
|
+
PODS = '/pods'
|
|
7
|
+
UNITS = '/units'
|
|
8
|
+
CHARGE_SCHEDULES = '/charge-schedules'
|
|
9
|
+
CHARGES = '/charges'
|
|
10
|
+
CHARGE_OVERRIDE = '/charge-override'
|
|
11
|
+
CHARGERS = '/chargers'
|
|
12
|
+
CONNECTIVITY_STATUS = '/connectivity-status'
|
|
13
|
+
FIRMWARE = '/firmware'
|
|
14
|
+
|
|
15
|
+
MOBILE_API_BASE = 'mobile-api.pod-point.com'
|
|
16
|
+
API_BASE = f"{MOBILE_API_BASE}/api3/"
|
|
17
|
+
API_VERSION = 'v5'
|
|
18
|
+
API_BASE_URL = f"https://{API_BASE}{API_VERSION}"
|
|
19
|
+
|
|
20
|
+
MOBILE_API_BASE_URL = f"https://{MOBILE_API_BASE}"
|
|
21
|
+
|
|
22
|
+
"""Google endpoint, used for auth"""
|
|
23
|
+
GOOGLE_KEY = '?key=AIzaSyCwhF8IOl_7qHXML0pOd5HmziYP46IZAGU'
|
|
24
|
+
PASSWORD_VERIFY = f"/verifyPassword{GOOGLE_KEY}"
|
|
25
|
+
TOKEN = f"/token{GOOGLE_KEY}"
|
|
26
|
+
|
|
27
|
+
GOOGLE_BASE = 'www.googleapis.com/identitytoolkit/v3/relyingparty'
|
|
28
|
+
GOOGLE_BASE_URL = f"https://{GOOGLE_BASE}"
|
|
29
|
+
|
|
30
|
+
GOOGLE_TOKEN_BASE = 'securetoken.googleapis.com/v1'
|
|
31
|
+
GOOGLE_TOKEN_BASE_URL = f"https://{GOOGLE_TOKEN_BASE}"
|
|
32
|
+
|
|
33
|
+
GOOGLE_MFA_BASE_URL = "https://identitytoolkit.googleapis.com/v2/accounts/mfaSignIn"
|
|
34
|
+
MFA_START = f"{GOOGLE_MFA_BASE_URL}:start{GOOGLE_KEY}"
|
|
35
|
+
MFA_FINALIZE = f"{GOOGLE_MFA_BASE_URL}:finalize{GOOGLE_KEY}"
|
podpointclient/errors.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Custom errors"""
|
|
2
|
+
|
|
3
|
+
class APIError(Exception):
|
|
4
|
+
"""The most generic APIError"""
|
|
5
|
+
|
|
6
|
+
class AuthError(APIError):
|
|
7
|
+
"""An error relating to authentication with pod point"""
|
|
8
|
+
def __init__(self, status, response):
|
|
9
|
+
self.status = status
|
|
10
|
+
message = f'Auth Error ({status}) - {response}'
|
|
11
|
+
super().__init__(message)
|
|
12
|
+
|
|
13
|
+
class MfaRequired(AuthError):
|
|
14
|
+
"""The password was accepted and an SMS challenge must be completed."""
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
super().__init__(200, "Two-step verification is required")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MfaError(AuthError):
|
|
21
|
+
"""The SMS challenge could not be started or completed."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class MfaInvalidCode(MfaError):
|
|
25
|
+
"""The verification code is incorrect and can be retried."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SessionError(APIError):
|
|
29
|
+
"""An error relating to session creation with pod point"""
|
|
30
|
+
def __init__(self, status, response):
|
|
31
|
+
message = f'Session Error ({status}) - {response}'
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
|
|
34
|
+
class ApiConnectionError(APIError):
|
|
35
|
+
"""An error relating to connecting to pod point"""
|
|
36
|
+
def __init__(self, message):
|
|
37
|
+
super().__init__(f'Connection Error: {message}')
|
|
38
|
+
|
|
39
|
+
class ChargeOverrideValidationError(Exception):
|
|
40
|
+
"""An error relating to connecting to pod point"""
|
|
41
|
+
def __init__(self):
|
|
42
|
+
super().__init__(f'A validate error occured when processing charge override. Please ensure that an hour, minute or second value is passed and that it is > 0.')
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
"""Factories used to create top level objects such as pods, sessions and charges"""
|
|
2
|
+
from typing import Dict, Any, List
|
|
3
|
+
from .pod import Pod, Firmware
|
|
4
|
+
from .user import User
|
|
5
|
+
from .schedule import Schedule, ScheduleStatus
|
|
6
|
+
from .charge import Charge
|
|
7
|
+
from .charge_override import ChargeOverride
|
|
8
|
+
from .connectivity_status import ConnectivityStatus
|
|
9
|
+
|
|
10
|
+
class PodFactory:
|
|
11
|
+
"""Factory for creating Pod objects"""
|
|
12
|
+
def build_pods(self, pods_response: Dict[str, Any]) -> List[Pod]:
|
|
13
|
+
"""Build a number of pod objects based off of a response from pod point"""
|
|
14
|
+
pods = []
|
|
15
|
+
|
|
16
|
+
pods_data = pods_response.get('pods', None) if pods_response is not None else None
|
|
17
|
+
if pods_data is None:
|
|
18
|
+
return pods
|
|
19
|
+
|
|
20
|
+
for pod_data in pods_data:
|
|
21
|
+
pods.append(Pod(data=pod_data))
|
|
22
|
+
|
|
23
|
+
return pods
|
|
24
|
+
|
|
25
|
+
class ScheduleFactory:
|
|
26
|
+
"""Factory for creating Schedule objects"""
|
|
27
|
+
def build_schedules(
|
|
28
|
+
self,
|
|
29
|
+
enabled: bool,
|
|
30
|
+
start_time: str = "00:00:00",
|
|
31
|
+
end_time: str = "00:00:01"
|
|
32
|
+
) -> List[Schedule]:
|
|
33
|
+
"""Build a number of schedule objects based off of a response from pod point"""
|
|
34
|
+
schedules = []
|
|
35
|
+
|
|
36
|
+
for iterator in range(7):
|
|
37
|
+
day = iterator + 1
|
|
38
|
+
|
|
39
|
+
schedule = Schedule(
|
|
40
|
+
start_day=day,
|
|
41
|
+
start_time=start_time,
|
|
42
|
+
end_day=day,
|
|
43
|
+
end_time=end_time,
|
|
44
|
+
status=ScheduleStatus(is_active=enabled)
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
schedules.append(schedule)
|
|
48
|
+
|
|
49
|
+
return schedules
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class ChargeFactory:
|
|
53
|
+
"""Factory for creating Charge objects"""
|
|
54
|
+
def build_charges(self, charge_response: Dict[str, Any]) -> List[Charge]:
|
|
55
|
+
"""Build a list of charge objects based off of a response from pod point"""
|
|
56
|
+
charges = []
|
|
57
|
+
|
|
58
|
+
charge_data = charge_response.get('charges', None) if charge_response is not None else None
|
|
59
|
+
if charge_data is None:
|
|
60
|
+
return charges
|
|
61
|
+
|
|
62
|
+
for charge in charge_data:
|
|
63
|
+
charges.append(Charge(data=charge))
|
|
64
|
+
|
|
65
|
+
return charges
|
|
66
|
+
|
|
67
|
+
class ChargeOverrideFactory:
|
|
68
|
+
"""Factory for creating Charge objects"""
|
|
69
|
+
def build_charge_override(self, charge_override_response: Dict[str, Any]) -> ChargeOverride:
|
|
70
|
+
"""Build a list of charge objects based off of a response from pod point"""
|
|
71
|
+
if charge_override_response is None:
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
return ChargeOverride(data=charge_override_response)
|
|
75
|
+
|
|
76
|
+
class FirmwareFactory:
|
|
77
|
+
"""Factory for creating Firmware objects"""
|
|
78
|
+
def build_firmwares(self, firmware_response: Dict[str, Any]) -> List[Firmware]:
|
|
79
|
+
"""Build a list of firmware objects based off of a response from pod point"""
|
|
80
|
+
firmwares = []
|
|
81
|
+
|
|
82
|
+
firmware_data = firmware_response.get('data', None) if firmware_response is not None else None
|
|
83
|
+
if firmware_data is None:
|
|
84
|
+
return firmwares
|
|
85
|
+
|
|
86
|
+
for firmware in firmware_data:
|
|
87
|
+
firmwares.append(Firmware(data=firmware))
|
|
88
|
+
|
|
89
|
+
return firmwares
|
|
90
|
+
|
|
91
|
+
class UserFactory:
|
|
92
|
+
"""Factory for creating User objects"""
|
|
93
|
+
def build_user(self, user_response: Dict[str, Any]) -> User:
|
|
94
|
+
"""Build a user object based off of a response from pod point"""
|
|
95
|
+
user_data = user_response.get('users', None) if user_response is not None else None
|
|
96
|
+
if user_data is None:
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
return User(data=user_data)
|
|
100
|
+
|
|
101
|
+
class ConnectivityStatusFactory:
|
|
102
|
+
"""Factory for creating ConnectivityStatus objects"""
|
|
103
|
+
def build_connectivity_status(self, connectivity_status_response: Dict[str, Any]):
|
|
104
|
+
"""Build a ConnectivityStatus object based off of a response from pod point"""
|
|
105
|
+
if connectivity_status_response is None:
|
|
106
|
+
return None
|
|
107
|
+
|
|
108
|
+
return ConnectivityStatus(data=connectivity_status_response)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Helpers module"""
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Wrapper around calls to the pod point API"""
|
|
2
|
+
import asyncio
|
|
3
|
+
from typing import Any, Dict
|
|
4
|
+
import time
|
|
5
|
+
import logging
|
|
6
|
+
from socket import gaierror
|
|
7
|
+
import aiohttp
|
|
8
|
+
import async_timeout
|
|
9
|
+
|
|
10
|
+
from ..errors import APIError, AuthError, SessionError, ApiConnectionError
|
|
11
|
+
|
|
12
|
+
TIMEOUT=10
|
|
13
|
+
HEADERS = {"Content-type": "application/json; charset=UTF-8"}
|
|
14
|
+
|
|
15
|
+
_LOGGER: logging.Logger = logging.getLogger(__package__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class APIWrapper:
|
|
19
|
+
"""Wrapper around calls to the pod point API"""
|
|
20
|
+
def __init__(self, session: aiohttp.ClientSession, timeout: int = TIMEOUT) -> None:
|
|
21
|
+
self._timeout: int = timeout
|
|
22
|
+
self._session: aiohttp.ClientSession = session
|
|
23
|
+
|
|
24
|
+
async def get(
|
|
25
|
+
self,
|
|
26
|
+
url: str,
|
|
27
|
+
headers: Dict[str, Any],
|
|
28
|
+
params: Dict[str, Any] = None,
|
|
29
|
+
exception_class=APIError
|
|
30
|
+
) -> aiohttp.ClientResponse:
|
|
31
|
+
"""Make a GET request"""
|
|
32
|
+
return await self.__wrapper(
|
|
33
|
+
method="get",
|
|
34
|
+
url=url,
|
|
35
|
+
params=params,
|
|
36
|
+
headers=headers,
|
|
37
|
+
exception_class=exception_class
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
async def put(
|
|
41
|
+
self,
|
|
42
|
+
url: str,
|
|
43
|
+
body: Any,
|
|
44
|
+
headers: Dict[str, Any],
|
|
45
|
+
params: Dict[str, Any] = None,
|
|
46
|
+
exception_class=APIError
|
|
47
|
+
) -> aiohttp.ClientResponse:
|
|
48
|
+
"""Make a PUT request"""
|
|
49
|
+
return await self.__wrapper(
|
|
50
|
+
method="put",
|
|
51
|
+
url=url,
|
|
52
|
+
params=params,
|
|
53
|
+
data=body,
|
|
54
|
+
headers=headers,
|
|
55
|
+
exception_class=exception_class
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
async def post(
|
|
59
|
+
self,
|
|
60
|
+
url: str,
|
|
61
|
+
body: Any,
|
|
62
|
+
headers: Dict[str, Any],
|
|
63
|
+
params: Dict[str, Any] = None,
|
|
64
|
+
exception_class=APIError
|
|
65
|
+
) -> aiohttp.ClientResponse:
|
|
66
|
+
"""Make a POST request"""
|
|
67
|
+
return await self.__wrapper(
|
|
68
|
+
method="post",
|
|
69
|
+
url=url,
|
|
70
|
+
params=params,
|
|
71
|
+
data=body,
|
|
72
|
+
headers=headers,
|
|
73
|
+
exception_class=exception_class
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
async def delete(
|
|
77
|
+
self,
|
|
78
|
+
url: str,
|
|
79
|
+
headers: Dict[str, Any],
|
|
80
|
+
params: Dict[str, Any] = None,
|
|
81
|
+
exception_class=APIError
|
|
82
|
+
) -> aiohttp.ClientResponse:
|
|
83
|
+
"""Make a GET request"""
|
|
84
|
+
return await self.__wrapper(
|
|
85
|
+
method="delete",
|
|
86
|
+
url=url,
|
|
87
|
+
params=params,
|
|
88
|
+
headers=headers,
|
|
89
|
+
exception_class=exception_class
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
async def __wrapper(
|
|
93
|
+
self,
|
|
94
|
+
method: str,
|
|
95
|
+
url: str,
|
|
96
|
+
data: Dict[str, Any] = None,
|
|
97
|
+
headers: Dict[str, Any] = None,
|
|
98
|
+
params: Dict[str, Any] = None,
|
|
99
|
+
exception_class=APIError
|
|
100
|
+
) -> aiohttp.ClientResponse:
|
|
101
|
+
"""Get information from the API."""
|
|
102
|
+
if data is None:
|
|
103
|
+
data = {}
|
|
104
|
+
if headers is None:
|
|
105
|
+
headers = {}
|
|
106
|
+
if params is None:
|
|
107
|
+
params = {}
|
|
108
|
+
|
|
109
|
+
try:
|
|
110
|
+
async with async_timeout.timeout(self._timeout):
|
|
111
|
+
start_time = time.time()
|
|
112
|
+
_LOGGER.debug("%s %s", method.upper(), url.split("?", 1)[0])
|
|
113
|
+
|
|
114
|
+
response = None
|
|
115
|
+
|
|
116
|
+
if method == "get":
|
|
117
|
+
response = await self._session.get(url, headers=headers, params=params)
|
|
118
|
+
|
|
119
|
+
elif method == "put":
|
|
120
|
+
response = await self._session.put(
|
|
121
|
+
url,
|
|
122
|
+
headers=headers,
|
|
123
|
+
params=params,
|
|
124
|
+
json=data
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
elif method == "post":
|
|
128
|
+
if isinstance(data, str):
|
|
129
|
+
response = await self._session.post(
|
|
130
|
+
url,
|
|
131
|
+
headers=headers,
|
|
132
|
+
params=params,
|
|
133
|
+
data=data
|
|
134
|
+
)
|
|
135
|
+
else:
|
|
136
|
+
response = await self._session.post(
|
|
137
|
+
url,
|
|
138
|
+
headers=headers,
|
|
139
|
+
params=params,
|
|
140
|
+
json=data
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
elif method == "delete":
|
|
144
|
+
response = await self._session.delete(url, headers=headers, params=params)
|
|
145
|
+
|
|
146
|
+
else:
|
|
147
|
+
raise ValueError(f'Method \'{method}\' not supported')
|
|
148
|
+
|
|
149
|
+
if response is None:
|
|
150
|
+
raise APIError(
|
|
151
|
+
"Unexpected error from Pod Point API. \
|
|
152
|
+
Received a None response when querying."
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
end_time = time.time()
|
|
156
|
+
_LOGGER.debug("%s - %ss", response.status, end_time - start_time)
|
|
157
|
+
|
|
158
|
+
if response.status < 200 or response.status > 204:
|
|
159
|
+
await self.__handle_response_error(
|
|
160
|
+
response=response,
|
|
161
|
+
exception_class=exception_class
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
return response
|
|
165
|
+
|
|
166
|
+
except asyncio.TimeoutError as exception:
|
|
167
|
+
message = f"Timeout error fetching information from {url} - {exception}"
|
|
168
|
+
raise ApiConnectionError(message) from exception
|
|
169
|
+
|
|
170
|
+
except (KeyError, TypeError) as exception:
|
|
171
|
+
_LOGGER.error(
|
|
172
|
+
"Error parsing information from %s - %s",
|
|
173
|
+
url,
|
|
174
|
+
exception,
|
|
175
|
+
)
|
|
176
|
+
raise exception
|
|
177
|
+
|
|
178
|
+
except (aiohttp.ClientError, gaierror) as exception:
|
|
179
|
+
message = f"Error connecting to Pod Point ({url}) - {exception}"
|
|
180
|
+
raise ApiConnectionError(message) from exception
|
|
181
|
+
|
|
182
|
+
except (AuthError, SessionError) as exception:
|
|
183
|
+
_LOGGER.error(
|
|
184
|
+
"Authentication error when creating auth or session. (%s)",
|
|
185
|
+
type(exception)
|
|
186
|
+
)
|
|
187
|
+
raise exception
|
|
188
|
+
|
|
189
|
+
except Exception as exception: # pylint: disable=broad-except
|
|
190
|
+
_LOGGER.error("Something really wrong happened")
|
|
191
|
+
raise exception
|
|
192
|
+
|
|
193
|
+
async def __handle_response_error(self, response: aiohttp.ClientResponse, exception_class):
|
|
194
|
+
status = response.status
|
|
195
|
+
response = await response.text()
|
|
196
|
+
|
|
197
|
+
raise exception_class(status, response)
|