Skip to content

Commit bf152bb

Browse files
authored
Fix more typing issues (#1351)
Type hints (mypy) part 1.
1 parent b564144 commit bf152bb

File tree

11 files changed

+50
-48
lines changed

11 files changed

+50
-48
lines changed

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
*.pyc
33
*.swp
44
__pycache__/
5-
.cache/
5+
.*cache/
66
.coverage
77
.DS_Store
88
.eggs/
99
.idea
1010
.idea/
1111
.noseids
1212
.pymodhis
13-
.pytest_cache/
1413
.venv
1514
.vscode
1615
.vscode/

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ The default command can be overridden by passing any valid command at the end.::
277277

278278
Usage: pymodbus.server [OPTIONS] COMMAND [ARGS]...
279279

280-
Reactive modebus server
280+
Reactive Modbus server
281281

282282
╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
283283
│ --host TEXT Host address [default: localhost] │

pymodbus/client/base.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ def run():
6464
"""
6565

6666
state = ModbusTransactionState.IDLE
67-
last_frame_end = 0
68-
silent_interval = 0
67+
last_frame_end: float = 0
68+
silent_interval: float = 0
6969

7070
@dataclass
7171
class _params: # pylint: disable=too-many-instance-attributes
@@ -163,7 +163,7 @@ def is_socket_open(self) -> bool:
163163
"""Return whether socket/serial is open or not (call **sync**)."""
164164
raise NotImplementedException
165165

166-
def idle_time(self) -> int:
166+
def idle_time(self) -> float:
167167
"""Time before initiating next transaction (call **sync**).
168168
169169
Applications can call message functions without checking idle_time(),

pymodbus/client/serial.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def __init__(
5555
framer: ModbusFramer = ModbusRtuFramer,
5656
baudrate: int = Defaults.Baudrate,
5757
bytesize: int = Defaults.Bytesize,
58-
parity: chr = Defaults.Parity,
58+
parity: str = Defaults.Parity,
5959
stopbits: int = Defaults.Stopbits,
6060
handle_local_echo: bool = Defaults.HandleLocalEcho,
6161
**kwargs: Any,
@@ -203,16 +203,16 @@ def run():
203203
"""
204204

205205
state = ModbusTransactionState.IDLE
206-
inter_char_timeout = 0
207-
silent_interval = 0
206+
inter_char_timeout: float = 0
207+
silent_interval: float = 0
208208

209209
def __init__(
210210
self,
211211
port: str,
212212
framer: ModbusFramer = ModbusRtuFramer,
213213
baudrate: int = Defaults.Baudrate,
214214
bytesize: int = Defaults.Bytesize,
215-
parity: chr = Defaults.Parity,
215+
parity: str = Defaults.Parity,
216216
stopbits: int = Defaults.Stopbits,
217217
handle_local_echo: bool = Defaults.HandleLocalEcho,
218218
**kwargs: Any,

pymodbus/datastore/simulator.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import random
44
import struct
55
from datetime import datetime
6-
from typing import Any, Callable, Dict
6+
from typing import Any, Callable, Dict, List
77

88

99
WORD_SIZE = 16
@@ -30,7 +30,7 @@ class Cell:
3030
access: bool = False
3131
value: int = 0
3232
action: int = 0
33-
action_kwargs: int = None
33+
action_kwargs: Dict[str, Any] = None
3434
count_read: int = 0
3535
count_write: int = 0
3636

@@ -455,15 +455,15 @@ def __init__(
455455
self, config: Dict[str, Any], custom_actions: Dict[str, Callable]
456456
) -> None:
457457
"""Initialize."""
458-
self.registers = []
459-
self.fc_offset = {}
458+
self.registers: List[int] = []
459+
self.fc_offset: Dict[int, int] = {}
460460
self.register_count = 0
461461
self.type_exception = False
462-
self.action_name_to_id = {}
463-
self.action_id_to_name = []
464-
self.action_methods = []
465-
self.registerType_name_to_id = {}
466-
self.registerType_id_to_name = []
462+
self.action_name_to_id: Dict[str, int] = {}
463+
self.action_id_to_name: List[str] = []
464+
self.action_methods: List[Callable] = []
465+
self.registerType_name_to_id: Dict[str, int] = {}
466+
self.registerType_id_to_name: List[str] = []
467467
Setup(self).setup(config, custom_actions)
468468

469469
# --------------------------------------------

pymodbus/repl/client/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ def _(event):
256256

257257

258258
@click.group("pymodbus-repl")
259-
@click.version_option(version, message=TITLE)
259+
@click.version_option(str(version), message=TITLE)
260260
@click.option("--verbose", is_flag=True, default=False, help="Verbose logs")
261261
@click.option(
262262
"--broadcast-support",

pymodbus/repl/server/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Invoke REPL server with `pymodbus.server run` command.
2828

2929
Usage: pymodbus.server [OPTIONS] COMMAND [ARGS]...
3030

31-
Reactive modebus server
31+
Reactive Modbus server
3232

3333
╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
3434
│ --host TEXT Host address [default: localhost] │
@@ -63,7 +63,7 @@ docker run -it pymodbus-dev/pymodbus pymodbus.server --help
6363
╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮
6464
│ --modbus-server -s TEXT Modbus Server [default: ModbusServerTypes.tcp] │
6565
│ --framer -f TEXT Modbus framer to use [default: ModbusFramerTypes.socket] │
66-
│ --modbus-port -p TEXT Modbus port [default: 5020] │
66+
│ --modbus-port -p INTEGER Modbus port [default: 5020] │
6767
│ --unit-id -u INTEGER Supported Modbus unit id's [default: None] │
6868
│ --modbus-config PATH Path to additional modbus server config [default: None] │
6969
│ --random -r INTEGER Randomize every `r` reads. 0=never, 1=always,2=every-second-read, and so on. Applicable │

pymodbus/repl/server/main.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ def process_extra_args(extra_args: list[str], modbus_config: dict) -> dict:
9090
app = typer.Typer(
9191
no_args_is_help=True,
9292
context_settings=CONTEXT_SETTING,
93-
help="Reactive modebus server",
93+
help="Reactive Modbus server",
9494
)
9595

9696

@@ -138,7 +138,7 @@ def run(
138138
autocompletion=framers,
139139
help="Modbus framer to use",
140140
),
141-
modbus_port: str = typer.Option("5020", "--modbus-port", "-p", help="Modbus port"),
141+
modbus_port: int = typer.Option(5020, "--modbus-port", "-p", help="Modbus port"),
142142
modbus_unit_id: List[int] = typer.Option(
143143
None, "--unit-id", "-u", help="Supported Modbus unit id's"
144144
),
@@ -180,7 +180,6 @@ def run(
180180
modbus_config = modbus_config.get(modbus_server, {})
181181
modbus_config = process_extra_args(extra_args, modbus_config)
182182
if modbus_server != "serial":
183-
modbus_port = int(modbus_port)
184183
handler = modbus_config.pop("handler", "ModbusConnectedRequestHandler")
185184
else:
186185
handler = modbus_config.pop("handler", "ModbusSingleRequestHandler")

pymodbus/server/simulator/http_server.py

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import json
66
import os
77
from time import time
8+
from typing import List
89

910

1011
try:
@@ -44,8 +45,8 @@ class CallTypeMonitor:
4445
"""Define Request/Response monitor"""
4546

4647
active: bool = False
47-
range_start: int = ""
48-
range_stop: int = ""
48+
range_start: int = -1
49+
range_stop: int = -1
4950
function: int = -1
5051
hex: bool = False
5152
decode: bool = False
@@ -176,7 +177,7 @@ def __init__(
176177
with open(file, encoding="utf-8") as handle:
177178
self.generator_html[entry][0] = handle.read()
178179
self.refresh_rate = 0
179-
self.register_filter = []
180+
self.register_filter: List[int] = []
180181
self.call_list = []
181182
self.call_monitor = CallTypeMonitor()
182183
self.call_response = CallTypeResponse()
@@ -326,15 +327,11 @@ async def build_html_log(self, _params, html):
326327

327328
def helper_build_html_calls_submit_monitor(self, params):
328329
"""Build html calls submit."""
329-
if params["range_start"]:
330-
self.call_monitor.range_start = int(params["range_start"])
331-
if params["range_stop"]:
332-
self.call_monitor.range_stop = int(params["range_stop"])
333-
else:
334-
self.call_monitor.range_stop = self.call_monitor.range_start
330+
self.call_monitor.range_start = params["range_start"]
331+
if params["range_stop"] != -1:
332+
self.call_monitor.range_stop = params["range_stop"]
335333
else:
336-
self.call_monitor.range_start = ""
337-
self.call_monitor.range_stop = ""
334+
self.call_monitor.range_stop = self.call_monitor.range_start
338335
if params["function"]:
339336
self.call_monitor.function = int(params["function"])
340337
else:
@@ -412,9 +409,19 @@ async def build_html_calls(self, params, html):
412409
):
413410
selected = "selected" if i == self.call_response.error_response else ""
414411
function_error += f"<option value={i} {selected}>{txt}</option>"
412+
range_start_html = (
413+
str(self.call_monitor.range_start)
414+
if self.call_monitor.range_start != -1
415+
else ""
416+
)
417+
range_stop_html = (
418+
str(self.call_monitor.range_stop)
419+
if self.call_monitor.range_stop != -1
420+
else ""
421+
)
415422
html = (
416-
html.replace("FUNCTION_RANGE_START", str(self.call_monitor.range_start))
417-
.replace("FUNCTION_RANGE_STOP", str(self.call_monitor.range_stop))
423+
html.replace("FUNCTION_RANGE_START", range_start_html)
424+
.replace("FUNCTION_RANGE_STOP", range_stop_html)
418425
.replace("<!--FUNCTION_TYPES-->", function_error)
419426
.replace(
420427
"FUNCTION_SHOW_HEX_CHECKED", "checked" if self.call_monitor.hex else ""
@@ -493,14 +500,8 @@ async def build_json_server(self, params, json_dict):
493500

494501
def helper_build_filter(self, params):
495502
"""Build list of registers matching filter."""
496-
if x := params.get("range_start"):
497-
range_start = int(x)
498-
else:
499-
range_start = -1
500-
if x := params.get("range_stop"):
501-
range_stop = int(x)
502-
else:
503-
range_stop = range_start
503+
range_start = params.get("range_start", -1)
504+
range_stop = params.get("range_stop", range_start)
504505
reg_action = int(params["action"])
505506
reg_writeable = "writeable" in params
506507
reg_type = int(params["type"])

pymodbus/version.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,14 @@ def __init__(self, package, major, minor, micro, pre=None):
2222
self.micro = micro
2323
self.pre = pre
2424

25-
def short(self):
25+
def short(self) -> str:
2626
"""Return a string in canonical short version format: <major>.<minor>.<micro>.<pre>."""
2727
pre = ""
2828
if self.pre:
2929
pre = f".{self.pre}"
3030
return f"{self.major}.{self.minor}.{self.micro}{pre}"
3131

32-
def __str__(self):
32+
def __str__(self) -> str:
3333
"""Return a string representation of the object.
3434
3535
:returns: A string representation of this object

0 commit comments

Comments
 (0)