|
1 | 1 | """Heating and Cooling Degree Days calculation functions.""" |
2 | 2 |
|
3 | | -from datetime import datetime |
| 3 | +from datetime import datetime, timedelta |
4 | 4 | import logging |
5 | 5 |
|
6 | 6 | from homeassistant.components.recorder import get_instance |
7 | 7 | from homeassistant.components.recorder.history import get_significant_states |
8 | 8 | from homeassistant.core import HomeAssistant |
| 9 | +from homeassistant.util import dt as dt_util |
9 | 10 |
|
10 | 11 | _LOGGER = logging.getLogger(__name__) |
11 | 12 |
|
@@ -304,3 +305,242 @@ async def async_calculate_cdd( |
304 | 305 |
|
305 | 306 | _LOGGER.debug("CDD calculation result: %.2f degree-days", result) |
306 | 307 | return result |
| 308 | + |
| 309 | + |
| 310 | +def calculate_hdd_from_forecast( |
| 311 | + forecast_data: list[dict], base_temp: float, start_time: datetime, end_time: datetime |
| 312 | +) -> float: |
| 313 | + """Calculate HDD from weather forecast data. |
| 314 | +
|
| 315 | + Uses forecast entries that fall within the specified time range. |
| 316 | + For each forecast entry, estimates HDD based on temperature and templow. |
| 317 | +
|
| 318 | + Args: |
| 319 | + forecast_data: List of forecast dictionaries with 'datetime', 'temperature', 'templow' |
| 320 | + base_temp: Base temperature for HDD calculation |
| 321 | + start_time: Start of the period to calculate |
| 322 | + end_time: End of the period to calculate |
| 323 | +
|
| 324 | + Returns: |
| 325 | + float: Calculated HDD value rounded to 1 decimal place |
| 326 | + """ |
| 327 | + if not forecast_data: |
| 328 | + _LOGGER.debug("No forecast data provided for HDD calculation") |
| 329 | + return 0 |
| 330 | + |
| 331 | + total_hdd = 0 |
| 332 | + used_forecasts = 0 |
| 333 | + |
| 334 | + for forecast in forecast_data: |
| 335 | + # Get forecast datetime - handle both 'datetime' and 'dt' keys |
| 336 | + forecast_dt = forecast.get("datetime") or forecast.get("dt") |
| 337 | + if not forecast_dt: |
| 338 | + continue |
| 339 | + |
| 340 | + # Convert to datetime if it's a string |
| 341 | + if isinstance(forecast_dt, str): |
| 342 | + try: |
| 343 | + forecast_dt = dt_util.parse_datetime(forecast_dt) |
| 344 | + except (ValueError, TypeError): |
| 345 | + _LOGGER.warning("Could not parse forecast datetime: %s", forecast_dt) |
| 346 | + continue |
| 347 | + |
| 348 | + # Skip if forecast is outside the time range |
| 349 | + if forecast_dt < start_time or forecast_dt >= end_time: |
| 350 | + continue |
| 351 | + |
| 352 | + # Get temperature - for hourly forecasts, use temperature directly |
| 353 | + # For daily forecasts, use templow and temperature average |
| 354 | + temp = forecast.get("temperature") |
| 355 | + templow = forecast.get("templow") |
| 356 | + |
| 357 | + if temp is None: |
| 358 | + continue |
| 359 | + |
| 360 | + # For hourly forecasts, use temperature directly |
| 361 | + # For daily forecasts (with templow), use average |
| 362 | + if templow is not None: |
| 363 | + avg_temp = (templow + temp) / 2 |
| 364 | + else: |
| 365 | + avg_temp = temp |
| 366 | + |
| 367 | + # Calculate HDD for this forecast period |
| 368 | + # Assume each forecast represents approximately 1 hour |
| 369 | + # (this is a simplification - actual duration may vary) |
| 370 | + duration_days = 1.0 / 24.0 # 1 hour in days |
| 371 | + |
| 372 | + # Calculate deficit from base temperature |
| 373 | + deficit = max(0, base_temp - avg_temp) |
| 374 | + forecast_hdd = deficit * duration_days |
| 375 | + |
| 376 | + total_hdd += forecast_hdd |
| 377 | + used_forecasts += 1 |
| 378 | + |
| 379 | + _LOGGER.debug( |
| 380 | + "Calculated HDD from %d forecast entries: %.1f degree-days", |
| 381 | + used_forecasts, |
| 382 | + total_hdd, |
| 383 | + ) |
| 384 | + |
| 385 | + return round(total_hdd, 1) |
| 386 | + |
| 387 | + |
| 388 | +def calculate_cdd_from_forecast( |
| 389 | + forecast_data: list[dict], base_temp: float, start_time: datetime, end_time: datetime |
| 390 | +) -> float: |
| 391 | + """Calculate CDD from weather forecast data. |
| 392 | +
|
| 393 | + Uses forecast entries that fall within the specified time range. |
| 394 | + For each forecast entry, estimates CDD based on temperature and templow. |
| 395 | +
|
| 396 | + Args: |
| 397 | + forecast_data: List of forecast dictionaries with 'datetime', 'temperature', 'templow' |
| 398 | + base_temp: Base temperature for CDD calculation |
| 399 | + start_time: Start of the period to calculate |
| 400 | + end_time: End of the period to calculate |
| 401 | +
|
| 402 | + Returns: |
| 403 | + float: Calculated CDD value rounded to 1 decimal place |
| 404 | + """ |
| 405 | + if not forecast_data: |
| 406 | + _LOGGER.debug("No forecast data provided for CDD calculation") |
| 407 | + return 0 |
| 408 | + |
| 409 | + total_cdd = 0 |
| 410 | + used_forecasts = 0 |
| 411 | + |
| 412 | + for forecast in forecast_data: |
| 413 | + # Get forecast datetime - handle both 'datetime' and 'dt' keys |
| 414 | + forecast_dt = forecast.get("datetime") or forecast.get("dt") |
| 415 | + if not forecast_dt: |
| 416 | + continue |
| 417 | + |
| 418 | + # Convert to datetime if it's a string |
| 419 | + if isinstance(forecast_dt, str): |
| 420 | + try: |
| 421 | + forecast_dt = dt_util.parse_datetime(forecast_dt) |
| 422 | + except (ValueError, TypeError): |
| 423 | + _LOGGER.warning("Could not parse forecast datetime: %s", forecast_dt) |
| 424 | + continue |
| 425 | + |
| 426 | + # Skip if forecast is outside the time range |
| 427 | + if forecast_dt < start_time or forecast_dt >= end_time: |
| 428 | + continue |
| 429 | + |
| 430 | + # Get temperature - for hourly forecasts, use temperature directly |
| 431 | + # For daily forecasts, use templow and temperature average |
| 432 | + temp = forecast.get("temperature") |
| 433 | + templow = forecast.get("templow") |
| 434 | + |
| 435 | + if temp is None: |
| 436 | + continue |
| 437 | + |
| 438 | + # For hourly forecasts, use temperature directly |
| 439 | + # For daily forecasts (with templow), use average |
| 440 | + if templow is not None: |
| 441 | + avg_temp = (templow + temp) / 2 |
| 442 | + else: |
| 443 | + avg_temp = temp |
| 444 | + |
| 445 | + # Calculate CDD for this forecast period |
| 446 | + # Assume each forecast represents approximately 1 hour |
| 447 | + duration_days = 1.0 / 24.0 # 1 hour in days |
| 448 | + |
| 449 | + # Calculate excess above base temperature |
| 450 | + excess = max(0, avg_temp - base_temp) |
| 451 | + forecast_cdd = excess * duration_days |
| 452 | + |
| 453 | + total_cdd += forecast_cdd |
| 454 | + used_forecasts += 1 |
| 455 | + |
| 456 | + _LOGGER.debug( |
| 457 | + "Calculated CDD from %d forecast entries: %.1f degree-days", |
| 458 | + used_forecasts, |
| 459 | + total_cdd, |
| 460 | + ) |
| 461 | + |
| 462 | + return round(total_cdd, 1) |
| 463 | + |
| 464 | + |
| 465 | +def combine_actual_and_forecast_hdd( |
| 466 | + actual_readings: list[tuple[datetime, float]], |
| 467 | + forecast_data: list[dict], |
| 468 | + base_temp: float, |
| 469 | + actual_end_time: datetime, |
| 470 | + forecast_end_time: datetime, |
| 471 | +) -> float: |
| 472 | + """Combine actual temperature readings with forecast data for HDD calculation. |
| 473 | +
|
| 474 | + Calculates HDD from actual readings up to actual_end_time, then adds |
| 475 | + estimated HDD from forecast data for the remaining period. |
| 476 | +
|
| 477 | + Args: |
| 478 | + actual_readings: List of (timestamp, temperature) tuples from actual sensor |
| 479 | + forecast_data: List of forecast dictionaries |
| 480 | + base_temp: Base temperature for HDD calculation |
| 481 | + actual_end_time: End time for actual readings (start of forecast period) |
| 482 | + forecast_end_time: End time for forecast period |
| 483 | +
|
| 484 | + Returns: |
| 485 | + float: Combined HDD value rounded to 1 decimal place |
| 486 | + """ |
| 487 | + # Calculate HDD from actual readings |
| 488 | + actual_hdd = calculate_hdd_from_readings(actual_readings, base_temp) |
| 489 | + |
| 490 | + # Calculate HDD from forecast for remaining period |
| 491 | + forecast_hdd = calculate_hdd_from_forecast( |
| 492 | + forecast_data, base_temp, actual_end_time, forecast_end_time |
| 493 | + ) |
| 494 | + |
| 495 | + total_hdd = actual_hdd + forecast_hdd |
| 496 | + |
| 497 | + _LOGGER.debug( |
| 498 | + "Combined HDD: %.1f (actual) + %.1f (forecast) = %.1f", |
| 499 | + actual_hdd, |
| 500 | + forecast_hdd, |
| 501 | + total_hdd, |
| 502 | + ) |
| 503 | + |
| 504 | + return round(total_hdd, 1) |
| 505 | + |
| 506 | + |
| 507 | +def combine_actual_and_forecast_cdd( |
| 508 | + actual_readings: list[tuple[datetime, float]], |
| 509 | + forecast_data: list[dict], |
| 510 | + base_temp: float, |
| 511 | + actual_end_time: datetime, |
| 512 | + forecast_end_time: datetime, |
| 513 | +) -> float: |
| 514 | + """Combine actual temperature readings with forecast data for CDD calculation. |
| 515 | +
|
| 516 | + Calculates CDD from actual readings up to actual_end_time, then adds |
| 517 | + estimated CDD from forecast data for the remaining period. |
| 518 | +
|
| 519 | + Args: |
| 520 | + actual_readings: List of (timestamp, temperature) tuples from actual sensor |
| 521 | + forecast_data: List of forecast dictionaries |
| 522 | + base_temp: Base temperature for CDD calculation |
| 523 | + actual_end_time: End time for actual readings (start of forecast period) |
| 524 | + forecast_end_time: End time for forecast period |
| 525 | +
|
| 526 | + Returns: |
| 527 | + float: Combined CDD value rounded to 1 decimal place |
| 528 | + """ |
| 529 | + # Calculate CDD from actual readings |
| 530 | + actual_cdd = calculate_cdd_from_readings(actual_readings, base_temp) |
| 531 | + |
| 532 | + # Calculate CDD from forecast for remaining period |
| 533 | + forecast_cdd = calculate_cdd_from_forecast( |
| 534 | + forecast_data, base_temp, actual_end_time, forecast_end_time |
| 535 | + ) |
| 536 | + |
| 537 | + total_cdd = actual_cdd + forecast_cdd |
| 538 | + |
| 539 | + _LOGGER.debug( |
| 540 | + "Combined CDD: %.1f (actual) + %.1f (forecast) = %.1f", |
| 541 | + actual_cdd, |
| 542 | + forecast_cdd, |
| 543 | + total_cdd, |
| 544 | + ) |
| 545 | + |
| 546 | + return round(total_cdd, 1) |
0 commit comments