Repository navigation
Expand file tree
/
Copy pathapi_services.py
More file actions
711 lines (599 loc) · 24.4 KB
/
Copy pathapi_services.py
File metadata and controls
711 lines (599 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
"""COMCheck API service module for making HTTP requests to the COMCheck API."""
"""Note: Service layer accepts raw data types (dicts) as inputs to stay simple and
HTTP-library-friendly, but returns validated Pydantic models to provide type safety
and catch API schema mismatches at the boundary."""
import logging
import os
from importlib.metadata import PackageNotFoundError, version
from typing import Any, Dict, NoReturn, Optional
import httpx
from comcheck_api.exceptions import (
COMCheckHTTPError,
COMCheckConnectionError,
COMCheckValidationError,
)
from comcheck_api.types.api_types import (
RunSimulationResponse,
SimulationStatusResponse,
SimulationResultResponse,
)
try:
CLIENT_VERSION = version("comcheck_api")
except PackageNotFoundError:
# Running from a source checkout without an installed distribution.
CLIENT_VERSION = "unknown"
class COMCheckApiService:
"""Low-level HTTP service for the COMcheck Web API.
Handles authentication, request construction, response parsing, and
error mapping. Methods accept raw dicts as inputs and return either
raw dicts or validated Pydantic response models.
Can be used as a context manager::
with COMCheckApiService(api_key="key") as svc:
data = svc.get_project("123")
"""
def __init__(self, api_key: str) -> None:
"""Initialize COMCheck API service.
Args:
api_key: API key for authentication
Raises:
ValueError: If API key is not provided
"""
if not api_key:
raise ValueError(
"COM_API_KEY is not set. Please provide it as a constructor parameter "
"or set it in your environment variables."
)
self.api_key = api_key
self.base_url: str = os.getenv(
"COMCHECK_API_URL", "https://comcheck.energycode.pnl.gov/checkweb-api/COM"
)
self._client: Optional[httpx.Client] = None
def _get_client(self) -> httpx.Client:
"""Get or create HTTP client instance.
Returns:
Configured httpx.Client instance
"""
if self._client is None:
self._client = httpx.Client(
base_url=self.base_url,
headers=self._prepare_headers(),
timeout=30.0,
)
return self._client
def _prepare_headers(self) -> Dict[str, str]:
"""Prepare headers for API requests.
Returns:
HTTP headers dictionary
"""
return {
"x-api-key": self.api_key,
"x-client-version": CLIENT_VERSION,
"Content-Type": "application/json",
"Accept": "application/json",
}
def _handle_api_error(self, error: Exception) -> NoReturn:
"""Handle API errors with detailed logging and raise custom exceptions.
Args:
error: The error object to handle
Raises:
COMCheckHTTPError: For HTTP status errors
COMCheckConnectionError: For connection/request errors
COMCheckValidationError: For validation errors
"""
logger = logging.getLogger(__name__)
if isinstance(error, httpx.HTTPStatusError):
logger.error(
"HTTP error occurred (Status: %s): %s\nResponse body: %s",
error.response.status_code,
error,
error.response.text,
exc_info=True,
extra={
"response_data": error.response.text,
"response_headers": dict(error.response.headers),
},
)
raise COMCheckHTTPError(
status_code=error.response.status_code,
message=error.response.reason_phrase,
response_data=error.response.text,
) from error
elif isinstance(error, httpx.RequestError):
logger.error(
"Request error occurred: %s",
error,
exc_info=True,
extra={"request": str(error.request)},
)
raise COMCheckConnectionError(
f"Failed to connect to COMcheck API: {str(error)}"
) from error
else:
logger.error("Unexpected error: %s", error, exc_info=True)
raise
def get_project(self, project_id: str) -> Dict[str, Any]:
"""Get a single project by ID.
Args:
project_id: The project ID to retrieve
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.get(f"/project/{project_id}")
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def get_project_list(self) -> Dict[str, Any]:
"""Get a list of all projects.
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.get("/projects")
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def update_project(
self, project_id: str, project_data: Dict[str, Any]
) -> Dict[str, Any]:
"""Update a project by ID.
Args:
project_id: The project ID to update
project_data: The project data to send in the request body
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.put(f"/project/{project_id}", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def assemblies_uvalue(
self, envelope_data: Dict[str, Any], energy_code: str
) -> Dict[str, Any]:
"""get assemblies u values
Args:
envelope_data: The envelope data to send in the request body
energy_code: The energy code for the api end point path
Returns:
RunSimulationResponse with session information
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/assemblies/uvalues", json=envelope_data
)
response.raise_for_status()
# may need validation here.
return response.json()
except Exception as error:
self._handle_api_error(error)
def interior_space_allowed_wattage(
self, interior_space_data: Dict[str, Any], energy_code: str
) -> Dict[str, Any]:
"""Calculate allowed wattage for a single interior lighting space.
Args:
interior_space_data: The interior space data to send in the request body
energy_code: The energy code for the api end point path
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/activity-use/allowed-wattage", json=interior_space_data
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def interior_spaces_allowed_wattage(
self, interior_spaces_data: list[Dict[str, Any]], energy_code: str
) -> Dict[str, Any]:
"""Calculate allowed wattage for a list of interior lighting spaces.
Args:
interior_spaces_data: The list of interior space data to send in the request body
energy_code: The energy code for the api end point path
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/activity-uses/allowed-wattage",
json=interior_spaces_data,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def check_UA_compliance(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
"""Check UA path compliance for a project.
Args:
project_data: The project data to send in the request body
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/compliance", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def check_requirements(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
"""Check requirements for a project.
Args:
project_data: The project data to send in the request body
Returns:
API response data as dictionary
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/requirements", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def generate_report(self, report_data: Dict[str, Any]) -> Dict[str, Any]:
"""Generate a PDF report for a project.
The API stores the generated PDF in S3 and returns a presigned URL
to download it.
Args:
report_data: The report request body, containing ``building`` (the
project data) and the ``envelope``, ``extlighting``,
``intlighting``, and ``mechanical`` section flags, plus the
``useBackstopCompliance`` flag.
Returns:
API response as a dictionary with ``url`` (the presigned S3 URL),
``expires``, and ``fileName``
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/report", json=report_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def start_run_simulation(
self, project_data: Dict[str, Any]
) -> RunSimulationResponse:
"""Start a simulation.
Args:
project_data: The project data to send in the request body
Returns:
RunSimulationResponse with session information
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/compliance/start-run-simulation", json=project_data
)
response.raise_for_status()
return RunSimulationResponse.model_validate(response.json())
except Exception as error:
self._handle_api_error(error)
def get_simulation_status(self, session_id: str) -> SimulationStatusResponse:
"""Get status of a simulation.
Args:
session_id: The session ID of the simulation
Returns:
SimulationStatusResponse with status information
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.get(
f"/compliance/get-status-simulation?sessionId={session_id}"
)
response.raise_for_status()
return SimulationStatusResponse.model_validate(response.json())
except Exception as error:
self._handle_api_error(error)
def get_simulation_result(self, session_id: str) -> SimulationResultResponse:
"""Get result of a simulation.
Args:
session_id: The session ID of the simulation
Returns:
SimulationResultResponse with simulation results
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.get(
f"/compliance/get-result-simulation?sessionId={session_id}"
)
response.raise_for_status()
return SimulationResultResponse.model_validate(response.json())
except Exception as error:
self._handle_api_error(error)
def renewable_capacity(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
"""Calculate required and proposed renewable capacity for a project.
Args:
project_data: The project data to send in the request body
Returns:
API response data as dictionary. ``data`` holds
``requiredRenewableCapacity``, ``proposedRenewableCapacity``,
``requiredOffsiteRenewableProcurementEnergy``,
``proposedOffsiteRenewableProcurementEnergy``, and
``renewableComplianceStatus``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/renewable/renewable-capacity", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def area_for_renewable(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
"""Calculate the building areas used for renewable requirements.
Args:
project_data: The project data to send in the request body
Returns:
API response data as dictionary. ``data`` holds
``largestThreeFloorArea`` and ``roofAreaForRenewable``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/renewable/area-for-renewable", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def update_energy_credits(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
"""Calculate the proposed and required energy credits for a project.
Args:
project_data: The project data to send in the request body
Returns:
API response data as dictionary. ``data`` holds ``energyCredits``,
``proposed``, ``required``, ``proposedRenewableAndLoadMgmt``,
``requiredRenewableAndLoadMgmt``, ``warnings``, and ``userAlerts``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post("/update-energy-credits", json=project_data)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def water_heater_efficiency(
self, swh_data: Dict[str, Any], energy_code: str, water_heater_name: Optional[str] = None
) -> Dict[str, Any]:
"""Calculate efficiency for water heater systems.
Args:
swh_data: ServiceWaterHeatingSystem data or list of systems
energy_code: The energy code for the endpoint path
water_heater_name: Optional name to match a system description
Returns:
API response data as dictionary. ``data`` is a dict keyed by
system description, with ``minEfficiency``, ``maxEfficiency``,
and ``efficiencyUnits``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
params = {"waterHeaterName": water_heater_name} if water_heater_name else None
response = client.post(
f"/{energy_code}/mechanical/water-heaters/efficiency",
json=swh_data,
params=params,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def hvac_system_efficiency(
self, hvac_data: Dict[str, Any], energy_code: str, hvac_name: Optional[str] = None
) -> Dict[str, Any]:
"""Calculate efficiency for HVAC systems.
Args:
hvac_data: HVACSystem data or list of systems
energy_code: The energy code for the endpoint path
hvac_name: Optional name to match a system description
Returns:
API response data as dictionary. ``data`` is a dict keyed by
system description, with efficiency fields.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
params = {"hvacName": hvac_name} if hvac_name else None
response = client.post(
f"/{energy_code}/mechanical/hvac-systems/efficiency",
json=hvac_data,
params=params,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def hvac_system_economizers_validation(
self, hvac_data: Dict[str, Any], energy_code: str
) -> Dict[str, Any]:
"""Validate economizer requirements for an HVAC system.
Args:
hvac_data: Single HVACSystem data
energy_code: The energy code for the endpoint path
Returns:
API response data as dictionary. ``data`` is a dict keyed by
system description, with economizer validation fields.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/mechanical/hvac-systems/economizers-validation",
json=hvac_data,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def plant_efficiency(
self, plant_data: Dict[str, Any], energy_code: str, plant_name: Optional[str] = None
) -> Dict[str, Any]:
"""Calculate efficiency for HVAC plants.
Args:
plant_data: HVACPlant data or list of plants
energy_code: The energy code for the endpoint path
plant_name: Optional name to match a plant description
Returns:
API response data as dictionary. ``data`` is a dict keyed by
plant description, with efficiency fields.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
params = {"plantName": plant_name} if plant_name else None
response = client.post(
f"/{energy_code}/mechanical/plants/efficiency",
json=plant_data,
params=params,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def fan_pressure_drop_credit(
self, credit_data: Dict[str, Any], energy_code: str, fan_pressure_credit_type: str
) -> Dict[str, Any]:
"""Calculate pressure drop credit for a fan system.
Args:
credit_data: FanSystemPressureDropCredits data without type field
energy_code: The energy code for the endpoint path
fan_pressure_credit_type: The credit type (required query param)
Returns:
API response data as dictionary. ``data`` holds
``pressureDropCredit``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/mechanical/fan-systems/fan-pressure-credit",
json=credit_data,
params={"fanPressureCreditType": fan_pressure_credit_type},
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def fan_system_compliance(
self, fan_system_data: Dict[str, Any], energy_code: str
) -> Dict[str, Any]:
"""Check compliance for a fan system.
Args:
fan_system_data: Single FanSystem data
energy_code: The energy code for the endpoint path
Returns:
API response data as dictionary. ``data`` holds compliance fields.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/mechanical/fan-systems/compliance",
json=fan_system_data,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def fan_maximum_allowable_hp(
self, fan_data: Dict[str, Any], energy_code: str
) -> Dict[str, Any]:
"""Calculate maximum allowable horsepower for a fan.
Args:
fan_data: A single object with ``designBrakeHp`` and ``brakeHp``.
Both keys are required; the endpoint returns a server error
if ``brakeHp`` is absent or if a list is sent.
energy_code: The energy code for the endpoint path
Returns:
API response data as dictionary. ``data`` holds
``maxNameplateHp``.
Raises:
COMCheckHTTPError: If the API returns an error status
COMCheckConnectionError: If the request fails
"""
try:
client = self._get_client()
response = client.post(
f"/{energy_code}/mechanical/fan-systems/maximum-allowable-hp",
json=fan_data,
)
response.raise_for_status()
return response.json()
except Exception as error:
self._handle_api_error(error)
def close(self) -> None:
"""Close the HTTP client connection."""
if self._client is not None:
self._client.close()
self._client = None
def __enter__(self) -> "COMCheckApiService":
"""Context manager entry."""
return self
def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
"""Context manager exit."""
self.close()