mbus-ffi 0.13.0

Native C FFI and browser WASM bindings for modbus-rs client APIs, with optional generated server bindings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
"""
Type stubs for the ``modbus_rs._modbus_rs`` native extension module.

All classes are generated by the Rust / PyO3 backend.  Async methods return
awaitables that can be ``await``-ed with any asyncio-compatible event loop.
"""

from __future__ import annotations
from typing import Any, Optional, Awaitable

# ---------------------------------------------------------------------------
# Exceptions
# ---------------------------------------------------------------------------

class ModbusError(Exception):
    """Base exception for all modbus-rs errors."""

class ModbusTimeout(ModbusError):
    """Request timed out waiting for a response."""

class ModbusConnectionError(ModbusError):
    """Connection could not be established or was lost."""

class ModbusProtocolError(ModbusError):
    """The remote device returned a malformed or unexpected PDU."""

class ModbusDeviceException(ModbusProtocolError):
    """The remote device returned a Modbus exception response."""

class ModbusConfigError(ModbusError):
    """Invalid configuration (address, baud rate, etc.)."""

class ModbusInvalidArgument(ModbusError):
    """Invalid argument passed to a Modbus call (out-of-range address, count, etc.)."""

# ---------------------------------------------------------------------------
# Sync TCP client
# ---------------------------------------------------------------------------

class TcpClient:
    """Synchronous (blocking) Modbus TCP client.

    Each method releases the GIL while waiting for the network response so
    that other Python threads continue to run.

    Usage::

        with TcpClient("192.168.1.10", unit_id=1) as client:
            regs = client.read_holding_registers(0, 5)
    """

    def __init__(
        self,
        host: str,
        port: int = 502,
        unit_id: int = 1,
        timeout_ms: int = 1000,
    ) -> None: ...

    def connect(self) -> None:
        """Establish the TCP connection."""

    def disconnect(self) -> None:
        """Disconnect from the server."""

    def has_pending_requests(self) -> bool:
        """Return ``True`` if there are in-flight requests."""

    def __enter__(self) -> TcpClient: ...
    def __exit__(self, *args: Any) -> bool: ...

    # Coils
    def read_coils(self, address: int, quantity: int) -> list[bool]: ...
    def write_coil(self, address: int, value: bool) -> tuple[int, bool]: ...
    def write_coils(self, address: int, values: list[bool]) -> None: ...

    # Discrete inputs
    def read_discrete_inputs(self, address: int, quantity: int) -> list[bool]: ...

    # Holding registers
    def read_holding_registers(self, address: int, quantity: int) -> list[int]: ...
    def write_register(self, address: int, value: int) -> tuple[int, int]: ...
    def write_registers(self, address: int, values: list[int]) -> None: ...
    def mask_write_register(
        self, address: int, and_mask: int, or_mask: int
    ) -> tuple[int, int, int]: ...
    def read_write_registers(
        self,
        read_address: int,
        read_quantity: int,
        write_address: int,
        write_values: list[int],
    ) -> list[int]: ...

    # Input registers
    def read_input_registers(self, address: int, quantity: int) -> list[int]: ...

    # FIFO queue
    def read_fifo_queue(self, address: int) -> list[int]: ...

    # File records
    def read_file_record(self, file_number: int, record_number: int, record_length: int) -> list[int]: ...
    def write_file_record(self, file_number: int, record_number: int, data: list[int]) -> None: ...

    # Diagnostics
    def get_device_identification(self, object_id: int) -> dict[int, bytes]: ...

# ---------------------------------------------------------------------------
# Async TCP client
# ---------------------------------------------------------------------------

class AsyncTcpClient:
    """Asyncio Modbus TCP client.

    Usage::

        async with AsyncTcpClient("192.168.1.10", unit_id=1) as client:
            regs = await client.read_holding_registers(0, 5)
    """

    def __init__(
        self,
        host: str,
        port: int = 502,
        unit_id: int = 1,
        timeout_ms: int = 1000,
    ) -> None: ...

    def connect(self) -> Any:
        """Awaitable — establish the TCP connection."""

    def has_pending_requests(self) -> bool:
        """Return ``True`` if there are in-flight requests."""

    async def __aenter__(self) -> AsyncTcpClient: ...
    async def __aexit__(self, *args: Any) -> bool: ...

    # Coils
    def read_coils(self, address: int, quantity: int) -> Any: ...
    def write_coil(self, address: int, value: bool) -> Any: ...
    def write_coils(self, address: int, values: list[bool]) -> Any: ...

    # Discrete inputs
    def read_discrete_inputs(self, address: int, quantity: int) -> Any: ...

    # Holding registers
    def read_holding_registers(self, address: int, quantity: int) -> Any: ...
    def write_register(self, address: int, value: int) -> Any: ...
    def write_registers(self, address: int, values: list[int]) -> Any: ...
    def mask_write_register(self, address: int, and_mask: int, or_mask: int) -> Any: ...
    def read_write_registers(
        self,
        read_address: int,
        read_quantity: int,
        write_address: int,
        write_values: list[int],
    ) -> Any: ...

    # Input registers
    def read_input_registers(self, address: int, quantity: int) -> Any: ...

    # FIFO queue
    def read_fifo_queue(self, address: int) -> Any: ...

    # File records
    def read_file_record(self, file_number: int, record_number: int, record_length: int) -> Any: ...
    def write_file_record(self, file_number: int, record_number: int, data: list[int]) -> Any: ...

    # Diagnostics
    def get_device_identification(self, object_id: int) -> Any: ...

# ---------------------------------------------------------------------------
# Sync serial client
# ---------------------------------------------------------------------------

class SerialClient:
    """Synchronous (blocking) Modbus serial client (RTU or ASCII).

    Usage::

        with SerialClient("/dev/ttyUSB0", baud_rate=9600, unit_id=1) as client:
            regs = client.read_holding_registers(0, 5)
    """

    def __init__(
        self,
        port: str,
        baud_rate: int = 9600,
        unit_id: int = 1,
        mode: str = "rtu",
        timeout_ms: int = 1000,
    ) -> None: ...

    def connect(self) -> None: ...
    def disconnect(self) -> None: ...
    def has_pending_requests(self) -> bool: ...

    def __enter__(self) -> SerialClient: ...
    def __exit__(self, *args: Any) -> bool: ...

    # Coils
    def read_coils(self, address: int, quantity: int) -> list[bool]: ...
    def write_coil(self, address: int, value: bool) -> tuple[int, bool]: ...
    def write_coils(self, address: int, values: list[bool]) -> None: ...

    # Discrete inputs
    def read_discrete_inputs(self, address: int, quantity: int) -> list[bool]: ...

    # Holding registers
    def read_holding_registers(self, address: int, quantity: int) -> list[int]: ...
    def write_register(self, address: int, value: int) -> tuple[int, int]: ...
    def write_registers(self, address: int, values: list[int]) -> None: ...
    def mask_write_register(self, address: int, and_mask: int, or_mask: int) -> tuple[int, int, int]: ...
    def read_write_registers(
        self,
        read_address: int,
        read_quantity: int,
        write_address: int,
        write_values: list[int],
    ) -> list[int]: ...

    # Input registers
    def read_input_registers(self, address: int, quantity: int) -> list[int]: ...

    # FIFO queue
    def read_fifo_queue(self, address: int) -> list[int]: ...

    # File records
    def read_file_record(self, file_number: int, record_number: int, record_length: int) -> list[int]: ...
    def write_file_record(self, file_number: int, record_number: int, data: list[int]) -> None: ...

    # Diagnostics
    def get_device_identification(self, object_id: int) -> dict[int, bytes]: ...

# ---------------------------------------------------------------------------
# Async serial client
# ---------------------------------------------------------------------------

class AsyncSerialClient:
    """Asyncio Modbus serial client (RTU or ASCII).

    Usage::

        async with AsyncSerialClient("/dev/ttyUSB0", unit_id=1) as client:
            regs = await client.read_holding_registers(0, 5)
    """

    def __init__(
        self,
        port: str,
        baud_rate: int = 9600,
        unit_id: int = 1,
        mode: str = "rtu",
        timeout_ms: int = 1000,
    ) -> None: ...

    def connect(self) -> Any: ...
    def has_pending_requests(self) -> bool: ...

    async def __aenter__(self) -> AsyncSerialClient: ...
    async def __aexit__(self, *args: Any) -> bool: ...

    # Coils
    def read_coils(self, address: int, quantity: int) -> Any: ...
    def write_coil(self, address: int, value: bool) -> Any: ...
    def write_coils(self, address: int, values: list[bool]) -> Any: ...

    # Discrete inputs
    def read_discrete_inputs(self, address: int, quantity: int) -> Any: ...

    # Holding registers
    def read_holding_registers(self, address: int, quantity: int) -> Any: ...
    def write_register(self, address: int, value: int) -> Any: ...
    def write_registers(self, address: int, values: list[int]) -> Any: ...
    def mask_write_register(self, address: int, and_mask: int, or_mask: int) -> Any: ...
    def read_write_registers(
        self,
        read_address: int,
        read_quantity: int,
        write_address: int,
        write_values: list[int],
    ) -> Any: ...

    # Input registers
    def read_input_registers(self, address: int, quantity: int) -> Any: ...

    # FIFO queue
    def read_fifo_queue(self, address: int) -> Any: ...

    # File records
    def read_file_record(self, file_number: int, record_number: int, record_length: int) -> Any: ...
    def write_file_record(self, file_number: int, record_number: int, data: list[int]) -> Any: ...

    # Diagnostics
    def get_device_identification(self, object_id: int) -> Any: ...

