Skip to content
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

Add BackupMode to Fronius integration. #126973

Draft
wants to merge 10 commits into
base: dev
Choose a base branch
from

Conversation

schinckel
Copy link

@schinckel schinckel commented Sep 28, 2024

Proposed change

This adds a binary sensor that shows if the Fronius Gen24 inverter is running in "Backup Mode", which means the grid power is not available, and the device is running from battery (or using the PVPoint).

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:

Checklist

  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

To help with the load of incoming pull requests:

Copy link

@home-assistant home-assistant bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @schinckel

It seems you haven't yet signed a CLA. Please do so here.

Once you do that we will be able to review and accept this pull request.

Thanks!

@home-assistant
Copy link

Hey there @farmio, mind taking a look at this pull request as it has been labeled with an integration (fronius) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of fronius can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign fronius Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@schinckel
Copy link
Author

There is no documentation link, because the documentation already mentions "Backup Mode", even though this does not appear to be shown.

@schinckel schinckel marked this pull request as ready for review September 28, 2024 01:02
@farmio
Copy link
Contributor

farmio commented Sep 28, 2024

Hi 👋!

This adds a binary sensor

Yes, I think it should add a BinarySensorEntity, but right now this adds a SensorEntity with a Boolean state.

@schinckel
Copy link
Author

Yes, I think it should add a BinarySensorEntity, but right now this adds a SensorEntity with a Boolean state.

Ah, right. I thought that the meter_mode was binary too.

This turns out to be somewhat problematic: the async_setup_entry function appears to assume that all entities within a given coordinator are homogenous, which is not the case here.

Still working through how to handle that - suggestions welcome!

@farmio
Copy link
Contributor

farmio commented Sep 28, 2024

Maybe change

self.unregistered_descriptors: dict[
SolarNetId, list[FroniusSensorEntityDescription]
] = {}
to

