12
12
import gzip
13
13
import base64
14
14
from .const import LOGGER
15
+ import traceback
15
16
16
17
17
18
class OptisparkApiClientError (Exception ):
@@ -91,31 +92,57 @@ def __init__(
91
92
"""Sample API Client."""
92
93
self ._session = session
93
94
95
+ def extra_to_datetime (self , extra ):
96
+ """Corvert unix_time to datetime object."""
97
+ if 'oldest_dates' in extra and 'newest_dates' in extra :
98
+ # Convert from unix time to datetime object
99
+ for key in ['oldest_dates' , 'newest_dates' ]:
100
+ for column in extra [key ]:
101
+ if extra [key ][column ] is not None :
102
+ extra [key ][column ] = datetime .fromtimestamp (extra [key ][column ])
103
+ return extra
104
+
94
105
async def upload_history (self , dynamo_data ):
95
106
"""Upload historical data to dynamoDB without calculating heat pump profile."""
96
107
lambda_url = 'https://lhyj2mknjfmatuwzkxn4uuczrq0fbsbd.lambda-url.eu-west-2.on.aws/'
97
108
payload = {'dynamo_data' : dynamo_data }
98
109
payload ['upload_only' ] = True
99
- await self ._api_wrapper (
110
+ extra = await self ._api_wrapper (
111
+ method = "post" ,
112
+ url = lambda_url ,
113
+ data = payload ,
114
+ )
115
+ extra = self .extra_to_datetime (extra )
116
+ return extra ['oldest_dates' ], extra ['newest_dates' ]
117
+
118
+ async def get_data_dates (self , dynamo_data : dict ):
119
+ """Call lambda and only get the newest and oldest dates in dynamo.
120
+
121
+ dynamo_data will only contain the user_hash.
122
+ """
123
+ lambda_url = 'https://lhyj2mknjfmatuwzkxn4uuczrq0fbsbd.lambda-url.eu-west-2.on.aws/'
124
+ payload = {'dynamo_data' : dynamo_data }
125
+ payload ['get_newest_oldest_data_date_only' ] = True
126
+ extra = await self ._api_wrapper (
100
127
method = "post" ,
101
128
url = lambda_url ,
102
129
data = payload ,
103
- headers = {"Content-type" : "application/json; charset=UTF-8" },
104
130
)
131
+ extra = self .extra_to_datetime (extra )
132
+ return extra ['oldest_dates' ], extra ['newest_dates' ]
105
133
106
- async def async_get_data (self , lambda_args : dict , dynamo_data : dict ) -> any :
107
- """Upload historical data to dynamoDB and calculate heat pump profile."""
134
+ async def async_get_profile (self , lambda_args : dict ) :
135
+ """Get heat pump profile only ."""
108
136
lambda_url = 'https://lhyj2mknjfmatuwzkxn4uuczrq0fbsbd.lambda-url.eu-west-2.on.aws/'
109
137
110
138
payload = lambda_args
111
- payload ['dynamo_data' ] = dynamo_data
112
- results , errors , extra = await self ._api_wrapper (
139
+ payload ['get_profile_only' ] = True
140
+ LOGGER .debug ('----------Lambda get profile----------' )
141
+ results , errors = await self ._api_wrapper (
113
142
method = "post" ,
114
143
url = lambda_url ,
115
144
data = payload ,
116
- headers = {"Content-type" : "application/json; charset=UTF-8" },
117
145
)
118
- LOGGER .debug ('----------Lambda request----------' )
119
146
if errors ['success' ] is False :
120
147
LOGGER .debug (f'OptisparkApiClientLambdaError: { errors ["error_message" ]} ' )
121
148
raise OptisparkApiClientLambdaError (errors ['error_message' ])
@@ -124,18 +151,18 @@ async def async_get_data(self, lambda_args: dict, dynamo_data: dict) -> any:
124
151
results ['projected_percent_savings' ] = 100
125
152
else :
126
153
results ['projected_percent_savings' ] = results ['base_cost' ]/ results ['optimised_cost' ]* 100 - 100
127
- return results , extra [ 'oldest_dates' ]
154
+ return results
128
155
129
156
async def _api_wrapper (
130
157
self ,
131
158
method : str ,
132
159
url : str ,
133
160
data : dict | None = None ,
134
- headers : dict | None = None ,
135
161
):
136
162
"""Call the Lambda function."""
137
163
try :
138
- data ['dynamo_data' ] = floats_to_decimal (data ['dynamo_data' ])
164
+ if 'dynamo_data' in data :
165
+ data ['dynamo_data' ] = floats_to_decimal (data ['dynamo_data' ])
139
166
uncompressed_data = pickle .dumps (data )
140
167
compressed_data = gzip .compress (uncompressed_data )
141
168
LOGGER .debug (f'len(uncompressed_data): { len (uncompressed_data )} ' )
@@ -146,7 +173,6 @@ async def _api_wrapper(
146
173
response = await self ._session .request (
147
174
method = method ,
148
175
url = url ,
149
- #headers=headers,
150
176
json = base64_string ,
151
177
)
152
178
if response .status in (401 , 403 ):
@@ -162,16 +188,19 @@ async def _api_wrapper(
162
188
return await response .json ()
163
189
164
190
except asyncio .TimeoutError as exception :
191
+ LOGGER .error (traceback .format_exc ())
165
192
LOGGER .error ('OptisparkApiClientTimeoutError:\n Timeout error fetching information' )
166
193
raise OptisparkApiClientTimeoutError (
167
194
"Timeout error fetching information" ,
168
195
) from exception
169
196
except (aiohttp .ClientError , socket .gaierror ) as exception :
197
+ LOGGER .error (traceback .format_exc ())
170
198
LOGGER .error ('OptisparkApiClientCommunicationError:\n Error fetching information' )
171
199
raise OptisparkApiClientCommunicationError (
172
200
"Error fetching information" ,
173
201
) from exception
174
202
except Exception as exception : # pylint: disable=broad-except
203
+ LOGGER .error (traceback .format_exc ())
175
204
LOGGER .error ('OptisparkApiClientError:\n Something really wrong happened!' )
176
205
raise OptisparkApiClientError (
177
206
"Something really wrong happened!"
0 commit comments