Skip to content

Fix TypeError in UniFi LED brightness control#155936

Closed
Sese-Schneider wants to merge 2 commits into
home-assistant:devfrom
Sese-Schneider:unifi/led-control-brightness-fix
Closed

Fix TypeError in UniFi LED brightness control#155936
Sese-Schneider wants to merge 2 commits into
home-assistant:devfrom
Sese-Schneider:unifi/led-control-brightness-fix

Conversation

@Sese-Schneider
Copy link
Copy Markdown
Contributor

Proposed change

Fixes a TypeError in the UniFi LED brightness control.

  • Safeguards the input from the UniFi API to ensure the type of brightness is a int
  • Refactored brightness conversion logic into helper functions to improve code readability

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

  • I understand the code I am submitting and can explain how it works.
  • 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.
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

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:

Copilot AI review requested due to automatic review settings November 6, 2025 12:51
@home-assistant
Copy link
Copy Markdown
Contributor

home-assistant Bot commented Nov 6, 2025

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

Code owner commands

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

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the brightness conversion logic in the UniFi light integration by extracting inline brightness calculations into dedicated utility functions. The changes improve code maintainability and readability without altering the functional behavior.

Key Changes

  • Extracted brightness conversion logic into three new helper functions: convert_brightness_to_unifi(), convert_brightness_to_ha(), and get_device_brightness_or_default()
  • Refactored async_device_led_control_fn() to use the new helper functions with clearer control flow
  • Simplified async_update_state() to use the new conversion function

Comment thread homeassistant/components/unifi/light.py Outdated
Comment on lines +53 to +56
"""Get device's current LED brightness. Defaults to 100 (full brightness) if not set."""
if device.led_override_color_brightness is None:
return 100
return int(device.led_override_color_brightness)
Copy link

Copilot AI Nov 6, 2025

Choose a reason for hiding this comment

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

The function get_device_brightness_or_default returns a UniFi brightness value (0-100) but may return the device's current brightness value without validation. If device.led_override_color_brightness is a string (as accepted by convert_brightness_to_ha), this could raise a ValueError. Consider adding validation or clarifying the expected type to ensure consistency with the type hint annotation that expects int | str | None in the companion function.

Suggested change
"""Get device's current LED brightness. Defaults to 100 (full brightness) if not set."""
if device.led_override_color_brightness is None:
return 100
return int(device.led_override_color_brightness)
"""Get device's current LED brightness. Defaults to 100 (full brightness) if not set or invalid."""
value = device.led_override_color_brightness
if value is None:
return 100
try:
return int(value)
except (ValueError, TypeError):
return 100

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a valid concern. Why is the conversion needed in the first place? That sounds like either a logic or typing issue?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@frenck its super hard to tell, I was initially able to reproduce the issue after the initial update to HA 2025.11, but unfortunately now fail to reproduce at all, clean installation, reinitialization etc. doesn't help.

This was the initial stacktrace
[31m2025-11-06 10:03:52.668 ERROR (MainThread) [homeassistant.components.websocket_api.http.connection] [546689866048] Unexpected exception
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 270, in handle_call_service
    response = await hass.services.async_call(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    ...<7 lines>...
    )
    ^
  File "/usr/src/homeassistant/homeassistant/core.py", line 2816, in async_call
    response_data = await coro
                    ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/core.py", line 2859, in _execute_service
    return await target(service_call)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 830, in entity_service_call
    single_response = await _handle_entity_call(
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^
        hass, entity, func, data, call.context
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 902, in _handle_entity_call
    result = await task
             ^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/components/light/__init__.py", line 651, in async_handle_light_on_service
    await light.async_turn_on(**filter_turn_on_params(light, params))
  File "/usr/src/homeassistant/homeassistant/components/unifi/light.py", line 140, in async_turn_on
    await self.entity_description.control_fn(self.hub, self._obj_id, True, **kwargs)
  File "/usr/src/homeassistant/homeassistant/components/unifi/light.py", line 72, in async_device_led_control_fn
    DeviceSetLedStatus.create(
    ~~~~~~~~~~~~~~~~~~~~~~~~~^
        device=device,
        ^^^^^^^^^^^^^^
    ...<2 lines>...
        color=color,
        ^^^^^^^^^^^^
    )
    ^
  File "/usr/local/lib/python3.13/site-packages/aiounifi/models/device.py", line 847, in create
    if not (0 <= brightness <= 100):
            ^^^^^^^^^^^^^^^^^^^^^^

My assumption is that due to the usage of non-official APIs from UniFi, at some point the API returns a wrong type.
As the library implementation does not typeguard, a wrong type may end up in HA.

Why This Matters: When async_device_led_control_fn is called without ATTR_BRIGHTNESS (e.g., just turning on the light, like in the issue (#155892) mentioned), it uses the device's current brightness from the UniFi API.

I've added a try-catch block with some logging so we have more information if it would happen again in the future, but this should fix the issue some users are facing.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

My assumption is that due to the usage of non-official APIs from UniFi, at some point the API returns a wrong type.
As the library implementation does not typeguard, a wrong type may end up in HA.

With that in mind, the type conversion is unexpected. It masks the actual issue.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@Kane610 do you think this could be the behavior of the UniFi API?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There has been bugs before so it is not impossible. lets add the check and logging in the library instead and keep the integration code clean. It should be the responsibility of the lubrary

Comment thread homeassistant/components/unifi/light.py
@Kane610 Kane610 added this to the 2025.11.1 milestone Nov 6, 2025
Copy link
Copy Markdown
Member

@Kane610 Kane610 left a comment

Choose a reason for hiding this comment

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

Thanks!

Comment thread homeassistant/components/unifi/light.py Outdated
Comment on lines +53 to +56
"""Get device's current LED brightness. Defaults to 100 (full brightness) if not set."""
if device.led_override_color_brightness is None:
return 100
return int(device.led_override_color_brightness)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is a valid concern. Why is the conversion needed in the first place? That sounds like either a logic or typing issue?

@home-assistant home-assistant Bot marked this pull request as draft November 7, 2025 08:15
@home-assistant
Copy link
Copy Markdown
Contributor

home-assistant Bot commented Nov 7, 2025

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.

@Sese-Schneider Sese-Schneider marked this pull request as ready for review November 7, 2025 09:32
@home-assistant home-assistant Bot requested a review from frenck November 7, 2025 09:33
@frenck frenck marked this pull request as draft November 7, 2025 09:52
@frenck frenck modified the milestones: 2025.11.1, 2025.11.2 Nov 7, 2025
@Sese-Schneider
Copy link
Copy Markdown
Contributor Author

Closing as solution masks the actual problem; Library should be improved instead.

@github-actions github-actions Bot locked and limited conversation to collaborators Nov 11, 2025
@epenet epenet removed this from the 2025.11.2 milestone Nov 14, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unifi E7 LED turned off once... now error.

5 participants