-
-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathcalculated_sensor.py
More file actions
1843 lines (1611 loc) · 75.5 KB
/
calculated_sensor.py
File metadata and controls
1843 lines (1611 loc) · 75.5 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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Calculated sensor implementations for Sigenergy integration."""
from __future__ import annotations
import logging
from datetime import datetime, timezone, timedelta
from decimal import Decimal, InvalidOperation
from enum import Enum
from typing import Any, Dict, Optional, TYPE_CHECKING
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntityDescription,
SensorStateClass,
RestoreSensor,
)
from homeassistant.const import (
UnitOfEnergy,
EntityCategory,
UnitOfPower,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import callback, State
from homeassistant.helpers.event import async_track_point_in_time
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.event import async_track_state_change_event, async_call_later
from homeassistant.components.recorder import get_instance
from homeassistant.components.recorder.history import state_changes_during_period
from homeassistant.util import dt as dt_util
from .const import CONF_VALUES_TO_INIT, DEFAULT_MIN_INTEGRATION_TIME
from .modbusregisterdefinitions import EMSWorkMode
from .common import (
SigenergySensorEntityDescription,
safe_decimal,
safe_float,
)
from .sigen_entity import SigenergyEntity # Import the new base class
if TYPE_CHECKING:
from .coordinator import SigenergyDataUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
# Constants for daily sensor reset
DAILY_RESET_HOUR = 0
DAILY_RESET_MINUTE = 0
DAILY_RESET_SECOND = 0
# Only log for these entities
LOG_THIS_ENTITY = [
# "sensor.sigen_plant_daily_pv_energy",
]
class SigenergyCalculations:
"""Static class for Sigenergy calculated sensor functions."""
# Class variable to store last power readings and timestamps for energy calculation
_power_history = {}
@staticmethod
def minutes_to_gmt(minutes: Any) -> Optional[str]:
"""Convert minutes offset to GMT format."""
if minutes is None:
return None
try:
hours = int(minutes) // 60
return f"GMT{'+' if hours >= 0 else ''}{hours}"
except (ValueError, TypeError):
return None
@staticmethod
def epoch_to_datetime(
epoch: Any, coordinator_data: Optional[dict] = None
) -> Optional[datetime]:
"""Convert epoch timestamp to datetime using system's configured timezone."""
if epoch is None or epoch == 0: # Also treat 0 as None for timestamps
return None
try:
# Convert epoch to integer if it isn't already
epoch_int = int(epoch)
# Create timezone based on coordinator data if available
if coordinator_data and "plant" in coordinator_data:
try:
tz_offset = coordinator_data["plant"].get("plant_system_timezone")
if tz_offset is not None:
tz_minutes = int(tz_offset)
tz_hours = tz_minutes // 60
tz_remaining_minutes = tz_minutes % 60
tz = timezone(
timedelta(hours=tz_hours, minutes=tz_remaining_minutes)
)
else:
tz = timezone.utc
except (ValueError, TypeError) as e:
_LOGGER.warning(
"[CS][Timestamp] Invalid timezone in coordinator data: %s", e
)
tz = timezone.utc
else:
tz = timezone.utc
# Additional validation for timestamp range
if epoch_int < 0 or epoch_int > 32503680000: # Jan 1, 3000
_LOGGER.warning(
"[CS][Timestamp] Value %s out of reasonable range [0, 32503680000]",
epoch_int,
)
return None
try:
# Convert timestamp using the determined timezone
dt = datetime.fromtimestamp(epoch_int, tz=tz)
return dt
except (OSError, OverflowError) as ex:
_LOGGER.warning(
"[CS][Timestamp] Invalid timestamp %s: %s", epoch_int, ex
)
return None
except (ValueError, TypeError, OSError) as ex:
_LOGGER.warning("[CS][Timestamp] Conversion error for %s: %s", epoch, ex)
return None
@staticmethod
def calculate_total_pv_power(
_, # value is not used for this calculation
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None, # Not used here, but kept for consistency
) -> Optional[float]:
"""Calculate the total PV power from plant and party sources."""
if not coordinator_data or "plant" not in coordinator_data:
_LOGGER.debug("[CS][Total PV Power] Missing plant data in coordinator_data for total PV power calculation")
return None
plant_data = coordinator_data.get("plant", {})
plant_pv_power = safe_float(
plant_data.get("plant_sigen_photovoltaic_power"))
thirdparty_pv_power = safe_float(
plant_data.get("plant_third_party_photovoltaic_power"))
# If either value is None after safe_float, it means it was invalid or missing.
# We treat missing as 0 for summation, but if both are missing, return None.
if plant_pv_power is None and thirdparty_pv_power is None:
_LOGGER.debug("[CS][Total PV Power] Both plant_photovoltaic_power and thirdparty_pv_power are unavailable.")
return None
return safe_float((plant_pv_power or 0.0) + (thirdparty_pv_power or 0.0))
@staticmethod
def calculate_pv_power(
_,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[float]:
"""Calculate PV string power with proper error handling."""
if not coordinator_data or not extra_params:
_LOGGER.warning("Missing required data for PV power calculation")
return None
try:
pv_idx = extra_params.get("pv_idx")
# Expect device_name instead of device_id
device_name = extra_params.get("device_name")
if not pv_idx or not device_name:
_LOGGER.warning(
"Missing PV string index or device name for power calculation from extra_params: %s",
extra_params,
)
return None
# Use device_name to look up inverter data
inverter_data = coordinator_data.get("inverters", {}).get(device_name, {})
if not inverter_data:
_LOGGER.warning(
"[CS][PV Power] No inverter data available for power calculation"
)
return None
v_key = f"inverter_pv{pv_idx}_voltage"
c_key = f"inverter_pv{pv_idx}_current"
pv_voltage = inverter_data.get(v_key)
pv_current = inverter_data.get(c_key)
# Validate inputs
if pv_voltage is None or pv_current is None:
_LOGGER.warning(
"[CS][PV Power] Missing voltage or current data for PV string %d",
pv_idx,
)
return None
if not isinstance(pv_voltage, (int, float)) or not isinstance(
pv_current, (int, float)
):
_LOGGER.warning(
"Invalid data types for PV string %d: voltage=%s, current=%s",
pv_idx,
type(pv_voltage),
type(pv_current),
)
return None
# Calculate power with bounds checking
# Convert to Decimal for precise calculation
try:
voltage_dec = safe_decimal(pv_voltage)
current_dec = safe_decimal(pv_current)
if voltage_dec and current_dec:
power = voltage_dec * current_dec # Already in Watts
else:
return 0.0
except (ValueError, TypeError, InvalidOperation):
_LOGGER.warning(
"[CS][PV Power] Error converting values to Decimal: V=%s, I=%s",
pv_voltage,
pv_current,
)
return None
# Apply some reasonable bounds
MAX_REASONABLE_POWER = Decimal(
"20000"
) # 20kW per string is very high already
if isinstance(power, Decimal) and abs(power) > MAX_REASONABLE_POWER:
_LOGGER.warning(
"[CS][PV Power] Calculated power for PV string %d seems excessive: %s W",
pv_idx,
power,
)
elif not isinstance(power, Decimal) and abs(power) > float(
MAX_REASONABLE_POWER
):
_LOGGER.warning(
"[CS][PV Power] Calculated power for PV string %d seems excessive: %s W",
pv_idx,
power,
)
# Convert to kW
if isinstance(power, Decimal):
final_power = power / Decimal("1000")
else:
final_power = power / 1000
return (
safe_float(final_power) if isinstance(final_power, Decimal) else final_power
)
except Exception as ex: # pylint: disable=broad-exception-caught
_LOGGER.warning(
"[CS]Error calculating power for PV string %d: %s",
extra_params.get("pv_idx", "unknown"),
ex,
)
return None
@staticmethod
def calculate_grid_import_power(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate grid import power (positive values only)."""
if coordinator_data is None or "plant" not in coordinator_data:
return None
# Get the grid active power value from coordinator data
grid_power = coordinator_data["plant"].get("plant_grid_sensor_active_power")
if grid_power is None or not isinstance(grid_power, (int, float)):
return None
# Convert to Decimal for precise calculation
try:
power_dec = safe_decimal(grid_power)
# Return value if positive, otherwise 0
return power_dec if power_dec and power_dec > Decimal("0") else Decimal("0.0")
except (ValueError, TypeError, InvalidOperation):
# Fallback to float calculation
return safe_decimal(grid_power) if grid_power > 0 else Decimal("0.0")
@staticmethod
def calculate_grid_export_power(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate grid export power (negative values converted to positive)."""
if coordinator_data is None or "plant" not in coordinator_data:
return None
# Get the grid active power value from coordinator data
grid_power = coordinator_data["plant"].get("plant_grid_sensor_active_power")
if grid_power is None or not isinstance(grid_power, (int, float)):
return None
# Convert to Decimal for precise calculation
try:
power_dec = safe_decimal(str(grid_power))
# Return absolute value if negative, otherwise 0
return -power_dec if power_dec and power_dec < Decimal("0") else Decimal("0.0")
except (ValueError, TypeError, InvalidOperation):
# Fallback to float calculation
return safe_decimal(-grid_power) if grid_power < 0 else Decimal("0.0")
@staticmethod
def calculate_plant_consumed_power(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[float]:
"""Calculate plant consumed power (household/building consumption).
Formula: PV Power + Grid Import Power - Grid Export Power - Plant Battery Power
"""
if coordinator_data is None or "plant" not in coordinator_data:
return None
# Get the required values from coordinator data
plant_data = coordinator_data["plant"]
# Try to use the direct register value first (available in newer firmware)
# plant_general_load_power (30282)
plant_general_load_power = plant_data.get("plant_general_load_power")
if plant_general_load_power is not None:
try:
return float(plant_general_load_power)
except (ValueError, TypeError):
# If conversion fails, fallback to calculated method
_LOGGER.warning(
"[CS][Plant Consumed] Direct register value 'plant_general_load_power' is invalid: %s. Probably due to old firmware. Falling back to calculation.",
plant_general_load_power
)
total_ac_charger_power = 0.0
ac_chargers: dict[str, Any] = coordinator_data.get("ac_chargers", {})
for _, ac_charger_data in ac_chargers.items():
ac_power = safe_float(ac_charger_data.get("ac_charger_charging_power"))
if ac_power is not None:
total_ac_charger_power += ac_power
plant_power = plant_data.get("plant_active_power")
grid_power = plant_data.get("plant_grid_sensor_active_power")
third_party_pv_power = plant_data.get("plant_third_party_photovoltaic_power")
# Validate inputs
if plant_power is None or grid_power is None or third_party_pv_power is None:
return None
# Validate input types
def are_numbers(*values):
for x in values:
if not isinstance(x, (int, float)):
try:
float(x)
except (ValueError, TypeError):
_LOGGER.warning(
"[CS][Plant Consumed] Value is not a number: %s (type: %s)",
x,
type(x).__name__,
)
return False
return True
if not are_numbers(grid_power, plant_power, third_party_pv_power):
return None
# Calculate plant consumed power
try:
consumed_power = max(0, float(plant_power) + float(grid_power) + float(third_party_pv_power) - total_ac_charger_power)
except Exception as ex: # pylint: disable=broad-exception-caught
_LOGGER.error(
"[CS][Plant Consumed] Error during calculation: %s", ex, exc_info=True
)
return None
return consumed_power
@staticmethod
def _calculate_total_inverter_energy(
coordinator_data: Optional[Dict[str, Any]],
energy_key: str,
log_prefix: str,
) -> Optional[Decimal]:
"""Helper function to calculate total energy across all inverters for a given key."""
if coordinator_data is None or "inverters" not in coordinator_data:
_LOGGER.debug("[%s] No inverter data available for calculation", log_prefix)
return None
# Check if static sensors have been initialized
if not coordinator_data.get("_sensors_initialized", False):
_LOGGER.debug("[%s] Static sensors not yet initialized, skipping calculation for '%s'", log_prefix, energy_key)
return None
total_energy = Decimal("0.0")
valid_sample_count = 0
inverters_data = coordinator_data.get("inverters", {})
if not inverters_data:
_LOGGER.debug("[%s] Inverter data is empty", log_prefix)
return None # No inverters found
for inverter_name, inverter_data in inverters_data.items():
raw_value = inverter_data.get(energy_key)
if raw_value is None:
_LOGGER.debug(
"[%s] Missing '%s' for inverter %s",
log_prefix,
energy_key,
inverter_name,
)
continue
energy_value = safe_decimal(raw_value)
if energy_value is not None:
try:
total_energy += energy_value
valid_sample_count += 1
except (ValueError, TypeError, InvalidOperation) as e:
_LOGGER.warning(
"[%s] Invalid energy value '%s' for key '%s' in inverter %s: %s",
log_prefix,
energy_value,
energy_key,
inverter_name,
e
)
else:
_LOGGER.debug(
"[%s] Invalid '%s' value '%s' for inverter %s",
log_prefix,
energy_key,
raw_value,
inverter_name,
)
# If every inverter value was missing/invalid, publish unavailable instead of 0
# to avoid zero-bounce spikes in Energy Dashboard after reconnection events.
if valid_sample_count == 0:
_LOGGER.debug("[%s] No valid '%s' samples in this poll", log_prefix, energy_key)
return None
# Return as Decimal, matching other calculated sensors
return safe_decimal(total_energy)
@staticmethod
def calculate_accumulated_battery_charge_energy(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate the total accumulated battery charge energy across all inverters."""
# _LOGGER.debug("[CS][Batt Charge] Calculating accumulated battery charge energy")
return SigenergyCalculations._calculate_total_inverter_energy(
coordinator_data,
"inverter_ess_accumulated_charge_energy",
"CS][Batt Charge"
)
@staticmethod
def calculate_accumulated_battery_discharge_energy(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate the total accumulated battery discharge energy across all inverters."""
# _LOGGER.debug("[CS][Batt Discharge] Calculating accumulated battery discharge energy")
return SigenergyCalculations._calculate_total_inverter_energy(
coordinator_data,
"inverter_ess_accumulated_discharge_energy",
"CS][Batt Discharge"
)
@staticmethod
def calculate_daily_battery_charge_energy(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate the total daily battery charge energy across all inverters."""
# _LOGGER.debug("[CS][Daily Batt Charge] Calculating daily battery charge energy")
return SigenergyCalculations._calculate_total_inverter_energy(
coordinator_data,
"inverter_ess_daily_charge_energy",
"CS][Daily Batt Charge"
)
@staticmethod
def calculate_daily_battery_discharge_energy(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate the total daily battery discharge energy across all inverters."""
# _LOGGER.debug("[CS][Daily Batt Discharge] Calculating daily battery discharge energy")
return SigenergyCalculations._calculate_total_inverter_energy(
coordinator_data,
"inverter_ess_daily_discharge_energy",
"CS][Daily Batt Discharge"
)
@staticmethod
def calculate_plant_daily_pv_energy(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate the total daily PV energy across all inverters."""
# _LOGGER.debug("[CS][Daily PV] Calculating daily PV energy")
return SigenergyCalculations._calculate_total_inverter_energy(
coordinator_data,
"inverter_daily_pv_energy",
"CS][Daily PV"
)
@staticmethod
def _construct_source_entity_id(
register_name: str,
coordinator,
hass,
device_type: Optional[str] = None,
device_name: Optional[str] = None,
pv_string_idx: Optional[int] = None,
) -> Optional[str]:
"""Resolve source entity via entity registry using explicit device context.
This avoids assuming all lifetime sensors are plant-level. If device_name
is not provided and the device_type is the plant, fall back to the
config entry name.
"""
from .common import get_source_entity_id
from homeassistant.const import CONF_NAME
from .const import DEVICE_TYPE_PLANT
# If no explicit device_name provided and this is a plant-level sensor,
# use the configured plant name as a fallback.
if not device_name and device_type == DEVICE_TYPE_PLANT:
try:
device_name = coordinator.hub.config_entry.data.get(CONF_NAME, "Plant")
except Exception:
device_name = "Plant"
return get_source_entity_id(
device_type=device_type or DEVICE_TYPE_PLANT,
device_name=device_name,
source_key=register_name,
coordinator=coordinator,
hass=hass,
pv_string_idx=pv_string_idx,
)
@staticmethod
def calculate_daily_energy_from_lifetime(
value,
coordinator_data: Optional[Dict[str, Any]] = None,
extra_params: Optional[Dict[str, Any]] = None,
) -> Optional[Decimal]:
"""Calculate daily energy from lifetime total using register name from extra_params."""
if coordinator_data is None or "plant" not in coordinator_data:
return None
if extra_params is None or "register_name" not in extra_params:
_LOGGER.warning("[CS][Daily Energy] Missing register_name in extra_params")
return None
register_name = extra_params["register_name"]
# Get the current lifetime total
current_lifetime = coordinator_data["plant"].get(register_name)
if current_lifetime is None:
return None
current_lifetime_dec = safe_decimal(current_lifetime)
if current_lifetime_dec is None:
return None
# The daily calculation will be handled by SigenergyLifetimeDailySensor
# This function just returns the current lifetime value for the sensor to use
return current_lifetime_dec
class IntegrationTrigger(Enum):
"""Trigger type for integration calculations."""
STATE_EVENT = "state_event"
TIME_ELAPSED = "time_elapsed"
class SigenergyLifetimeDailySensor(SigenergyEntity, RestoreSensor):
"""Sensor that calculates daily totals from lifetime values with midnight reset."""
_attr_state_class = SensorStateClass.TOTAL_INCREASING
_attr_should_poll = False
def __init__(
self,
coordinator,
description: SensorEntityDescription,
name: str,
device_type: str,
device_id: Optional[str] = None,
device_name: str = "",
device_info: Optional[DeviceInfo] = None,
pv_string_idx: Optional[int] = None,
) -> None:
"""Initialize the lifetime daily sensor."""
# Call SigenergyEntity's __init__ first
super().__init__(
coordinator=coordinator,
description=description,
name=name,
device_type=device_type,
device_id=device_id,
device_name=device_name,
device_info=device_info,
pv_string_idx=pv_string_idx,
)
# Then initialize RestoreSensor
RestoreSensor.__init__(self)
self._attr_suggested_display_precision = getattr(
description, "suggested_display_precision", None
)
# State tracking
self._daily_value: Optional[Decimal] = None
self._start_of_day_lifetime: Optional[Decimal] = None
self._last_lifetime_value: Optional[Decimal] = None
self._last_reset_date: Optional[str] = None # Store as YYYY-MM-DD string
# Sensor configuration
self._round_digits = getattr(description, "round_digits", 6)
self.log_this_entity = False
def _get_current_date_str(self) -> str:
"""Get current date as YYYY-MM-DD string."""
return dt_util.now().strftime("%Y-%m-%d")
def _should_reset_for_new_day(self) -> bool:
"""Check if we should reset because it's a new day."""
current_date = self._get_current_date_str()
return self._last_reset_date != current_date
async def _get_lifetime_value_at_midnight(self) -> Optional[Decimal]:
"""Get the lifetime value from history at the start of today.
Approach:
1. Look for a state at midnight (±30 minutes window)
2. If not found, look for a state one hour before midnight (23:00 ±30 minutes)
3. If not available, return None to use current reading (daily = 0 at startup)
"""
try:
# Get the coordinator data to determine which register to look up
extra_params = getattr(self.entity_description, 'extra_params', None)
if not extra_params or "register_name" not in extra_params:
return None
# Extract register name from extra_params and construct source entity ID
register_name = extra_params.get("register_name")
if not register_name:
if self.log_this_entity:
_LOGGER.debug(
"[%s] Missing register_name in extra_params: %s",
self.entity_id, extra_params
)
return None
# Construct the source entity ID dynamically
source_entity_id = SigenergyCalculations._construct_source_entity_id(
register_name,
self.coordinator,
self.hass,
device_type=getattr(self, "_device_type", None),
device_name=getattr(self, "_device_name", None),
pv_string_idx=getattr(self, "_pv_string_idx", None),
)
if not source_entity_id:
if self.log_this_entity:
_LOGGER.debug(
"[%s] Could not find source entity for register: %s",
self.entity_id, register_name
)
return None
# Calculate midnight of current day
now = dt_util.now()
midnight_today = now.replace(
hour=DAILY_RESET_HOUR,
minute=DAILY_RESET_MINUTE,
second=DAILY_RESET_SECOND,
microsecond=0
)
# If we're very close to midnight, look at yesterday's midnight
if (now - midnight_today).total_seconds() < 300: # Within 5 minutes of midnight
midnight_today = midnight_today - timedelta(days=1)
# Get recorder instance
recorder_instance = get_instance(self.hass)
if not recorder_instance:
if self.log_this_entity:
_LOGGER.debug("[%s] Recorder not available", self.entity_id)
return None
# Primary: Look for state at midnight (±30 minutes window)
start_time = midnight_today - timedelta(minutes=30) # 23:30
end_time = midnight_today + timedelta(minutes=30) # 00:30
if self.log_this_entity:
_LOGGER.debug(
"[%s] Looking for %s state at midnight between %s and %s",
self.entity_id, source_entity_id, start_time, end_time
)
result = await self._query_history_for_midnight_value(
recorder_instance, source_entity_id, start_time, end_time, midnight_today, "midnight"
)
if result is not None:
return result
# Fallback: Look for state around 23:00 (1 hour before midnight) - ±30 minutes window
target_time = midnight_today - timedelta(hours=1) # 23:00
start_time = target_time - timedelta(minutes=30) # 22:30
end_time = target_time + timedelta(minutes=30) # 23:30
if self.log_this_entity:
_LOGGER.debug(
"[%s] No midnight value found, looking for %s state around 23:00 between %s and %s",
self.entity_id, source_entity_id, start_time, end_time
)
result = await self._query_history_for_midnight_value(
recorder_instance, source_entity_id, start_time, end_time, target_time, "23:00 fallback"
)
if result is not None:
return result
# No history found - this is fine, will use current reading (daily = 0 at startup)
if self.log_this_entity:
_LOGGER.debug(
"[%s] No state found at midnight or 23:00 for %s, will use current reading",
self.entity_id, source_entity_id
)
return None
except Exception as ex:
_LOGGER.warning(
"[%s] Error getting midnight value from history: %s",
self.entity_id, ex
)
return None
async def _query_history_for_midnight_value(
self, recorder_instance, source_entity_id: str, start_time, end_time,
target_time, phase_name: str
) -> Optional[Decimal]:
"""Query history and find the state closest to the target time."""
try:
states_dict = await recorder_instance.async_add_executor_job(
state_changes_during_period,
self.hass,
start_time,
end_time,
source_entity_id
)
if not states_dict or source_entity_id not in states_dict:
return None
states = states_dict[source_entity_id]
if not states:
return None
# Find the state closest to the target time
closest_state = None
closest_time_diff = None
for state in states:
if state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE, None):
continue
time_diff = abs((state.last_reported - target_time).total_seconds())
if closest_time_diff is None or time_diff < closest_time_diff:
closest_state = state
closest_time_diff = time_diff
if closest_state is None:
return None
target_value = safe_decimal(closest_state.state)
if self.log_this_entity:
_LOGGER.info(
"[%s] Found %s value: %s at %s (diff: %d seconds)",
self.entity_id,
phase_name,
target_value,
closest_state.last_reported,
closest_time_diff or 0
)
return target_value
except Exception as ex:
_LOGGER.warning(
"[%s] Error in %s query: %s",
self.entity_id, phase_name, ex
)
return None
def _get_lifetime_value(self) -> Optional[Decimal]:
"""Get the current lifetime value from coordinator data."""
if not hasattr(self.entity_description, 'value_fn'):
return None
try:
# Call the value function to get the current lifetime value
value_fn = getattr(self.entity_description, 'value_fn')
coordinator_data = self.coordinator.data if self.coordinator else None
# Get extra_fn_data flag and extra_params
extra_fn_data = getattr(self.entity_description, 'extra_fn_data', False)
extra_params = getattr(self.entity_description, 'extra_params', None)
if extra_fn_data:
result = value_fn(None, coordinator_data, extra_params)
else:
# Get the raw value from coordinator data if available
raw_value = None
if coordinator_data and hasattr(self.entity_description, 'key'):
# Try to get value from plant data first
plant_data = coordinator_data.get("plant", {})
raw_value = plant_data.get(self.entity_description.key)
result = value_fn(raw_value)
return safe_decimal(result) if result is not None else None
except Exception as ex:
_LOGGER.warning(
"[%s] Error getting lifetime value: %s",
self.entity_id, ex
)
return None
def _reset_daily_calculation(self, current_lifetime: Decimal) -> None:
"""Reset the daily calculation for a new day."""
self._start_of_day_lifetime = current_lifetime
self._daily_value = Decimal("0.0")
self._last_reset_date = self._get_current_date_str()
if self.log_this_entity:
_LOGGER.debug(
"[%s] Reset for new day: start_of_day=%s, date=%s",
self.entity_id,
self._start_of_day_lifetime,
self._last_reset_date
)
def _calculate_daily_value(self, current_lifetime: Decimal) -> Optional[Decimal]:
"""Calculate the daily value from current and start-of-day lifetime values."""
if self._start_of_day_lifetime is None:
# First time - we'll set this up properly in async_added_to_hass
# For now, just return None to indicate we're not ready yet
return None
# Check if we need to reset for a new day
if self._should_reset_for_new_day():
self._reset_daily_calculation(current_lifetime)
return Decimal("0.0")
# Handle potential counter rollover (rare but possible)
if current_lifetime < self._start_of_day_lifetime:
_LOGGER.warning(
"[%s] Lifetime counter rollover detected: current=%s < start_of_day=%s",
self.entity_id,
current_lifetime,
self._start_of_day_lifetime
)
# Reset with current value as new start
self._reset_daily_calculation(current_lifetime)
return Decimal("0.0")
# Normal calculation
daily_value = current_lifetime - self._start_of_day_lifetime
if self.log_this_entity:
_LOGGER.debug(
"[%s] Daily calculation: %s = %s - %s",
self.entity_id,
daily_value,
current_lifetime,
self._start_of_day_lifetime
)
return daily_value
def _update_from_coordinator(self) -> None:
"""Update sensor value from coordinator data."""
current_lifetime = self._get_lifetime_value()
if current_lifetime is None:
if self.log_this_entity:
_LOGGER.debug("[%s] No lifetime value available", self.entity_id)
return
# Calculate daily value (will return None if not initialized yet)
daily_value = self._calculate_daily_value(current_lifetime)
if daily_value is not None:
self._daily_value = daily_value
self._last_lifetime_value = current_lifetime
if self.log_this_entity:
_LOGGER.debug(
"[%s] Updated: daily=%s, lifetime=%s",
self.entity_id,
self._daily_value,
current_lifetime
)
elif self.log_this_entity:
_LOGGER.debug(
"[%s] Not ready for calculation yet (start_of_day not set)",
self.entity_id
)
def _setup_midnight_reset(self) -> None:
"""Schedule reset at midnight."""
now = dt_util.now()
# Calculate next midnight
next_midnight = (now + timedelta(days=1)).replace(
hour=DAILY_RESET_HOUR,
minute=DAILY_RESET_MINUTE,
second=DAILY_RESET_SECOND,
microsecond=0
)
@callback
def _handle_midnight(current_time):
"""Handle midnight reset."""
if self.log_this_entity:
_LOGGER.debug("[%s] Midnight reset triggered at %s", self.entity_id, current_time)
# Get current lifetime value and reset
current_lifetime = self._get_lifetime_value()
if current_lifetime is not None:
self._reset_daily_calculation(current_lifetime)
self.async_write_ha_state()
# Schedule next reset
self._setup_midnight_reset()
# Schedule the reset
self.async_on_remove(
async_track_point_in_time(self.hass, _handle_midnight, next_midnight)
)
if self.log_this_entity:
_LOGGER.debug(
"[%s] Scheduled midnight reset for %s",
self.entity_id,
next_midnight
)
async def async_added_to_hass(self) -> None:
"""Handle entity which will be added."""
await super().async_added_to_hass()
self.log_this_entity = self.entity_id in LOG_THIS_ENTITY
# Try to restore previous state
last_state = await self.async_get_last_state()
if last_state and last_state.state not in (None, STATE_UNKNOWN, STATE_UNAVAILABLE):
try:
# Restore daily value
self._daily_value = safe_decimal(last_state.state)
# Restore attributes
if last_state.attributes:
start_of_day = last_state.attributes.get("start_of_day_lifetime")
if start_of_day is not None:
self._start_of_day_lifetime = safe_decimal(start_of_day)
last_reset = last_state.attributes.get("last_reset_date")
if last_reset:
self._last_reset_date = last_reset