|
12 | 12 | from .const import DEFAULT_NAME, DOMAIN |
13 | 13 |
|
14 | 14 | CF_TO_GALLON = 7.48052 |
| 15 | +CF_PER_CCF = 100 # 1 CCF = 100 cubic feet |
15 | 16 |
|
16 | 17 |
|
17 | 18 | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities): |
@@ -52,32 +53,39 @@ def _convert_usage(self, usage, usage_unit=None): |
52 | 53 |
|
53 | 54 | config_unit_type = self.coordinator.config_entry.data.get("unit_type") |
54 | 55 |
|
| 56 | + try: |
| 57 | + usage_float = float(usage) |
| 58 | + except (ValueError, TypeError): |
| 59 | + return None |
| 60 | + |
| 61 | + # CF (cubic feet) conversions |
55 | 62 | if usage_unit == "CF" and config_unit_type == "gal": |
56 | | - try: |
57 | | - return round(float(usage) * CF_TO_GALLON) |
58 | | - except (ValueError, TypeError): |
59 | | - 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": |
| 63 | + return round(usage_float * CF_TO_GALLON) |
| 64 | + if usage_unit == "CF" and config_unit_type == "CCF": |
| 65 | + return round(usage_float / CF_PER_CCF, 2) |
| 66 | + |
| 67 | + # GAL (gallons) conversions |
| 68 | + if usage_unit == "GAL" and config_unit_type == "gal": |
66 | 69 | return usage |
| 70 | + if usage_unit == "GAL" and config_unit_type == "CCF": |
| 71 | + # Convert gallons to cubic feet, then to CCF |
| 72 | + return round(usage_float / CF_TO_GALLON / CF_PER_CCF, 2) |
| 73 | + |
67 | 74 | return usage |
68 | 75 |
|
69 | 76 | def _get_usage_unit(self): |
70 | 77 | """Determine the unit of measurement for usage sensors.""" |
71 | | - usage_unit = self.coordinator.data.get("usageUnit") |
72 | 78 | config_unit_type = self.coordinator.config_entry.data.get("unit_type") |
73 | 79 |
|
74 | | - if usage_unit == "CF" and config_unit_type == "gal": |
| 80 | + # Return the user's configured unit type |
| 81 | + # The _convert_usage method handles the actual value conversion |
| 82 | + if config_unit_type == "gal": |
75 | 83 | 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 |
| 84 | + if config_unit_type == "CCF": |
| 85 | + return "CCF" |
| 86 | + |
| 87 | + # Fallback to API-reported unit if config is unexpected |
| 88 | + return self.coordinator.data.get("usageUnit") |
81 | 89 |
|
82 | 90 |
|
83 | 91 | class DynamicUnitSensorBase(UsageConversionMixin, CoordinatorEntity, SensorEntity): |
|
0 commit comments