Patch pyserial on startup to force serial port locking (#170925)

This commit is contained in:
puddly
2026-10-15 15:03:39 -04:00
committed by GitHub
parent d4a1cb5185
commit 65518b3afa
8 changed files with 163 additions and 1 deletions
+73
View File
@@ -0,0 +1,73 @@
"""Block shared access to serial ports by forcing pyserial exclusivity.
Also wires up the `pySerial` logger around port opens, since pyserial itself is silent.
"""
from functools import wraps
import inspect
import logging
from serial import Serial as PlatformSerial, SerialBase
from serial.rfc2217 import Serial as Rfc2217Serial
from serial.urlhandler.protocol_socket import Serial as SocketSerial
_LOGGER = logging.getLogger("pySerial")
_original_init_defaults = SerialBase.__init__.__defaults__
_original_platform_open = PlatformSerial.open
_original_socket_open = SocketSerial.open
_original_rfc2217_open = Rfc2217Serial.open
_enabled = False
@wraps(_original_platform_open)
def _logged_platform_open(self: PlatformSerial) -> None:
_LOGGER.debug("Opening serial port %s", self.port)
_original_platform_open(self)
_LOGGER.debug("Opened serial port %s", self.port)
@wraps(_original_socket_open)
def _logged_socket_open(self: SocketSerial) -> None:
_LOGGER.debug("Opening serial port %s", self.port)
_original_socket_open(self)
_LOGGER.debug("Opened serial port %s", self.port)
@wraps(_original_rfc2217_open)
def _logged_rfc2217_open(self: Rfc2217Serial) -> None:
_LOGGER.debug("Opening serial port %s", self.port)
_original_rfc2217_open(self)
_LOGGER.debug("Opened serial port %s", self.port)
def enable() -> None:
"""Default `exclusive` to True and log every pyserial port open."""
global _enabled # noqa: PLW0603 # pylint: disable=global-statement
if _enabled:
return
_enabled = True
defaults = {
name: param.default
for name, param in inspect.signature(SerialBase.__init__).parameters.items()
if param.default is not param.empty
}
defaults["exclusive"] = True
SerialBase.__init__.__defaults__ = tuple(defaults.values())
PlatformSerial.open = _logged_platform_open # type:ignore[method-assign]
SocketSerial.open = _logged_socket_open # type:ignore[method-assign]
Rfc2217Serial.open = _logged_rfc2217_open # type:ignore[method-assign]
def disable() -> None:
"""Restore pyserial to its unpatched state."""
global _enabled # noqa: PLW0603 # pylint: disable=global-statement
_enabled = False
SerialBase.__init__.__defaults__ = _original_init_defaults
PlatformSerial.open = _original_platform_open # type:ignore[method-assign]
SocketSerial.open = _original_socket_open # type:ignore[method-assign]
Rfc2217Serial.open = _original_rfc2217_open # type:ignore[method-assign]
+2
View File
@@ -25,6 +25,7 @@ import yarl
from . import (
block_async_io,
block_shared_serial,
config as conf_util,
config_entries,
core,
@@ -349,6 +350,7 @@ async def async_setup_hass(
_LOGGER.info("Config directory: %s", runtime_config.config_dir)
block_async_io.enable()
block_shared_serial.enable()
if not (recovery_mode := runtime_config.recovery_mode):
config_dict = None
+1
View File
@@ -59,6 +59,7 @@ PyJWT==2.15.1
pymicro-vad==1.0.1
PyNaCl==1.6.2
pyopenssl==26.4.0
pyserial==3.5
pyspeex-noise==1.0.2
python-slugify==9.1.3
PyTurboJPEG==1.8.3
+2
View File
@@ -61,6 +61,8 @@ dependencies = [
"Pillow==12.3.0",
"propcache==0.5.4",
"pyopenssl==26.4.0",
# We patch pyserial at runtime in `block_shared_serial` and need it to be available
"pyserial==3.5",
# Do not bump orjson until the very aggressive buffer resizing introduced in
# 3.12.0, which causes memory use to balloon, has been adjusted or a workaround
# is available.
+1
View File
@@ -44,6 +44,7 @@ psutil-home-assistant==0.0.1
PyJWT==2.15.1
pymicro-vad==1.0.1
pyopenssl==26.4.0
pyserial==3.5
pyspeex-noise==1.0.2
python-slugify==9.1.3
PyTurboJPEG==1.8.3
+8 -1
View File
@@ -47,7 +47,7 @@ from syrupy.assertion import SnapshotAssertion
# Setup patching of JSON functions before any other Home Assistant imports
from . import patch_json # isort:skip
from homeassistant import block_async_io
from homeassistant import block_async_io, block_shared_serial
from homeassistant.exceptions import ServiceNotFound
# Setup patching of recorder functions before any other Home Assistant imports
@@ -2327,6 +2327,13 @@ def disable_block_async_io() -> Generator[None]:
calls.clear()
@pytest.fixture
def disable_block_shared_serial() -> Generator[None]:
"""Fixture to restore pyserial after block_shared_serial patched it."""
yield
block_shared_serial.disable()
# Ensure that incorrectly formatted mac addresses are rejected during
# DhcpServiceInfo initialisation
_real_dhcp_service_info_init = DhcpServiceInfo.__init__
+71
View File
@@ -0,0 +1,71 @@
"""Tests for the block_shared_serial pyserial patches."""
from collections.abc import Generator
import logging
from unittest.mock import patch
import pytest
import serial
from serial import SerialBase, SerialException
from serial.urlhandler.protocol_socket import Serial as SocketSerial
from homeassistant import block_shared_serial
@pytest.fixture(autouse=True)
def restore_pyserial() -> Generator[None]:
"""Start from and return to unpatched pyserial state around each test."""
block_shared_serial.disable()
yield
block_shared_serial.disable()
async def test_default_exclusive_becomes_true() -> None:
"""When `exclusive` is omitted, it defaults to True after enable()."""
assert SerialBase().exclusive is None
block_shared_serial.enable()
assert SerialBase().exclusive is True
@pytest.mark.parametrize("value", [None, False, True])
async def test_explicit_exclusive_is_preserved(value: bool | None) -> None:
"""Explicit `exclusive` arguments are honored after enable()."""
block_shared_serial.enable()
assert SerialBase(exclusive=value).exclusive is value
@pytest.mark.parametrize(
"uri",
["/dev/this-does-not-exist", "socket://127.0.0.1:1", "rfc2217://127.0.0.1:1"],
)
async def test_serial_open_logs(caplog: pytest.LogCaptureFixture, uri: str) -> None:
"""Opening a serial port emits a debug log on the pySerial logger."""
block_shared_serial.enable()
caplog.set_level(logging.DEBUG, logger="pySerial")
# We bypass `HASocketBlockedError` checks on purpose
with (
pytest.raises(SerialException),
patch("socket.socket", side_effect=RuntimeError("Cannot open socket")),
serial.serial_for_url(uri),
):
pass
assert f"Opening serial port {uri}" in caplog.text
async def test_enable_is_idempotent() -> None:
"""Calling enable() twice leaves the existing wrappers in place."""
block_shared_serial.enable()
wrapped_open = SocketSerial.open
block_shared_serial.enable()
assert SocketSerial.open is wrapped_open
async def test_disable_restores_pyserial() -> None:
"""disable() undoes enable()."""
original_open = SocketSerial.open
block_shared_serial.enable()
block_shared_serial.disable()
assert SerialBase().exclusive is None
assert SocketSerial.open is original_open
+5
View File
@@ -72,6 +72,11 @@ def disable_block_async_io(disable_block_async_io):
"""Disable the loop protection from block_async_io after each test."""
@pytest.fixture(autouse=True)
def disable_block_shared_serial(disable_block_shared_serial: None) -> None:
"""Restore pyserial after each test."""
@pytest.fixture(scope="module", autouse=True)
def mock_http_start_stop() -> Generator[None]:
"""Mock HTTP start and stop."""