@@ -42,19 +42,43 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_e
4242class UsageConversionMixin :
4343 """Mixin to provide usage conversion."""
4444
45+ # pylint: disable=too-many-return-statements
4546 def _convert_usage (self , usage , usage_unit = None ):
4647 """Convert usage based on configuration and native unit."""
4748 if usage is None :
4849 return None
4950 if usage_unit is None :
5051 usage_unit = self .coordinator .data .get ("usageUnit" )
51- if usage_unit == "CF" and self .coordinator .config_entry .data .get ("unit_type" ) == "gal" :
52+
53+ config_unit_type = self .coordinator .config_entry .data .get ("unit_type" )
54+
55+ if usage_unit == "CF" and config_unit_type == "gal" :
5256 try :
5357 return round (float (usage ) * CF_TO_GALLON )
5458 except (ValueError , TypeError ):
5559 return None
60+ elif usage_unit == "GAL" and config_unit_type == "CF" :
61+ try :
62+ return round (float (usage ) / CF_TO_GALLON )
63+ except (ValueError , TypeError ):
64+ return None
65+ elif usage_unit == "GAL" and config_unit_type == "gal" :
66+ return usage
5667 return usage
5768
69+ def _get_usage_unit (self ):
70+ """Determine the unit of measurement for usage sensors."""
71+ usage_unit = self .coordinator .data .get ("usageUnit" )
72+ config_unit_type = self .coordinator .config_entry .data .get ("unit_type" )
73+
74+ if usage_unit == "CF" and config_unit_type == "gal" :
75+ return "gal"
76+ if usage_unit == "GAL" and config_unit_type == "CF" :
77+ return "CF"
78+ if usage_unit == "GAL" and config_unit_type == "gal" :
79+ return "gal"
80+ return usage_unit
81+
5882
5983class DynamicUnitSensorBase (UsageConversionMixin , CoordinatorEntity , SensorEntity ):
6084 """Base class for sensors with dynamic units."""
@@ -72,13 +96,6 @@ def __init__(self, coordinator, entry):
7296 model = "Water Meter" ,
7397 )
7498
75- def _get_usage_unit (self ):
76- """Determine the unit of measurement for usage sensors."""
77- usage_unit = self .coordinator .data .get ("usageUnit" )
78- if usage_unit == "CF" and self .coordinator .config_entry .data .get ("unit_type" ) == "gal" :
79- return "gal"
80- return usage_unit
81-
8299 @property
83100 def native_unit_of_measurement (self ):
84101 """Return the unit of measurement."""
0 commit comments