dict[SolarNetId, dict[Platform, list[FroniusEntityDescription]]

and check each platform individually.

If you can find a better system over all that's fine too - the current seems a bit overly complex 😬

@farmio
Copy link
Contributor

farmio commented Sep 28, 2024

Afaic there are only 2 datapoints in the currently used api endpoints that return Boolean values:

"BackupMode": true,
"BatteryStandby": false,

So these would make only 2 entities which are only usable for battery systems. Non-battery systems seem to just omit those keys https://github.com/home-assistant/core/blob/dev/tests/components/fronius/fixtures/symo/GetPowerFlowRealtimeData.json

As a workaround to avoid complexity, it may be an option to provide a sensor entity with an Enum state - having 2 possible values 🤔
See

device_class=SensorDeviceClass.ENUM,

Nicer option would probably be binary sensor though.

@home-assistant home-assistant bot marked this pull request as draft September 28, 2024 17:41
@home-assistant
Copy link

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@schinckel
Copy link
Author

I've made some progress (took me ages to realise that HA magically selects the platform based upon which module is currently being run, and you need to enumerate the platforms the integration uses).

I'm stuck at the moment because the binary_sensor that is created does not seem to have the correct device_id.

Still working through it, but using an enumeration for the backup mode (and battery standby) is looking pretty appealing.

@schinckel
Copy link
Author

Ah, so the incorrect entity_id was because that was HA loading it from the entity registry.

@farmio
Copy link
Contributor

farmio commented Sep 30, 2024

@schinckel if you have any specific questions, feel free to ask here or find me on HA Discord @_farmio. Happy to help, if I can.

@schinckel
Copy link
Author

Wow, that took some figuring out.

I'm not totally happy with the duplication, but it was easier to do that than get mypy to be satisfied with my subclassing. If you really want I'll try to rationalise the Fronius*Entity classes since they share a bunch of code.

image

Let me know if you want handled, or I'll just squash the commits.

@schinckel schinckel force-pushed the fronius/backup-mode branch 2 times, most recently from dbbdd17 to 211e622 Compare October 2, 2024 00:49
This binary sensor shows if the Fronius Gen24 inverter is running
in "Backup Mode", which means the grid power is not available, and
the device is running from battery (or using the PVPoint).
This also adds the "Battery Standby" binary sensor.
homeassistant/components/fronius/binary_sensor.py Outdated Show resolved Hide resolved
homeassistant/components/fronius/binary_sensor.py Outdated Show resolved Hide resolved
homeassistant/components/fronius/binary_sensor.py Outdated Show resolved Hide resolved
homeassistant/components/fronius/coordinator.py Outdated Show resolved Hide resolved
@@ -40,7 +42,7 @@ class FroniusCoordinatorBase(

default_interval: timedelta
error_interval: timedelta
valid_descriptions: list[FroniusSensorEntityDescription]
valid_descriptions: dict[Platform, list[FroniusEntityDescription]]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
valid_descriptions: dict[Platform, list[FroniusEntityDescription]]
valid_descriptions: Mapping[Platform, list[FroniusEntityDescription]]

maybe use Mapping as type annotation to mark that read-only / non-mutable.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm. This causes issues because mypy won't let you call .copy() on a Mapping, I think.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from collections.abc import Mapping
from copy import copy


x: Mapping[str, int]
y = copy(x)

seems to work fine according to https://mypy-play.net/?mypy=latest&python=3.12&flags=strict

Copy link
Author

@schinckel schinckel Oct 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, it works, just mypy complains about it.

- hook id: mypy
- exit code: 1

homeassistant/components/fronius/coordinator.py:84: error: Argument 1 to "deepcopy" has incompatible type "Mapping[Platform, list[FroniusEntityDescription]]"; expected "dict[Platform, list[FroniusEntityDescription]]"  [arg-type]
Found 1 error in 1 file (checked 1 source file)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(But yeah, mypy-play.net says that is fine. Neat tool, I've never seen that before).

Copy link
Contributor

@farmio farmio Oct 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh 🤔 that's unfortunate that it behaves differently locally.
Are you sure you are running latest mypy locally since I can't seem to be able to reproduce that. Also the stub for deepcopy looks like

_T = TypeVar("_T")
def deepcopy(x: _T, memo: dict[int, Any] | None = None, _nil: Any = []) -> _T: ...

which doesn't seem to care at all about the type of the first argument.

A workaround would be to use dict() which creates a shallow copy itself, so deepcopy(dict(valid_descriptions)) which isn't beautiful, but would work 🙃
Or a dict comprehension like {platform: descriptors.copy() for platform, descriptors in valid_descriptions.items()} (untested sent form mobile 😬)

homeassistant/components/fronius/binary_sensor.py Outdated Show resolved Hide resolved
@farmio
Copy link
Contributor

farmio commented Oct 3, 2024

It would be great if some basic unit-tests for the new binary sensors would be added. We already have API-response fixtures that include the keys and also some that don't.

@schinckel
Copy link
Author

It would be great if some basic unit-tests for the new binary sensors would be added. We already have API-response fixtures that include the keys and also some that don't.

Yeah, I was working on some unit tests last night, but for some reason the two binary_sensors are coming back with "unknown" in the test case. Ran out of time to figure out why.

@schinckel
Copy link
Author

Hmm. It seems that when running the code the binary sensors are lagging behind the sensors: that is, when my test system boots up, the sensors are ready immediately, but the binary sensors seem to be 10 seconds behind...I wonder if this is related to the polling frequency, and if the first poll misses the binary sensors.

(I think this may be the cause of the failing tests, actually).

self.entity_description = description
self.response_key = description.response_key or description.key
self.solar_net_id = solar_net_id
self._attr_native_value = self._get_entity_value()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't notice when I refactored the class that in the __init__ it was doing the value set in a way that only works for sensors. This was the same problem that was preventing binary sensors from working at all initially, it needs to store a boolean value in a different instance variable.

@farmio
Copy link
Contributor

farmio commented Oct 4, 2024

Usually each platform has its own test file (eg. test_binary_sensor.py). For a good example, maybe see the fritz integration. You could even use snapshot assertions for that - this integration should use them anyway, but moving the existing tests is not in scope of this PR.

Could you also add a test with a fixture that doesn't have those keys - asserting the entities aren't created?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants