pyModbusTCP.server
The Modbus/TCP server, its data store, the access rules and the function handlers. See Modbus/TCP server for an introduction.
from pyModbusTCP.server import MemoryStore, ModbusServer, Space
ModbusServer
- class pyModbusTCP.server.ModbusServer(host: str = 'localhost', port: int = 502, no_block: bool = False, *, ipv6: bool = False, store: DataStore | Mapping[int, DataStore] | None = None, functions: Mapping[int, Callable[[Request], bytes]] | None = None, fallback: Callable[[Request], bytes] | None = None, device_id: DeviceIdentification | None = None, request_timeout: float | None = 30.0, idle_timeout: float | None = 300, max_connections: int | None = 128, max_connections_per_host: int | None = 16, evict_idle: bool = True, read_only: bool = False, allowed_hosts: Iterable[str] | None = None, ipv6_host_prefix: int = 64)[source]
Modbus TCP server
Initialize a Modbus TCP server.
Sets up a Modbus TCP server with configurable network parameters, data handling, and optional device identification. Type validation is performed on critical parameters to prevent silent runtime failures.
The arguments after no_block are keyword-only (like
ModbusServer('0.0.0.0', 5020, read_only=True)).The access control and limit settings (allowed_hosts, read_only, max_connections, max_connections_per_host, ipv6_host_prefix, request_timeout and idle_timeout) are also properties: a new value is checked like in the constructor and applies at once to a running server (see each property). host, port and ipv6 apply at the next start().
- Parameters:
host (str) – hostname or IPv4/IPv6 address to listen on (default is ‘localhost’), ‘0.0.0.0’ (or ‘::’ with ipv6=True) for every interface; an empty host, or an IPv4 address in a legacy form that bind() reads as another address (‘0’ is 0.0.0.0, ‘192.168.010.1’ is 192.168.8.1), is refused (ValueError); a link-local IPv6 address with its interface only (‘fe80::1%eth0’: the server only listens on this link); a hostname is resolved by start(), once, and refused if it resolves to the wildcard address (0.0.0.0 or ::, write it as an IP address to listen on every interface)
port (int) – TCP port number (default is 502), use 0 to let the OS choose a free port
no_block (bool) – no block mode, i.e. start() will return (default is False)
ipv6 (bool) – use ipv6 stack (default is False)
store (DataStore or dict or None) – the data store of the server (default: a new MemoryStore), or a mapping {unit id: store} to simulate several devices (a request for another unit id gets a “gateway path unavailable” exception)
functions (dict or None) – the function handlers, {function code: handler(request) -> response PDU} (default: a copy of the standard functions, see STANDARD_FUNCTIONS), also available as the functions attribute
fallback (callable or None) – the handler of the requests whose function code has no handler (default: None, an “illegal function” exception), like a gateway that relays every request
device_id (DeviceIdentification) – instance of DeviceIdentification class for read device identification request (optional)
request_timeout (float or None) – max time in seconds to receive a whole request (MBAP header and PDU) from its first byte (a stalled request), on expiry the client session is closed, None to disable (default is 30.0)
idle_timeout (float or None) – max time in seconds without any request from a client before closing its session, None to disable (default is 300.0)
max_connections (int or None) – max number of simultaneous client connections, None for no limit (default is 128). When it’s reached, a new client takes the place of the most idle session (see evict_idle), else it’s closed immediately
evict_idle (bool) – with max_connections reached, close the most idle session for a new client instead of refusing it: a session without any whole request first (the oldest), else the one with the oldest last request; never a session processing a request. The limit per host is checked before (a host at its limit is refused). False to refuse the new clients (default is True)
read_only (bool) – refuse the standard write functions (0x05, 0x06, 0x0F, 0x10, 0x15, 0x16 and 0x17) with an “illegal function” exception, whatever their handler; the fallback handler only gets the read functions (0x01 to 0x04, 0x2B/0x0E) (default is False). A function added or replaced by the application (see function()) is not checked: if it writes data, it must test server.read_only itself (and raise IllegalFunction), or the store must be wrapped in a ReadOnly wrapper
allowed_hosts (iterable of str or None) – whitelist of the clients allowed to connect: IP addresses or networks in CIDR notation (like [‘192.168.1.10’, ‘10.0.0.0/24’, ‘::1’]), other connections are closed at once, None to accept every client (default), an empty list for no client at all, hostnames are not supported; an IPv4-mapped entry (::ffff:a.b.c.d) is converted to IPv4, a link-local entry (fe80::/10) is refused (an allow list can’t tell the interface of a client)
max_connections_per_host (int or None) – max number of simultaneous connections from the same client host (an IPv4 address, or an IPv6 network, see ipv6_host_prefix), the next ones are closed immediately: a single host can’t take all the connections of max_connections. Clients behind a NAT share the same address. None for no limit (default is 16)
ipv6_host_prefix (int) – prefix length of the IPv6 network counted as one host by max_connections_per_host, 1 to 128 (default is 64: a host usually gets a whole /64 and can use any address of it, so a smaller group is easy to bypass). 128 counts each address apart: only for a network where a host can’t choose its addresses (static addresses, no SLAAC, source address filtering on the switches), or with allowed_hosts. A larger group (like 56) counts a client with a whole /56 as one host
- stores: dict[int, DataStore]
unit id -> data store, when the server has one store per unit id (else empty)
- functions: dict[int, Callable[[Request], bytes]]
function code -> handler, can be changed at any time (see function())
- fallback
handler of the other function codes (None: “illegal function” exception)
- property store: DataStore
The data store of the server (application access: server.store.app).
- Raises:
AttributeError – if the server has one store per unit id (see stores)
- property host: str
Get or set the address to listen on (applied by the next start()).
An empty host is refused (ValueError): for bind(), it is every interface. Use ‘0.0.0.0’ (or ‘::’ with ipv6=True) for that. So is an IPv4 address in a legacy form, read by bind() as another address (‘0’, ‘127.1’, ‘192.168.010.1’…).
- property allowed_hosts: tuple[str, ...] | None
Get or set the whitelist of the clients allowed to connect, as normalized networks (CIDR notation).
None: every client, an empty tuple: no client at all. A new value (an iterable of IP addresses or networks, or None) is checked like the constructor argument. On a running server it applies at once: the next connections are filtered with it, and the active sessions of the clients it no longer allows are closed. The value is a tuple: change the whitelist by setting a new value, never in place.
- property read_only: bool
Get or set the read-only mode (see the constructor): applies from the next request.
Only the standard write functions are refused: a function handler of the application that writes data tests it at each call (
if server.read_only: raise IllegalFunction()).
- property max_connections: int | None
Get or set the max number of simultaneous client connections (None: no limit).
On a running server, it applies to the next connections (the active sessions are kept).
- property evict_idle: bool
Get or set the eviction of the most idle session for a new client when max_connections is reached.
False: the new clients are refused. On a running server, it applies to the next connections.
- property max_connections_per_host: int | None
Get or set the max number of simultaneous connections of a client host (None: no limit).
On a running server, it applies to the next connections (the active sessions are kept).
- property ipv6_host_prefix: int
Get or set the prefix length of the IPv6 network counted as one host by max_connections_per_host.
64 by default, 128 to count each address apart (see the constructor). On a running server, the active sessions are counted again with the new value, which applies to the next connections (no session is closed).
- property request_timeout: float | None
Get or set the max time in seconds to receive a whole request (None: no limit).
On a running server, it applies from the next request of each session.
- property idle_timeout: float | None
Get or set the max time in seconds without any request before a session is closed (None: no limit).
On a running server, it applies from the next wait for a request of each session.
- property is_run: bool
Deprecated: use is_running.
- property is_running: bool
Return True if server running.
- property active_sessions: list[tuple[str, int]]
Return the (address, port) of the clients of all active sessions (empty if server is stopped).
- shutdown_sessions() int[source]
Call shutdown() on every active session (client connection).
The server keeps listening: new clients can still connect afterwards. It is automatically called when the server stops.
- Returns:
number of sessions the shutdown was requested for
- Return type:
int
- function(code: int) Callable[[Callable[[Request], bytes]], Callable[[Request], bytes]][source]
Decorator to add (or replace) the handler of a function code:
@server.function(0x41) def my_function(req: Request) -> bytes: return req.reply('>B', 42)
A handler takes a Request and returns the response PDU (bytes, function code first). It raises a ModbusException (like IllegalDataAddress) for an exception response. Delete server.functions[code] to remove a function.
- start() tuple[str, int][source]
Start the server.
This function will block (or not if no_block flag is set). With port=0, the port chosen by the OS is available through the returned tuple.
- Returns:
A tuple containing the bound host string and port integer.
- Return type:
Tuple[str, int]
- Raises:
NetworkError – if the server is already running, or can’t listen (port already in use, bad host…)
Data store
- class pyModbusTCP.server.Space(*values)[source]
The 4 Modbus data spaces.
- property is_bit: bool
True for the spaces of bits (coils and discrete inputs), False for the spaces of 16 bits registers.
- class pyModbusTCP.server.DataStore[source]
Where the server reads and writes the Modbus data: the base class of every store and store wrapper.
- abstractmethod transaction(ctx: RequestContext | None = None) AbstractContextManager[Transaction][source]
Return a context manager that runs an atomic transaction (it gives a Transaction object).
- Parameters:
ctx – the context of a client request, None for the application
- abstractmethod subscribe(listener: Callable[[ChangeEvent], None], app_writes: bool = False, threaded: bool = False) Callable[[], None][source]
Call listener with a ChangeEvent after each transaction that changed some values.
- Parameters:
listener – a function called with the ChangeEvent (its exceptions are logged)
app_writes – also notify the writes of the application (by default, only the client requests)
threaded – call the listener from a thread of the store instead of the thread that committed the transaction (the session thread of the client: its response waits for the listener); the events wait in a bounded queue, an event that doesn’t fit is dropped (and logged). A threaded listener gets the events one at a time, in the order of the commits. Without it, the listener is called by the thread of each transaction, without the lock of the store: by several threads at once (sessions of several clients), and two events can come in another order than their commits (a listener that keeps the last value of an address can keep the older one)
- Returns:
a function to call to unsubscribe
- class pyModbusTCP.server.MemoryStore(size: int = 65536, *, coils: int | range | None = None, discrete_inputs: int | range | None = None, holding_registers: int | range | None = None, input_registers: int | range | None = None, default_bit: bool = False, default_word: int = 0)[source]
The default data store: the 4 Modbus data spaces in memory, thread-safe.
Each space has size addresses from 0 (65536 by default). A space can have its own size, or its own range of addresses: MemoryStore(0, holding_registers=range(40_000, 41_000)) is a store with the holding registers 40000 to 40999 only (a request out of this range gets an “illegal data address” exception). A range of addresses can also be computed at each access (see map()), even out of the addresses of its space.
Constructor
- Parameters:
size – number of addresses of each space, from 0 (default 65536, 0 for a store with mapped ranges only)
coils – the coils, if different from size: their number (from address 0), or their addresses as a range (like range(100, 200): the coils 100 to 199)
discrete_inputs – the discrete inputs, if different from size (a number or a range, like coils)
holding_registers – the holding registers, if different from size (a number or a range, like coils)
input_registers – the input registers, if different from size (a number or a range, like coils)
default_bit – startup value of the coils and the discrete inputs (default False)
default_word – startup value of the registers (default 0)
- notify_queue_size: int = 10000
max number of change events waiting for the threaded listeners: a slow listener can’t make the memory grow without limit (with clients that write faster than it), the events that don’t fit are dropped and logged
- notify_queue_values: int = 200000
max number of values (ChangeEvent.size, of all these events together) waiting for the threaded listeners: an event holds up to 1968 values (a write of coils), so the number of events alone doesn’t bound the memory. An event that doesn’t fit is dropped and logged, like above; an event larger than this limit is only queued when nothing else waits
- size(space: Space) int[source]
The number of addresses of a space in memory (the mapped ranges are not counted).
- addresses(space: Space) range[source]
The addresses of a space in memory, like range(0, 65536) (the mapped ranges are not counted).
- transaction(ctx: RequestContext | None = None) Generator[Transaction, None, None][source]
Return a context manager that runs an atomic transaction (it gives a Transaction object).
- Parameters:
ctx – the context of a client request, None for the application
- map(space: Space, address: int, count: int, read: Callable[[int, int, RequestContext | None], Sequence[Any]], write: Callable[[int, list[Any], RequestContext | None], None] | None = None) None[source]
Compute the values of a range of addresses at each access, instead of keeping them in memory.
The functions run in the transaction (with the lock of the store): keep them fast. A mapped range can be beyond the size of its space (MemoryStore(size=0) for a store with mapped ranges only).
- Parameters:
space – the data space
address – first address of the range
count – number of addresses
read – read(address, count, ctx) returns the count values from address (ctx is None for the application)
write – write(address, values, ctx) for a writable range, None for a read-only range (a write gets an “illegal data address” exception). The store can’t restore what this function did if the transaction fails afterwards: only the values in memory are restored.
- Raises:
ValueError – if the range overlaps another mapped range, or is out of 0 to 65535
- subscribe(listener: Callable[[ChangeEvent], None], app_writes: bool = False, threaded: bool = False) Callable[[], None][source]
Call listener with a ChangeEvent after each transaction that changed some values.
- Parameters:
listener – a function called with the ChangeEvent (its exceptions are logged)
app_writes – also notify the writes of the application (by default, only the client requests)
threaded – call the listener from a thread of the store instead of the thread that committed the transaction (the session thread of the client: its response waits for the listener); the events wait in a bounded queue, an event that doesn’t fit is dropped (and logged). A threaded listener gets the events one at a time, in the order of the commits. Without it, the listener is called by the thread of each transaction, without the lock of the store: by several threads at once (sessions of several clients), and two events can come in another order than their commits (a listener that keeps the last value of an address can keep the older one)
- Returns:
a function to call to unsubscribe
- class pyModbusTCP.server.Transaction[source]
The access to the data during a transaction (see DataStore.transaction()).
- abstractmethod read(space: Space, address: int, count: int = 1) list[Any][source]
Read count values from address.
- Returns:
a list of count bool (space of bits) or int (space of registers)
- Raises:
ModbusException – like IllegalDataAddress for an address out of the space
- abstractmethod write(space: Space, address: int, values: Iterable[Any]) None[source]
Write values from address (nothing is written if a part of the range is invalid).
- Raises:
ModbusException – like IllegalDataAddress for an address out of the space
TypeError, ValueError – for an invalid value (see Space.check_values())
- class pyModbusTCP.server.RequestContext(client: ClientInfo = <factory>, unit_id: int = 0, function_code: int = 0)[source]
Where a request comes from: given to the transactions, the store wrappers and the change listeners.
The application accesses the store without context (None).
The client of a request context is a ModbusServer.ClientInfo: client.address is the IP address of the
client (str), client.port its TCP port (int).
Change notifications
- class pyModbusTCP.server.ChangeEvent(ctx: RequestContext | None, changes: Iterable[Change] | None = None, *, writes: Iterable[WrittenRange] = ())[source]
The changes of one committed transaction (one client request, or one application access).
The event keeps the ranges written by the transaction (writes); the changes, value by value, are only computed when a listener reads them (changes, of()), once: the store never pays for a detail nobody reads.
- Parameters:
ctx – the context of the client request, None for the application
changes – the changes value by value (default: computed from writes when they are read)
writes – the ranges written, in the order of the transaction
- property by_client: bool
True for the changes of a client request, False for an application write.
- property changes: tuple[Change, ...]
The values changed by the transaction, each address at most once (its value before the transaction and after it), in the order of their first change. A value written back to its first value is not a change.
- property size: int
The number of values that the event holds (written values, or changes): its weight in memory.
- class pyModbusTCP.server.Change(space: Space, address: int, old: Any, new: Any)[source]
A value changed by a transaction.
Create new instance of Change(space, address, old, new)
- address: int
Alias for field number 1
- old: Any
Alias for field number 2
- new: Any
Alias for field number 3
- class pyModbusTCP.server.WrittenRange(space: Space, address: int, old: tuple[Any, ...], new: tuple[Any, ...])[source]
A range of addresses written in memory by a transaction: the values before and after the write.
Some values of the range may be unchanged (written with the value they had): see ChangeEvent.changes.
Create new instance of WrittenRange(space, address, old, new)
- address: int
Alias for field number 1
- old: tuple[Any, ...]
Alias for field number 2
- new: tuple[Any, ...]
Alias for field number 3
Application access
- class pyModbusTCP.server.AppAccess(store: DataStore)[source]
The access of the application to a store (store.app): no client context, the wrappers don’t apply.
- transaction() AbstractContextManager[Transaction][source]
An atomic transaction of the application, to change several values (of several spaces) at once.
- class pyModbusTCP.server.SpaceAccess(store: DataStore, space: Space)[source]
The access of the application to one data space: store.app.coils, store.app.holding_registers…
- read(address: int, count: int = 1) list[Any][source]
Read count values from address.
- Raises:
IllegalDataAddress – if the range is out of the space
- write(address: int, values: Iterable[Any]) None[source]
Write values from address (all or nothing).
- Raises:
IllegalDataAddress – if the range is out of the space
TypeError, ValueError – for an invalid value (a register is a 16 bits unsigned int)
- class pyModbusTCP.server.RegistersAccess(store: DataStore, space: Space)[source]
Bases:
SpaceAccessThe access of the application to a space of registers, with typed values on 1, 2 or 4 registers.
read_values() and write_values() take a
Codec(any type and byte order). The shortcuts have one method per type: read_uint16(), write_int16()… on 1 register, read_uint32(), write_float64()… on 2 or 4 registers, with aByteOrder(defaultABCD: the first register holds the most significant word). The 64 bits shortcuts also take aByteOrder64, for the rare orders of 8 bytes; the 32 bits ones refuse it (ValueError).- read_values(address: int, codec: Codec, count: int = 1) list[int | float][source]
Read count values of the type of codec (count * codec.words registers from address).
- Raises:
IllegalDataAddress – if a register is out of the space
- write_values(address: int, values: Sequence[int | float], codec: Codec) None[source]
Write values of the type of codec from address (atomic: all the registers or nothing).
- Raises:
TypeError, ValueError – for a value that is not a value of the type (nothing is written)
IllegalDataAddress – if a register is out of the space
- read_uint16(address: int) int[source]
Read an unsigned 16 bits int on 1 register (like read(address)[0]).
- write_uint16(address: int, value: int) None[source]
Write an unsigned 16 bits int on 1 register (ValueError out of 0 to 65535).
- write_int16(address: int, value: int) None[source]
Write a signed 16 bits int (2’s complement) on 1 register (ValueError out of -32768 to 32767).
- read_uint32(address: int, byte_order: ByteOrder = ByteOrder.ABCD) int[source]
Read an unsigned 32 bits int on 2 registers.
- write_uint32(address: int, value: int, byte_order: ByteOrder = ByteOrder.ABCD) None[source]
Write an unsigned 32 bits int on 2 registers (ValueError out of 0 to 2**32 - 1).
- read_int32(address: int, byte_order: ByteOrder = ByteOrder.ABCD) int[source]
Read a signed 32 bits int (2’s complement) on 2 registers.
- write_int32(address: int, value: int, byte_order: ByteOrder = ByteOrder.ABCD) None[source]
Write a signed 32 bits int (2’s complement) on 2 registers (ValueError out of -2**31 to 2**31 - 1).
- read_float32(address: int, byte_order: ByteOrder = ByteOrder.ABCD) float[source]
Read an IEEE 754 single precision float on 2 registers.
- write_float32(address: int, value: float, byte_order: ByteOrder = ByteOrder.ABCD) None[source]
Write an IEEE 754 single precision float on 2 registers.
- read_uint64(address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) int[source]
Read an unsigned 64 bits int on 4 registers.
- write_uint64(address: int, value: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) None[source]
Write an unsigned 64 bits int on 4 registers (ValueError out of 0 to 2**64 - 1).
- read_int64(address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) int[source]
Read a signed 64 bits int (2’s complement) on 4 registers.
- write_int64(address: int, value: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) None[source]
Write a signed 64 bits int (2’s complement) on 4 registers (ValueError out of -2**63 to 2**63 - 1).
- read_float64(address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) float[source]
Read an IEEE 754 double precision float on 4 registers.
- write_float64(address: int, value: float, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) None[source]
Write an IEEE 754 double precision float on 4 registers.
Access rules
- class pyModbusTCP.server.StoreWrapper(store: DataStore)[source]
Base class of the wrappers: override check() to refuse some accesses of the clients.
The other attributes of the wrapped store (like MemoryStore.map()) are available on the wrapper.
- check(ctx: RequestContext, access: Literal['read', 'write'], space: Space, address: int, count: int) None[source]
Check an access of a client request: raise a ModbusException to refuse it (default: allowed).
- class pyModbusTCP.server.ReadOnly(store: DataStore, spaces: Iterable[Space] | None = None)[source]
Bases:
StoreWrapperRefuse the client writes (“illegal function” exception), in every space or in some of them.
- Parameters:
store – the wrapped store
spaces – the read-only spaces (default: every space)
- class pyModbusTCP.server.AccessControl(store: DataStore, read_hosts: Iterable[str] | None = None, write_hosts: Iterable[str] | None = None)[source]
Bases:
StoreWrapperAllow the reads and the writes only to some client addresses or networks (“illegal function” exception).
This filters on the source IP address, it’s not an authentication.
- Parameters:
store – the wrapped store
read_hosts – IP addresses or networks allowed to read (like [‘192.168.1.0/24’]), None for every client, an empty list for no client
write_hosts – IP addresses or networks allowed to write, None for every client, an empty list for no client
- class pyModbusTCP.server.Guard(store: DataStore, check: Callable[[RequestContext, Literal['read', 'write'], Space, int, int], bool])[source]
Bases:
StoreWrapperCheck each client access with a function: check(ctx, access, space, address, count).
The function returns True to allow the access, False to refuse it (“illegal data address” exception), or raises a ModbusException for another exception code.
Function handlers
- class pyModbusTCP.server.Request(pdu: bytes, ctx: RequestContext, store: DataStore, device_id: DeviceIdentification | None = None)[source]
A request given to a function handler.
- property function_code: int
The function code of the request (the first byte of the PDU).
- unpack(fmt: str, from_byte: int | None = None, to_byte: int | None = None) tuple[Any, ...][source]
Decode a part of the PDU with struct.
- Parameters:
fmt – struct format; its byte order prefix is used as is (‘<’ for little endian data…), a format without prefix is big endian (the byte order of Modbus), not the native order of struct
- Raises:
PDUDecodeError – if this part is too short (the client gets an “illegal data value” exception)
- reply(fmt: str = '', *args: Any) bytes[source]
Build a response PDU: the function code of the request, then args packed with struct.
- Parameters:
fmt – struct format of the fields after the function code; its byte order prefix is used as is (‘<’ for little endian data…), a format without prefix is big endian (the byte order of Modbus), not the native order of struct
- Raises:
DataFormatError – if a value doesn’t fit its field (the client gets a “slave device failure”)
- transaction() AbstractContextManager[Transaction][source]
A transaction of the store, with the context of this request.
- pyModbusTCP.server.FunctionHandler
The type of a function handler:
Callable[[Request], bytes], it returns the response PDU (the function code first) and raises aModbusExceptionfor an exception response.
- pyModbusTCP.server.STANDARD_FUNCTIONS
The handlers of the standard functions, by function code (0x01 to 0x06, 0x0F, 0x10, 0x17 and 0x2B/0x0E). A copy is the default of
ModbusServer.functions.
DeviceIdentification
- class pyModbusTCP.server.DeviceIdentification(vendor_name: bytes = b'', product_code: bytes = b'', major_minor_revision: bytes = b'', vendor_url: bytes = b'', product_name: bytes = b'', model_name: bytes = b'', user_application_name: bytes = b'', objects_by_id: dict[int, bytes] | None = None, objects_id: dict[int, bytes] | None = None)[source]
Container class for device identification objects (MEI type 0x0E) return by function 0x2B.
Constructor
- Parameters:
vendor_name (bytes) – VendorName mandatory object
product_code (bytes) – ProductCode mandatory object
major_minor_revision (bytes) – MajorMinorRevision mandatory object
vendor_url (bytes) – VendorUrl regular object
product_name (bytes) – ProductName regular object
model_name (bytes) – ModelName regular object
user_application_name (bytes) – UserApplicationName regular object
objects_by_id (dict) – Objects values by id as dict example: {42:b’value’} (optional), the name of the client side (DeviceIdentificationResponse.objects_by_id)
objects_id (dict) – deprecated name of objects_by_id (DeprecationWarning)
- property conformity_level: int
The conformity level of the read device identification response: the categories of the published objects.
0x81 basic (objects 0x00 to 0x02), 0x82 regular (an object of 0x03 to 0x7F), 0x83 extended (an object of 0x80 to 0xFF); the flag 0x80: the server supports the individual access (read code 4) as well as the stream access. The objects 0x03 to 0x06 always exist (empty by default): the level is at least 0x82.
Modbus exceptions
Raise them from a store, a wrapper, a mapped range or a function handler: the client gets the exception response, its session goes on.
- class pyModbusTCP.server.ModbusException(message: str = '', code: int | None = None)[source]
A Modbus exception response: the server answers the request with this exception code.
Use a subclass (IllegalDataAddress…) for the standard codes, or this class with any code (1 to 255). A subclass of the application sets its code as a class attribute (code = 0x80), checked at its definition (ValueError).
- class pyModbusTCP.server.IllegalFunction(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x01: the function is not supported, or not allowed (like a write on a read-only server).
- class pyModbusTCP.server.IllegalDataAddress(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x02: an address of the request is out of the data space (or not allowed).
- class pyModbusTCP.server.IllegalDataValue(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x03: a value of the request is not accepted.
- class pyModbusTCP.server.SlaveDeviceFailure(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x04: the server failed to process a valid request.
- class pyModbusTCP.server.SlaveDeviceBusy(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x06: the server is busy, the client should retry later.
Bases:
ModbusExceptionException 0x0A: a gateway can’t route the request (like an unknown unit id).
- class pyModbusTCP.server.GatewayTargetFailed(message: str = '', code: int | None = None)[source]
Bases:
ModbusExceptionException 0x0B: the target device behind a gateway didn’t answer.
Errors of the server
The errors of the server are also available as attributes of ModbusServer (like
ModbusServer.NetworkError).
- class pyModbusTCP.server.errors.Error[source]
Bases:
ExceptionBase exception for ModbusServer related errors.
- class pyModbusTCP.server.errors.NetworkError[source]
Bases:
ErrorException raised by ModbusServer on I/O errors.
- class pyModbusTCP.server.errors.DataFormatError[source]
Bases:
ErrorException raised by ModbusServer for data format errors.
- class pyModbusTCP.server.errors.PDUDecodeError[source]
Bases:
DataFormatErrorException raised when a received request PDU can’t be decoded (too short…).