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 datetime platform for supported broadlink devices #115408

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from

Conversation

eifinger
Copy link
Contributor

@eifinger eifinger commented Apr 11, 2024

Proposed change

The Broadlink thermostat devices have a large time drift of up to several minutes per week. This platform allows to sync time to the device.

Especially after DST changes this saves users from having to walk to each device and click buttons.

As an example this can also be run with an automation every night.

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

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.
  • Untested files have been added to .coveragerc.

To help with the load of incoming pull requests:

@home-assistant
Copy link

Hey there @Danielhiversen, @felipediel, @L-I-Am, mind taking a look at this pull request as it has been labeled with an integration (broadlink) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of broadlink 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 broadlink 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.

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch from 868a6f0 to e6c8923 Compare April 11, 2024 16:41
Copy link
Contributor

@PeteRager PeteRager left a comment

Choose a reason for hiding this comment

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

In the tests, consider validating the parameters (hour, minute, day, etc) get passed to the device call correctly. May require mocking dt_util.now().

@eifinger
Copy link
Contributor Author

In the tests, consider validating the parameters (hour, minute, day, etc) get passed to the device call correctly. May require mocking dt_util.now().

Also considered this but decided that the simple logic does not warrant such a complex test.

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch from e6c8923 to 53dba01 Compare April 12, 2024 06:37
@felipediel
Copy link
Contributor

Thanks @eifinger!

Have you thought about using a datetime entity to show/update the date/time?

@eifinger
Copy link
Contributor Author

Thanks @eifinger!

Have you thought about using a datetime entity to show/update the date/time?

I thought about supplying a datetime to the service but could not think of a valid usecase why it would be different from now(). Can you think of a usecase for doing that?

Also nice idea to use a datetime entity for that 👍

@eifinger
Copy link
Contributor Author

Thanks @eifinger!

Have you thought about using a datetime entity to show/update the date/time?

For showing the current time of the device I would need to find out how it works. Moreover I wanted to stay simple.

@eifinger
Copy link
Contributor Author

Thanks @eifinger!
Have you thought about using a datetime entity to show/update the date/time?

For showing the current time of the device I would need to find out how it works. Moreover I wanted to stay simple.

For future reference: https://github.com/mjg59/python-broadlink/blob/66744707f517593de8276ed550cecae31c204c57/broadlink/climate.py#L83-L109

@felipediel
Copy link
Contributor

Thanks @eifinger! Here's a datetime implementation for reference. It is straightforward, we basically need:

  • a property named native_value that returns the datetime fetched by the update coordinador (in our case it is stored in self._coordinator.data)
    @property
    def native_value(self) -> datetime | None:
        """Return the latest value."""
        if (data := self._coordinator.data) is None:
            return None

        now = dt.now()
        device_weekday = data["dayofweek"] - 1
        this_weekday = now.weekday()

        if device_weekday != this_weekday:
            days_diff = this_weekday - device_weekday
            if days_diff < 0:
                days_diff += 7
            now -= timedelta(days=days_diff)

        return now.replace(
            hour=data["hour"],
            minute=data["min"],
            second=data["sec"],
        )
  • a method named async_set_value() that receives a datetime as parameter and sends it to the device
    async def async_set_value(self, value: datetime) -> None:
        """Change the value."""
        await self._device.async_request(
            self._device.api.set_time,
            hour=value.hour,
            minute=value.minute,
            second=value.second,
            day=value.weekday() + 1,
        )

I don't see any practical scenarios beyond exposing the device date/time and adjusting it manually or through automations, but I would still prefer to use the native Home Assistant component. Leveraging native components offers several benefits, such as a user-friendly interface and the potential for services and automations to be reused seemlessly, without the user having to learn the verbatim of our integration.

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch 2 times, most recently from 6394b4f to 967d7c5 Compare April 30, 2024 13:11
@eifinger eifinger changed the title Add service broadlink.sync_time for climate devices Add datetime platform for supported broadlink devices Apr 30, 2024
@eifinger
Copy link
Contributor Author

Thanks @eifinger! Here's a datetime implementation for reference. It is straightforward, we basically need:

  • a property named native_value that returns the datetime fetched by the update coordinador (in our case it is stored in self._coordinator.data)
    @property
    def native_value(self) -> datetime | None:
        """Return the latest value."""
        if (data := self._coordinator.data) is None:
            return None

        now = dt.now()
        device_weekday = data["dayofweek"] - 1
        this_weekday = now.weekday()

        if device_weekday != this_weekday:
            days_diff = this_weekday - device_weekday
            if days_diff < 0:
                days_diff += 7
            now -= timedelta(days=days_diff)

        return now.replace(
            hour=data["hour"],
            minute=data["min"],
            second=data["sec"],
        )
  • a method named async_set_value() that receives a datetime as parameter and sends it to the device
    async def async_set_value(self, value: datetime) -> None:
        """Change the value."""
        await self._device.async_request(
            self._device.api.set_time,
            hour=value.hour,
            minute=value.minute,
            second=value.second,
            day=value.weekday() + 1,
        )

I don't see any practical scenarios beyond exposing the device date/time and adjusting it manually or through automations, but I would still prefer to use the native Home Assistant component. Leveraging native components offers several benefits, such as a user-friendly interface and the potential for services and automations to be reused seemlessly, without the user having to learn the verbatim of our integration.

Removed the service and implemented the datetime platform instead.

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch from 967d7c5 to dd56179 Compare May 1, 2024 07:28
Copy link
Contributor

@felipediel felipediel left a comment

Choose a reason for hiding this comment

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

Looks great @eifinger! A few changes and we'll be all set 🚀

homeassistant/components/broadlink/datetime.py Outdated Show resolved Hide resolved
Comment on lines +46 to +58
now = dt_util.now()
device_weekday = data["dayofweek"] - 1
this_weekday = now.weekday()

if device_weekday != this_weekday:
days_diff = this_weekday - device_weekday
if days_diff < 0:
days_diff += 7
now -= timedelta(days=days_diff)

self._attr_native_value = now.replace(
hour=data["hour"],
minute=data["min"],
second=data["sec"],
)
Copy link
Contributor

Choose a reason for hiding this comment

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

We can move this block to _update_state(), checking if data is None before and returning in case it is.

second=value.second,
day=value.weekday() + 1,
)
self._update_internal_state(value)
Copy link
Contributor

Choose a reason for hiding this comment

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

Here we can assign self._attr_native_value = value directly instead of calling this method.

self._attr_unique_id = f"{device.unique_id}-datetime"
self._update_internal_state()

def _update_internal_state(self, value: datetime | None = None) -> None:
Copy link
Contributor

Choose a reason for hiding this comment

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

Let's try to eliminate this function.

@eifinger

This comment was marked as outdated.

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch 3 times, most recently from bb87925 to 8c2a957 Compare May 1, 2024 18:56
Copy link
Contributor

@felipediel felipediel left a comment

Choose a reason for hiding this comment

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

LGTM 👍🚀

@eifinger eifinger force-pushed the broadlink_thermostat_set_time_service branch from 8c2a957 to 68c760f Compare May 2, 2024 15:17
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.

None yet

4 participants