|
1 | 1 | """Modbus client async serial communication.""" |
2 | 2 | from __future__ import annotations |
3 | 3 |
|
| 4 | +import contextlib |
| 5 | +import sys |
4 | 6 | import time |
5 | 7 | from collections.abc import Callable |
6 | 8 | from functools import partial |
7 | | -from typing import TYPE_CHECKING |
8 | 9 |
|
9 | 10 | from pymodbus.client.base import ModbusBaseClient, ModbusBaseSyncClient |
10 | 11 | from pymodbus.exceptions import ConnectionException |
|
14 | 15 | from pymodbus.utilities import ModbusTransactionState |
15 | 16 |
|
16 | 17 |
|
17 | | -try: |
| 18 | +with contextlib.suppress(ImportError): |
18 | 19 | import serial |
19 | 20 |
|
20 | | - PYSERIAL_MISSING = False |
21 | | -except ImportError: |
22 | | - PYSERIAL_MISSING = True |
23 | | - if TYPE_CHECKING: # always False at runtime |
24 | | - # type checkers do not understand the Raise RuntimeError in __init__() |
25 | | - import serial |
26 | 21 |
|
27 | 22 | class AsyncModbusSerialClient(ModbusBaseClient): |
28 | 23 | """**AsyncModbusSerialClient**. |
@@ -82,7 +77,7 @@ def __init__( # pylint: disable=too-many-arguments |
82 | 77 | on_connect_callback: Callable[[bool], None] | None = None, |
83 | 78 | ) -> None: |
84 | 79 | """Initialize Asyncio Modbus Serial Client.""" |
85 | | - if PYSERIAL_MISSING: |
| 80 | + if "serial" not in sys.modules: |
86 | 81 | raise RuntimeError( |
87 | 82 | "Serial client requires pyserial " |
88 | 83 | 'Please install with "pip install pyserial" and try again.' |
@@ -191,6 +186,11 @@ def __init__( # pylint: disable=too-many-arguments |
191 | 186 | framer, |
192 | 187 | retries, |
193 | 188 | ) |
| 189 | + if "serial" not in sys.modules: |
| 190 | + raise RuntimeError( |
| 191 | + "Serial client requires pyserial " |
| 192 | + 'Please install with "pip install pyserial" and try again.' |
| 193 | + ) |
194 | 194 | self.socket: serial.Serial | None = None |
195 | 195 | self.last_frame_end = None |
196 | 196 | self._t0 = float(1 + bytesize + stopbits) / baudrate |
|
0 commit comments