# ---------------------------------------------------------------------------
# Server application base class
# ---------------------------------------------------------------------------

class ModbusApp:
    """Base class for Modbus server application handlers.

    Subclass this and override the ``handle_*`` methods to implement your
    server logic.  Raise :class:`ModbusError` (or a subclass) to return an
    exception response to the client.

    Usage::

        class MyApp(modbus_rs.ModbusApp):
            def handle_read_holding_registers(self, address, count):
                return [0] * count
    """

    def handle_read_coils(self, address: int, count: int) -> list[bool] | Awaitable[list[bool]]:
        """Return a list of ``count`` coil values starting at ``address``."""
        ...

    def handle_write_coil(self, address: int, value: bool) -> None | Awaitable[None]:
        """Set the coil at ``address`` to ``value``."""
        ...

    def handle_write_coils(self, address: int, values: list[bool]) -> None | Awaitable[None]:
        """Write multiple coils (FC15)."""
        ...

    def handle_read_discrete_inputs(self, address: int, count: int) -> list[bool] | Awaitable[list[bool]]:
        """Return a list of ``count`` discrete input values starting at ``address``."""
        ...

    def handle_read_holding_registers(self, address: int, count: int) -> list[int] | Awaitable[list[int]]:
        """Return a list of ``count`` holding register values."""
        ...

    def handle_read_input_registers(self, address: int, count: int) -> list[int] | Awaitable[list[int]]:
        """Return a list of ``count`` input register values."""
        ...

    def handle_write_register(self, address: int, value: int) -> None | Awaitable[None]:
        """Write a single holding register."""
        ...

    def handle_write_registers(self, address: int, values: list[int]) -> None | Awaitable[None]:
        """Write multiple holding registers (FC16)."""
        ...

    def handle_mask_write_register(
        self, address: int, and_mask: int, or_mask: int
    ) -> None | Awaitable[None]:
        """Apply bit masks to a holding register (FC22)."""
        ...

    def handle_read_write_registers(
        self,
        read_address: int,
        read_count: int,
        write_address: int,
        write_values: list[int],
    ) -> list[int] | Awaitable[list[int]]:
        """Read/write holding registers in one transaction (FC23)."""
        ...

    def handle_read_fifo_queue(self, pointer_address: int) -> list[int] | Awaitable[list[int]]:
        """Return FIFO queue contents starting at ``pointer_address`` (FC24)."""
        ...

    def handle_read_exception_status(self) -> int | Awaitable[int]:
        """Return the 8-bit exception status byte (FC07)."""
        ...

    def handle_get_comm_event_counter(self) -> tuple[int, int] | Awaitable[tuple[int, int]]:
        """Return ``(status, event_count)`` tuple (FC11)."""
        ...

# ---------------------------------------------------------------------------
# Async TCP server
# ---------------------------------------------------------------------------

class AsyncTcpServer:
    """Asyncio Modbus TCP server.

    Pass a :class:`ModbusApp` subclass instance; the server dispatches each
    incoming request to the corresponding ``handle_*`` method.

    Usage::

        class MyApp(modbus_rs.ModbusApp):
            def handle_read_holding_registers(self, address, count):
                return [0] * count

        async def main():
            async with AsyncTcpServer("0.0.0.0", MyApp(), port=502, unit_id=1) as server:
                await server.serve_forever()
    """

    def __init__(
        self,
        host: str,
        app: ModbusApp,
        port: int = 502,
        unit_id: int = 1,
    ) -> None: ...

    def serve_forever(self) -> Any:
        """Awaitable — bind and serve until an error occurs."""

    async def __aenter__(self) -> AsyncTcpServer: ...
    async def __aexit__(self, *args: Any) -> bool: ...

# ---------------------------------------------------------------------------
# Sync TCP server
# ---------------------------------------------------------------------------

