Skip to content

Commit acd5caf

Browse files
committed
Make mypy and black happy.
1 parent 99a8d23 commit acd5caf

7 files changed

Lines changed: 44 additions & 27 deletions

File tree

.github/workflows/python-app.yml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,14 @@ jobs:
3939
run: |
4040
python -m pip install --upgrade pip
4141
python -m pip install .[test]
42-
- name: Lint with flake8
42+
- name: Linting
4343
run: |
4444
# stop the build if there are Python syntax errors or undefined names
4545
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
4646
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
4747
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
48+
black --check .
49+
mypy .
4850
- name: Test with pytest
4951
run: |
5052
pytest --cov --cov-report=xml

modbus4mqtt/modbus4mqtt.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -67,11 +67,9 @@ def __init__(
6767
self.modbus_reconnect_sleep_interval = (
6868
5 # Wait this many seconds between modbus connection attempts
6969
)
70-
self.modbus_connection_status: ModbusConnectionStatus = (
71-
ModbusConnectionStatus.Offline
72-
)
73-
self._subscription_mids: map[int, str] = {}
74-
self.mqtt_connection_status: MqttConnectionStatus = MqttConnectionStatus.Offline
70+
self.modbus_connection_status: str = ModbusConnectionStatus.Offline
71+
self._subscription_mids: dict[int, str] = {}
72+
self.mqtt_connection_status: str = MqttConnectionStatus.Offline
7573
self.setup_modbus()
7674

7775
def connect(self):
@@ -121,7 +119,7 @@ def connect_modbus(self):
121119
else:
122120
self.set_modbus_connection_status(ModbusConnectionStatus.Offline)
123121

124-
def set_modbus_connection_status(self, status: ModbusConnectionStatus):
122+
def set_modbus_connection_status(self, status: str):
125123
if status == self.modbus_connection_status:
126124
return
127125
self.modbus_connection_status = status
@@ -293,7 +291,7 @@ def _on_subscribe(self, client, userdata, mid, reason_code_list, properties):
293291
logging.info("Subscribed to all set topics.")
294292
self._set_mqtt_connection_status(MqttConnectionStatus.Online)
295293

296-
def _set_mqtt_connection_status(self, status: MqttConnectionStatus):
294+
def _set_mqtt_connection_status(self, status: str):
297295
if self.mqtt_connection_status == status:
298296
return
299297
self.mqtt_connection_status = status

modbus4mqtt/modbus_interface.py

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pymodbus.framer import FramerType
66
from pymodbus import ModbusException
77

8-
from SungrowModbusTcpClient import SungrowModbusTcpClient
8+
from SungrowModbusTcpClient import SungrowModbusTcpClient # type: ignore
99
from modbus4mqtt.modbus_table import ModbusTable
1010

1111
DEFAULT_READ_BATCHING = 100
@@ -48,18 +48,26 @@ def __init__(
4848
self._unit: int = device_address
4949
self._variant: str | None = variant
5050
self._word_order: WordOrder = word_order
51-
self._read_batching: int = read_batching
52-
self._write_batching: int = write_batching
53-
if not MIN_BATCHING <= self._read_batching <= MAX_BATCHING:
51+
self._read_batching: int = (
52+
read_batching if read_batching is not None else DEFAULT_READ_BATCHING
53+
)
54+
self._write_batching: int = (
55+
write_batching if write_batching is not None else DEFAULT_WRITE_BATCHING
56+
)
57+
if not (MIN_BATCHING <= self._read_batching <= MAX_BATCHING):
5458
logging.warning(
5559
f"Bad value for read_batching: {self._read_batching}. Enforcing limits of {MIN_BATCHING} to {MAX_BATCHING}."
5660
)
57-
self._read_batching = max(MIN_BATCHING, min(MAX_BATCHING, self._read_batching))
58-
if not MIN_BATCHING <= self._write_batching <= MAX_BATCHING:
61+
self._read_batching = max(
62+
MIN_BATCHING, min(MAX_BATCHING, self._read_batching)
63+
)
64+
if not (MIN_BATCHING <= self._write_batching <= MAX_BATCHING):
5965
logging.warning(
6066
f"Bad value for write_batching: {self._write_batching}. Enforcing limits of {MIN_BATCHING} to {MAX_BATCHING}."
6167
)
62-
self._write_batching = max(MIN_BATCHING, min(MAX_BATCHING, self._write_batching))
68+
self._write_batching = max(
69+
MIN_BATCHING, min(MAX_BATCHING, self._write_batching)
70+
)
6371
if self._write_mode == WriteMode.Single and self._write_batching != 1:
6472
logging.warning("Overriding write batching to 1 due to single write mode.")
6573
self._write_batching = 1

modbus4mqtt/modbus_table.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,9 +46,9 @@ def _generate_batched_addresses(
4646
# of a range of addresses that can be read/written together.
4747
# If "write_mode" is true, the returned lists will only include
4848
# registers that've changed since the last read operation.
49-
result = []
50-
current_batch_start = None
51-
current_batch_size = 0
49+
result: list[tuple[int, int]] = []
50+
current_batch_start: int = -1
51+
current_batch_size: int = 0
5252
previous_addr = None
5353
if write_mode:
5454
max_batch_size = self._write_batch_size
@@ -60,17 +60,17 @@ def _generate_batched_addresses(
6060
if current_batch_size >= max_batch_size or (
6161
previous_addr is not None and addr != previous_addr + 1
6262
):
63-
result.append([current_batch_start, current_batch_size])
63+
result.append((current_batch_start, current_batch_size))
6464
current_batch_start = addr
6565
current_batch_size = 1
6666
else:
67-
if current_batch_start is None:
67+
if current_batch_start == -1:
6868
current_batch_start = addr
6969
current_batch_size += 1
7070
previous_addr = addr
7171
# Don't forget to add the last batch
72-
if current_batch_start is not None:
73-
result.append([current_batch_start, current_batch_size])
72+
if current_batch_start != -1:
73+
result.append((current_batch_start, current_batch_size))
7474
return result
7575

7676
def clear_changed_registers(self):

tests/test_modbus_server.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@
88
import asyncio
99
from paho.mqtt import client as mqtt_client
1010

11-
from pymodbus import ModbusDeviceIdentification
11+
from pymodbus import (
12+
ModbusDeviceIdentification,
13+
)
1214
from pymodbus.server import ModbusTcpServer
15+
from pymodbus.constants import ExcCodes
1316
from pymodbus.datastore import (
1417
ModbusDeviceContext,
1518
ModbusSequentialDataBlock,
@@ -47,7 +50,12 @@ async def set_holding_register(self, address: int, value: int) -> None:
4750

4851
async def get_holding_register(self, address: int) -> int:
4952
"""Get holding register value."""
50-
return self.holding_registers.getValues(address + 1, count=1)[0]
53+
result = self.holding_registers.getValues(address + 1, count=1)
54+
if type(result) is ExcCodes:
55+
raise ValueError(f"Error getting holding register at address {address}")
56+
if type(result) is list and len(result) > 0:
57+
return result[0]
58+
raise ValueError(f"Error getting holding register at address {address}")
5159

5260
async def run_async_server(self) -> None:
5361
"""Run server."""

tests/test_modbustable.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ def test_generate_batched_addresses_simple():
5757
table.add_register(addr)
5858
batches = table.get_batched_addresses()
5959
# Should batch: [1,2] (start=1, len=2), [3] (start=3, len=1), [10,11] (start=10, len=2)
60-
assert batches == [[1, 2], [3, 1], [10, 2]]
60+
assert batches == [(1, 2), (3, 1), (10, 2)]
6161

6262

6363
def test_generate_batched_addresses_max_batch():
@@ -66,7 +66,7 @@ def test_generate_batched_addresses_max_batch():
6666
table.add_register(addr)
6767
batches = table.get_batched_addresses()
6868
# Should batch: [1,2,3,4] (start=1, len=4), [5] (start=5, len=1)
69-
assert batches == [[1, 4], [5, 1]]
69+
assert batches == [(1, 4), (5, 1)]
7070

7171

7272
def test_generate_batched_addresses_max_batch_write_mode():
@@ -80,4 +80,4 @@ def test_generate_batched_addresses_max_batch_write_mode():
8080
table.set_value(addr, 123, write=True)
8181
batches = table.get_batched_addresses(write_mode=True)
8282
# Should batch: [2] (start=2, len=1), [4] (start=4, len=1)
83-
assert batches == [[2, 1], [4, 1]]
83+
assert batches == [(2, 1), (4, 1)]

tests/test_mqtt.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -757,6 +757,7 @@ def assert_modbus_call(
757757
write_mode=modbus4mqtt.modbus_interface.WriteMode.Multi,
758758
variant=None,
759759
read_batching=None,
760+
write_batching=None,
760761
word_order=word_order,
761762
)
762763

0 commit comments

Comments
 (0)