Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@TryAnotherName
Copy link

Problem

The localtuya custom component’s UDP discovery handler was logging a high volume of errors:

ERROR (MainThread) [homeassistant] Error doing job: Exception in callback _SelectorDatagramTransport._read_ready() (None)
Traceback (most recent call last):
  File "/config/custom_components/localtuya/discovery.py", line 65, in datagram_received
    data = decrypt_udp(data)
  File "/config/custom_components/localtuya/discovery.py", line 30, in decrypt_udp
    return _unpad(decryptor.update(message) + decryptor.finalize()).decode()
                                              ~~~~~~~~~~~~~~~~~~^^
ValueError: The length of the provided data is not a multiple of the block length.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.13/asyncio/events.py", line 89, in _run
    self._context.run(self._callback, *self._args)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/asyncio/selector_events.py", line 1243, in _read_ready
    self._protocol.datagram_received(data, addr)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^
  File "/config/custom_components/localtuya/discovery.py", line 67, in datagram_received
    data = data.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8f in position 0: invalid start byte

Although these errors did not affect functionality, they flooded the logs with hundreds of thousands of entries per day, making debugging difficult and increasing log storage.

Solution

This PR improves the datagram_received method to:

  • Gracefully handle decryption failures by attempting to decode raw data

  • Handle decoding errors without exceptions

  • Validate that decrypted data is JSON-formatted before parsing

  • Log warnings for malformed or unexpected packets instead of raising exceptions

These changes significantly reduce noisy error logs and improve the stability and clarity of localtuya's UDP discovery.

…_read_ready()" in localtuya discovery UDP handler
@bstlaurentnz
Copy link

Any chance we can get this PR reviewed? I've added it to my local install and it does what it says, nice to see my logs going back to a reasonable size

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants