-
-
Notifications
You must be signed in to change notification settings - Fork 43
feat & fix: better handling about the access rate #793
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
zopanix
wants to merge
4
commits into
dvd-dev:main
Choose a base branch
from
zopanix:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+113
−0
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -200,10 +200,23 @@ def create_energy_entity(hilo, device): | |
|
|
||
| hilo_rate_current = HiloCostSensor(hilo, "Hilo rate current", hq_plan_name) | ||
| cost_entities.append(hilo_rate_current) | ||
|
|
||
| # Create hilo_rate_current_total sensor that includes access rate per hour | ||
| access_rate = tariff_config.get("access", 0) | ||
| hilo_rate_current_total = HiloCostSensorTotal( | ||
| hilo, "Hilo rate current total", hq_plan_name, access_rate | ||
| ) | ||
| cost_entities.append(hilo_rate_current_total) | ||
|
|
||
| async_add_entities(cost_entities) | ||
| async_track_state_change_event( | ||
| hilo._hass, ["sensor.hilo_rate_current"], hilo_rate_current._handle_state_change | ||
| ) | ||
| async_track_state_change_event( | ||
| hilo._hass, | ||
| ["sensor.hilo_rate_current"], | ||
| hilo_rate_current_total._handle_state_change, | ||
| ) | ||
| # This setups the utility_meter platform | ||
| await utility_manager.update(async_add_entities) | ||
| # This sends the entities to the energy dashboard | ||
|
|
@@ -1162,6 +1175,9 @@ def __init__(self, hilo, name, plan_name, amount=0): | |
| if "low_threshold" in name: | ||
| self._attr_device_class = SensorDeviceClass.ENERGY | ||
| self._attr_native_unit_of_measurement = UnitOfEnergy.KILO_WATT_HOUR | ||
| elif "access" in name.lower(): | ||
| # Access fee is a fixed daily cost, not per kWh | ||
| self._attr_native_unit_of_measurement = f"{CURRENCY_DOLLAR}/day" | ||
| self.data = None | ||
| self._attr_name = name | ||
| self.plan_name = plan_name | ||
|
|
@@ -1226,6 +1242,103 @@ async def async_added_to_hass(self): | |
| async def async_update(self): | ||
| """Update the state.""" | ||
| self._last_update = dt_util.utcnow() | ||
|
|
||
|
|
||
| class HiloCostSensorTotal(HiloEntity, SensorEntity): | ||
| """This sensor generates the total cost entity including access rate per hour""" | ||
|
|
||
| _attr_device_class = SensorDeviceClass.MONETARY | ||
| _attr_native_unit_of_measurement = ( | ||
| f"{CURRENCY_DOLLAR}/{UnitOfEnergy.KILO_WATT_HOUR}" | ||
| ) | ||
| _attr_state_class = SensorStateClass.TOTAL | ||
| _attr_icon = "mdi:cash" | ||
|
|
||
| def __init__(self, hilo, name, plan_name, access_rate=0): | ||
| for d in hilo.devices.all: | ||
| if d.type == "Gateway": | ||
| device = d | ||
| self.data = None | ||
| self._attr_name = name | ||
| self.plan_name = plan_name | ||
| self._last_update = dt_util.utcnow() | ||
| self._current_rate = 0 | ||
| self._access_rate_per_hour = ( | ||
| access_rate / 24 | ||
| ) # Convert daily access rate to hourly | ||
| self._total_cost = 0 | ||
| old_unique_id = slugify(self._attr_name) | ||
| self._attr_unique_id = ( | ||
| f"{slugify(device.identifier)}-{slugify(self._attr_name)}" | ||
| ) | ||
| hilo.async_migrate_unique_id( | ||
| old_unique_id, self._attr_unique_id, Platform.SENSOR | ||
| ) | ||
| self._last_update = dt_util.utcnow() | ||
| super().__init__(hilo, name=self._attr_name, device=device) | ||
| LOG.info( | ||
| f"Initializing total energy cost sensor {name} {plan_name} " | ||
| f"Access rate per hour: {self._access_rate_per_hour}" | ||
| ) | ||
|
|
||
| def _handle_state_change(self, event): | ||
| LOG.debug("_handle_state_change() %s | %s ", self, self._last_update) | ||
| if (state := event.data.get("new_state")) is None: | ||
| return | ||
|
|
||
| now = dt_util.utcnow() | ||
| try: | ||
| if ( | ||
| state.attributes.get("hilo_update") | ||
| and self._last_update + timedelta(seconds=30) < now | ||
| ): | ||
| LOG.debug( | ||
| "Setting new state %s state=%s state.attributes=%s", | ||
| state.state, | ||
| state, | ||
| state.attributes, | ||
| ) | ||
| # Get the current rate from hilo_rate_current | ||
| try: | ||
| self._current_rate = float(state.state) | ||
| except (ValueError, TypeError): | ||
| self._current_rate = 0 | ||
|
|
||
| # Calculate total cost: current rate + access rate per hour | ||
| self._total_cost = self._current_rate + self._access_rate_per_hour | ||
| self._last_update = now | ||
| self.async_write_ha_state() | ||
| except ValueError: | ||
| LOG.error(f"Invalid state received for {self._attr_unique_id}: {state}") | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Lazy formating here |
||
|
|
||
| @property | ||
| def state(self): | ||
| return self._total_cost | ||
|
|
||
| @property | ||
| def suggested_display_precision(self) -> int: | ||
| return 5 | ||
|
|
||
| @property | ||
| def should_poll(self) -> bool: | ||
| return False | ||
|
|
||
| @property | ||
| def extra_state_attributes(self): | ||
| return { | ||
| "Current Rate": self._current_rate, | ||
| "Access Rate Per Hour": self._access_rate_per_hour, | ||
| "Total Cost": self._total_cost, | ||
| "Plan": self.plan_name, | ||
| "last_update": self._last_update, | ||
| } | ||
|
|
||
| async def async_added_to_hass(self): | ||
| """Handle entity about to be added to hass event.""" | ||
| await super().async_added_to_hass() | ||
|
|
||
| async def async_update(self): | ||
| self._last_update = dt_util.utcnow() | ||
| return super().async_update() | ||
|
|
||
|
|
||
|
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make this properly async or call
instead of