class TcpServer:
    """Synchronous (blocking) Modbus TCP server.

    Blocks the calling thread until an error or shutdown.

    Usage::

        server = TcpServer("0.0.0.0", MyApp(), port=502, unit_id=1)
        server.serve_forever()  # blocks
    """

    def __init__(
        self,
        host: str,
        app: ModbusApp,
        port: int = 502,
        unit_id: int = 1,
    ) -> None: ...

    def serve_forever(self) -> None:
        """Block the calling thread, serving requests until an error."""

    def __enter__(self) -> TcpServer: ...
    def __exit__(self, *args: Any) -> bool: ...

# ---------------------------------------------------------------------------
# Async serial server
# ---------------------------------------------------------------------------

class AsyncSerialServer:
    """Asyncio Modbus serial server (RTU or ASCII).

    Usage::

        async with AsyncSerialServer("/dev/ttyUSB0", MyApp(), unit_id=1) as srv:
            await srv.serve_forever()
    """

    def __init__(
        self,
        port: str,
        app: ModbusApp,
        baud_rate: int = 9600,
        unit_id: int = 1,
        mode: str = "rtu",
        timeout_ms: int = 1000,
    ) -> None: ...

    def serve_forever(self) -> Any:
        """Awaitable — run the server until the port closes."""

    async def __aenter__(self) -> AsyncSerialServer: ...
    async def __aexit__(self, *args: Any) -> bool: ...

# ---------------------------------------------------------------------------
# Sync serial server
# ---------------------------------------------------------------------------

class SerialServer:
    """Synchronous (blocking) Modbus serial server (RTU or ASCII).

    Usage::

        server = SerialServer("/dev/ttyUSB0", MyApp(), baud_rate=9600, unit_id=1)
        server.serve_forever()  # blocks
    """

    def __init__(
        self,
        port: str,
        app: ModbusApp,
        baud_rate: int = 9600,
        unit_id: int = 1,
        mode: str = "rtu",
        timeout_ms: int = 1000,
    ) -> None: ...

    def serve_forever(self) -> None:
        """Block the calling thread, serving requests until the port closes."""

    def __enter__(self) -> SerialServer: ...
    def __exit__(self, *args: Any) -> bool: ...


# ─── Gateway (feature: python-gateway) ─────────────────────────────────────

class GatewayEventHandler:
    """
    Forward-compatible base class for gateway lifecycle events.

    All methods are no-ops by default. Override only what you need.
    """

    def __init__(self) -> None: ...
    def on_forward(self, session_id: int, unit_id: int, channel_idx: int) -> None: ...
    def on_response_returned(self, session_id: int, upstream_txn: int) -> None: ...
    def on_routing_miss(self, session_id: int, unit_id: int) -> None: ...
    def on_downstream_timeout(self, session_id: int, internal_txn: int) -> None: ...
    def on_upstream_disconnect(self, session_id: int) -> None: ...


class AsyncTcpGateway:
    """Asyncio Modbus TCP→TCP gateway."""

    def __init__(
        self,
        bind_addr: str,
        event_handler: Optional[GatewayEventHandler] = None,
    ) -> None: ...

    def bind_address(self) -> str: ...
    def add_tcp_downstream(self, host: str, port: int = 502) -> int:
        """Register a downstream TCP endpoint; returns its channel index."""
    def add_unit_route(self, unit: int, channel: int) -> None: ...
    def add_range_route(self, min: int, max: int, channel: int) -> None: ...

    async def serve_forever(self) -> None:
        """Bind the listener and serve until :meth:`stop` is called."""

    def stop(self) -> None: ...

    async def __aenter__(self) -> "AsyncTcpGateway": ...
    async def __aexit__(self, *args: Any) -> bool: ...


class TcpGateway:
    """Blocking Modbus TCP→TCP gateway."""

    def __init__(
        self,
        bind_addr: str,
        event_handler: Optional[GatewayEventHandler] = None,
    ) -> None: ...

    def bind_address(self) -> str: ...
    def add_tcp_downstream(self, host: str, port: int = 502) -> int: ...
    def add_unit_route(self, unit: int, channel: int) -> None: ...
    def add_range_route(self, min: int, max: int, channel: int) -> None: ...

    def serve_forever(self) -> None:
        """Block the calling thread, serving until :meth:`stop` is called."""

    def stop(self) -> None: ...

    def __enter__(self) -> "TcpGateway": ...
    def __exit__(self, *args: Any) -> bool: ...