""" pyModbusTCP server: the data store, where the server reads and writes the Modbus data.
Every request of a client runs in a transaction of the store::
with store.transaction(ctx) as tx:
tx.write(Space.HOLDING_REGISTERS, 10, [1, 2])
values = tx.read(Space.HOLDING_REGISTERS, 0, 4)
A transaction is atomic: no other request (or application access) can run during it, and if an exception is raised
inside it, every value it wrote is restored. The changes are notified to the listeners (see DataStore.subscribe())
once the transaction is committed.
The application accesses the store with store.app (no request context): store.app.holding_registers.write(0, [1]).
"""
from __future__ import annotations
import itertools
import logging
import operator
import queue
import threading
from abc import ABC, abstractmethod
from collections.abc import Callable, Generator, Iterable, Sequence
from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, NamedTuple
from ..codec import ByteOrder, ByteOrder64, Codec, DataType, Number
from ..utils import _to_bool_list, _to_int_list
from ._common import LogThrottle, logger
from .errors import IllegalDataAddress, SlaveDeviceFailure
from .session import ClientInfo
[docs]
class Space(Enum):
"""The 4 Modbus data spaces."""
COILS = 'coils'
DISCRETE_INPUTS = 'discrete_inputs'
HOLDING_REGISTERS = 'holding_registers'
INPUT_REGISTERS = 'input_registers'
@property
def is_bit(self) -> bool:
"""True for the spaces of bits (coils and discrete inputs), False for the spaces of 16 bits registers."""
return self in (Space.COILS, Space.DISCRETE_INPUTS)
[docs]
def check_values(self, values: Iterable[Any]) -> list[Any]:
"""Return values as a list of bool (space of bits) or of 16 bits int (space of registers).
:raises TypeError: if an item is not a bool/int (str, float...)
:raises ValueError: if a register value is out of the 0 to 65535 range
"""
if self.is_bit:
return _to_bool_list(values, 'values')
words = _to_int_list(values, 'values')
if words and (min(words) < 0 or max(words) > 0xFFFF):
raise ValueError('a register value must be between 0 and 65535')
return words
[docs]
@dataclass(frozen=True)
class RequestContext:
"""Where a request comes from: given to the transactions, the store wrappers and the change listeners.
The application accesses the store without context (None).
"""
client: ClientInfo = field(default_factory=ClientInfo)
unit_id: int = 0
function_code: int = 0
[docs]
class Change(NamedTuple):
"""A value changed by a transaction."""
space: Space
address: int
old: Any
new: Any
[docs]
class WrittenRange(NamedTuple):
"""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.
"""
space: Space
address: int
old: tuple[Any, ...]
new: tuple[Any, ...]
[docs]
def count_changed(self) -> int:
"""The number of values of the range that changed (computed at C speed)."""
return sum(map(operator.ne, self.old, self.new))
[docs]
class ChangeEvent:
"""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.
"""
__slots__ = ('_changes', 'ctx', 'writes')
def __init__(self, ctx: RequestContext | None, changes: Iterable[Change] | None = None, *,
writes: Iterable[WrittenRange] = ()) -> None:
"""
:param ctx: the context of the client request, None for the application
:param changes: the changes value by value (default: computed from writes when they are read)
:param writes: the ranges written, in the order of the transaction
"""
self.ctx = ctx
self.writes: tuple[WrittenRange, ...] = tuple(writes)
self._changes: tuple[Change, ...] | None = None if changes is None else tuple(changes)
def __repr__(self) -> str:
return f'ChangeEvent(ctx={self.ctx!r}, changes={self.changes!r})'
@property
def by_client(self) -> bool:
"""True for the changes of a client request, False for an application write."""
return self.ctx is not None
@property
def changes(self) -> 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."""
if self._changes is None and len(self.writes) == 1:
# the usual case (every standard function): one range, each address once, the changed ones found at C speed
space, address, olds, news = self.writes[0]
self._changes = tuple(Change(space, address + i, olds[i], news[i])
for i in itertools.compress(range(len(news)), map(operator.ne, olds, news)))
if self._changes is None:
first_last: dict[tuple[Space, int], list[Any]] = {}
for space, address, olds, news in self.writes:
for i, (old, new) in enumerate(zip(olds, news, strict=True)):
entry = first_last.get((space, address + i))
if entry is not None:
entry[1] = new
elif old != new:
first_last[(space, address + i)] = [old, new]
# (a race of two threads computes it twice, with the same result)
self._changes = tuple(Change(space, address, old, new)
for (space, address), (old, new) in first_last.items() if old != new)
return self._changes
@property
def size(self) -> int:
"""The number of values that the event holds (written values, or changes): its weight in memory."""
if self.writes:
return sum(len(written.new) for written in self.writes)
return len(self.changes)
[docs]
def of(self, space: Space) -> tuple[Change, ...]:
"""The changes in a data space."""
return tuple(change for change in self.changes if change.space is space)
# a listener of the changes, see DataStore.subscribe()
Listener = Callable[[ChangeEvent], None]
[docs]
class Transaction(ABC):
"""The access to the data during a transaction (see DataStore.transaction())."""
ctx: RequestContext | None
[docs]
@abstractmethod
def read(self, space: Space, address: int, count: int = 1) -> list[Any]:
"""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
"""
[docs]
@abstractmethod
def write(self, space: Space, address: int, values: Iterable[Any]) -> None:
"""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
:raises TypeError, ValueError: for an invalid value (see Space.check_values())
"""
[docs]
class DataStore(ABC):
"""Where the server reads and writes the Modbus data: the base class of every store and store wrapper."""
[docs]
@abstractmethod
def transaction(self, ctx: RequestContext | None = None) -> AbstractContextManager[Transaction]:
"""Return a context manager that runs an atomic transaction (it gives a Transaction object).
:param ctx: the context of a client request, None for the application
"""
[docs]
@abstractmethod
def subscribe(self, listener: Listener, app_writes: bool = False, threaded: bool = False) -> Callable[[], None]:
"""Call listener with a ChangeEvent after each transaction that changed some values.
:param listener: a function called with the ChangeEvent (its exceptions are logged)
:param app_writes: also notify the writes of the application (by default, only the client requests)
:param 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
"""
@property
def app(self) -> AppAccess:
"""The access of the application to the data (no client context, the wrappers don't apply)."""
return AppAccess(self)
# --- the in-memory store ---
@dataclass
class _Mapping:
"""A range of addresses whose values are computed (see MemoryStore.map())."""
start: int
count: int
read: Callable[[int, int, RequestContext | None], Sequence[Any]]
write: Callable[[int, list[Any], RequestContext | None], None] | None
@property
def end(self) -> int:
return self.start + self.count
@dataclass
class _ListenerEntry:
listener: Listener
app_writes: bool
threaded: bool
class _MemoryTransaction(Transaction):
"""A transaction of a MemoryStore: runs with the lock of the store, keeps a journal to roll back."""
def __init__(self, store: MemoryStore, ctx: RequestContext | None) -> None:
self.ctx = ctx
self._store = store
# journal of the memory writes (space, address, previous values, new values): restores the previous values
# on an exception, gives the ranges written to the listeners once committed (see ChangeEvent)
self._journal: list[tuple[Space, int, list[Any], list[Any]]] = []
def read(self, space: Space, address: int, count: int = 1) -> list[Any]:
values: list[Any] = []
memory, start = self._store._data[space], self._store._start[space]
for mapping, seg_address, seg_count in self._store._segments(space, address, count):
if mapping is None:
index = seg_address - start
values.extend(memory[index:index + seg_count])
else:
values.extend(self._mapped_read(space, mapping, seg_address, seg_count))
return values
def _mapped_read(self, space: Space, mapping: _Mapping, address: int, count: int) -> list[Any]:
"""Call the read function of a mapping, check what it returns (a slave device failure if it's invalid)."""
try:
values = space.check_values(mapping.read(address, count, self.ctx))
except (TypeError, ValueError) as e:
logger.error('Mapped read of %s @%d returned an invalid value: %s', space.value, address, e)
raise SlaveDeviceFailure() from e
if len(values) != count:
logger.error('Mapped read of %s @%d returned %d value(s), %d expected', space.value, address,
len(values), count)
raise SlaveDeviceFailure()
return values
def write(self, space: Space, address: int, values: Iterable[Any]) -> None:
values = space.check_values(values)
if not values:
return
# checked first: nothing is written if a part of the range is invalid
segments = self._store._segments(space, address, len(values))
for mapping, _, _ in segments:
if mapping is not None and mapping.write is None:
raise IllegalDataAddress()
memory, start = self._store._data[space], self._store._start[space]
offset = 0
for mapping, seg_address, seg_count in segments:
seg_values = values[offset:offset + seg_count]
offset += seg_count
if mapping is not None:
assert mapping.write is not None
mapping.write(seg_address, seg_values, self.ctx)
continue
# the journal and the events give the Modbus addresses, the memory list starts at the first one
index = seg_address - start
old_values = memory[index:index + seg_count]
# compare the whole slice at C speed: skip everything if nothing changes
if old_values == seg_values:
continue
# (no comparison value by value here: done by ChangeEvent.changes, only if a listener reads it)
self._journal.append((space, seg_address, old_values, seg_values))
memory[index:index + seg_count] = seg_values
def _rollback(self) -> None:
for space, address, old_values, _ in reversed(self._journal):
index = address - self._store._start[space]
self._store._data[space][index:index + len(old_values)] = old_values
self._journal.clear()
def _committed_event(self) -> ChangeEvent | None:
"""The change event of the committed transaction, None if it changed nothing."""
if not self._journal:
return None
event = ChangeEvent(self.ctx, writes=(WrittenRange(space, address, tuple(old), tuple(new))
for space, address, old, new in self._journal))
# a range is only journaled if it changes something: with a single range (every standard function), the
# event has a change. With several, they may cancel out (a value written back): checked here, rarely
if len(self._journal) > 1 and not event.changes:
return None
return event
def _checked_size(value: object, name: str) -> int:
"""A number of addresses: an int from 0 to 65536."""
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0x10000:
raise ValueError(f'{name} must be an int between 0 and 65536 (or a range of addresses)')
return value
def _checked_addresses(value: object, space: Space) -> range:
"""The addresses of a space: a number of addresses from 0 (int), or a range of addresses in 0 to 65535."""
if isinstance(value, range):
if value.step != 1 or not 0 <= value.start <= value.stop <= 0x10000:
raise ValueError(f'the range of {space.value} must be a range of addresses in 0 to 65535, with a step '
f'of 1, not {value!r}')
return value
return range(_checked_size(value, f'the size of {space.value}'))
[docs]
class MemoryStore(DataStore):
"""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.
"""
#: 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_size: int = 10_000
#: 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
notify_queue_values: int = 200_000
def __init__(self, size: int = 0x10000, *, 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) -> None:
"""Constructor
:param size: number of addresses of each space, from 0 (default 65536, 0 for a store with mapped ranges only)
:param 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)
:param discrete_inputs: the discrete inputs, if different from size (a number or a range, like coils)
:param holding_registers: the holding registers, if different from size (a number or a range, like coils)
:param input_registers: the input registers, if different from size (a number or a range, like coils)
:param default_bit: startup value of the coils and the discrete inputs (default False)
:param default_word: startup value of the registers (default 0)
"""
sizes = {Space.COILS: coils, Space.DISCRETE_INPUTS: discrete_inputs,
Space.HOLDING_REGISTERS: holding_registers, Space.INPUT_REGISTERS: input_registers}
default_word = Space.HOLDING_REGISTERS.check_values([default_word])[0]
self._data: dict[Space, list[Any]] = {}
# the address of the first value of each space in memory (self._data[space][0])
self._start: dict[Space, int] = {}
for space, addresses in sizes.items():
if addresses is None:
addresses = range(_checked_size(size, 'size'))
else:
addresses = _checked_addresses(addresses, space)
self._start[space] = addresses.start
self._data[space] = [bool(default_bit) if space.is_bit else default_word] * len(addresses)
self._maps: dict[Space, list[_Mapping]] = {space: [] for space in Space}
self._lock = threading.Lock()
# the transaction in progress in the current thread (a nested transaction joins it)
self._local = threading.local()
self._listeners: list[_ListenerEntry] = []
self._listeners_lock = threading.Lock()
self._notify_queue: queue.Queue[tuple[Listener, ChangeEvent]] | None = None
# number of values in the events of the queue (see notify_queue_values), and its lock
self._queued_values = 0
self._queued_values_lock = threading.Lock()
# dropped events: the first one is logged at once, then one message per 10 s at most
self._dropped_log = LogThrottle(logger)
# errors of the listeners (called on each write of a client): one message per 10 s at most
self._listener_error_log = LogThrottle(logger, level=logging.ERROR)
def __repr__(self) -> str:
# a space from 0 by its size, another one by its range of addresses (like the constructor arguments)
spaces = ', '.join(f'{space.value}={self.addresses(space) if self._start[space] else self.size(space)}'
for space in Space)
return f'MemoryStore({spaces})'
[docs]
def size(self, space: Space) -> int:
"""The number of addresses of a space in memory (the mapped ranges are not counted)."""
return len(self._data[space])
[docs]
def addresses(self, space: Space) -> range:
"""The addresses of a space in memory, like range(0, 65536) (the mapped ranges are not counted)."""
start = self._start[space]
return range(start, start + len(self._data[space]))
# transactions
[docs]
@contextmanager
def transaction(self, ctx: RequestContext | None = None) -> Generator[Transaction, None, None]:
current: _MemoryTransaction | None = getattr(self._local, 'tx', None)
if current is not None:
# nested in the same thread (like a mapped function that uses the store): part of the same transaction
yield current
return
event: ChangeEvent | None = None
sync_listeners: list[_ListenerEntry] = []
with self._lock:
tx = _MemoryTransaction(self, ctx)
self._local.tx = tx
try:
yield tx
except BaseException:
tx._rollback()
raise
finally:
self._local.tx = None
# committed; no listener (the usual case): no event at all. The threaded listeners get the event now,
# with the lock: their queue has the events in the order of the commits (queued after the lock, a
# transaction committed later could pass it)
if self._listeners:
event = tx._committed_event()
if event is not None:
sync_listeners = self._notify_threaded(event)
# the other listeners: in this thread, without the lock (they can use the store)
if event is not None:
for entry in sync_listeners:
_call_listener(entry.listener, event, self._listener_error_log)
def _segments(self, space: Space, address: int, count: int) -> list[tuple[_Mapping | None, int, int]]:
"""Split a range in memory and mapped parts: [(mapping or None, address, count), ...].
:raises IllegalDataAddress: if a part of the range is neither in memory nor mapped
"""
if address < 0 or count < 0 or address + count > 0x10000:
raise IllegalDataAddress()
memory_start = self._start[space]
memory_end = memory_start + len(self._data[space])
maps = self._maps[space]
# usual case: no mapped range in this space
if not maps:
if address < memory_start or address + count > memory_end:
raise IllegalDataAddress()
return [(None, address, count)]
segments: list[tuple[_Mapping | None, int, int]] = []
current, end = address, address + count
while current < end:
mapping = next((m for m in maps if m.start <= current < m.end), None)
if mapping is not None:
seg_end = min(end, mapping.end)
else:
if not memory_start <= current < memory_end:
raise IllegalDataAddress()
# memory, until the end of the memory or the next mapped range
next_start = min((m.start for m in maps if m.start > current), default=end)
seg_end = min(end, memory_end, next_start)
segments.append((mapping, current, seg_end - current))
current = seg_end
return segments
# computed values
[docs]
def map(self, 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:
"""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).
:param space: the data space
:param address: first address of the range
:param count: number of addresses
:param read: read(address, count, ctx) returns the count values from address (ctx is None for the
application)
:param 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
"""
if address < 0 or count < 1 or address + count > 0x10000:
raise ValueError('a mapped range must be in the 0 to 65535 address range')
new = _Mapping(address, count, read, write)
with self._lock:
if any(m.start < new.end and new.start < m.end for m in self._maps[space]):
raise ValueError('a mapped range must not overlap another one')
self._maps[space].append(new)
self._maps[space].sort(key=lambda m: m.start)
# notifications
[docs]
def subscribe(self, listener: Listener, app_writes: bool = False, threaded: bool = False) -> Callable[[], None]:
entry = _ListenerEntry(listener, app_writes, threaded)
with self._listeners_lock:
self._listeners.append(entry)
if threaded and self._notify_queue is None:
self._notify_queue = queue.Queue(maxsize=self.notify_queue_size)
threading.Thread(target=self._notify_loop, args=(self._notify_queue,), daemon=True,
name='MemoryStore notifications').start()
def unsubscribe() -> None:
with self._listeners_lock:
if entry in self._listeners:
self._listeners.remove(entry)
return unsubscribe
[docs]
def join_notifications(self) -> None:
"""Wait until the threaded listeners have processed every change event (useful in tests)."""
notify_queue = self._notify_queue
if notify_queue is not None:
notify_queue.join()
def _notify_threaded(self, event: ChangeEvent) -> list[_ListenerEntry]:
"""Queue the event for the threaded listeners (called with the lock of the store, never blocks).
:returns: the other listeners of the event, to call in the thread of the transaction, without the lock
"""
with self._listeners_lock:
entries = list(self._listeners)
sync_listeners: list[_ListenerEntry] = []
for entry in entries:
if not event.by_client and not entry.app_writes:
continue
if entry.threaded and self._notify_queue is not None:
if not self._enqueue(self._notify_queue, entry.listener, event):
# never block the client: the listener is too slow, this event is lost
self._dropped_log.event('Threaded listener too slow: %(count)d change event(s) dropped (queue '
'full: %(events)d events or %(values)d values at most)',
events=self.notify_queue_size, values=self.notify_queue_values)
else:
sync_listeners.append(entry)
return sync_listeners
def _enqueue(self, notify_queue: queue.Queue[tuple[Listener, ChangeEvent]], listener: Listener,
event: ChangeEvent) -> bool:
"""Queue an event for a threaded listener, False if the queue is full (in events or in values)."""
size = event.size
with self._queued_values_lock:
# an event larger than the limit alone: only when nothing else waits (else it could never be delivered)
if self._queued_values and self._queued_values + size > self.notify_queue_values:
return False
try:
notify_queue.put_nowait((listener, event))
except queue.Full:
return False
self._queued_values += size
return True
def _notify_loop(self, notify_queue: queue.Queue[tuple[Listener, ChangeEvent]]) -> None:
# this thread serves every threaded listener of the store, for the life of the store: it never ends on an
# error of one of them. _call_listener() logs an Exception; a BaseException (like a sys.exit() in a listener)
# ended the thread, without a log of the store: the next events of every threaded listener were never
# delivered (once the queue full, dropped), and join_notifications() never returned
while True:
listener, event = notify_queue.get()
try:
_call_listener(listener, event, self._listener_error_log)
except BaseException: # noqa: BLE001
self._listener_error_log.event('Error in a change listener: %(count)d error(s) (last: %(listener)r)',
listener=listener, exc_info=True)
finally:
with self._queued_values_lock:
self._queued_values -= event.size
notify_queue.task_done()
def _call_listener(listener: Listener, event: ChangeEvent, error_log: LogThrottle) -> None:
"""Call a listener: the transaction is committed, an error of the listener can't change it, it's logged."""
try:
listener(event)
except Exception: # noqa: BLE001
error_log.event('Error in a change listener: %(count)d error(s) (last: %(listener)r)', listener=listener,
exc_info=True)
# --- the access of the application ---
[docs]
class SpaceAccess:
"""The access of the application to one data space: store.app.coils, store.app.holding_registers..."""
def __init__(self, store: DataStore, space: Space) -> None:
self.store = store
self.space = space
def __repr__(self) -> str:
return f'{type(self).__name__}({self.space.value})'
[docs]
def read(self, address: int, count: int = 1) -> list[Any]:
"""Read count values from address.
:raises IllegalDataAddress: if the range is out of the space
"""
with self.store.transaction() as tx:
return list(tx.read(self.space, address, count))
[docs]
def write(self, address: int, values: Iterable[Any]) -> None:
"""Write values from address (all or nothing).
:raises IllegalDataAddress: if the range is out of the space
:raises TypeError, ValueError: for an invalid value (a register is a 16 bits unsigned int)
"""
with self.store.transaction() as tx:
tx.write(self.space, address, values)
[docs]
class RegistersAccess(SpaceAccess):
"""The 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 :class:`~pyModbusTCP.codec.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 a :class:`~pyModbusTCP.codec.ByteOrder` (default ``ABCD``: the first
register holds the most significant word). The 64 bits shortcuts also take a
:class:`~pyModbusTCP.codec.ByteOrder64`, for the rare orders of 8 bytes; the 32 bits ones refuse it (ValueError).
"""
[docs]
def read_values(self, address: int, codec: Codec, count: int = 1) -> list[Number]:
"""Read count values of the type of codec (count * codec.words registers from address).
:raises IllegalDataAddress: if a register is out of the space
"""
return codec.decode(self.read(address, count * codec.words))
[docs]
def write_values(self, address: int, values: Sequence[Number], codec: Codec) -> None:
"""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)
:raises IllegalDataAddress: if a register is out of the space
"""
self.write(address, codec.encode(values))
[docs]
def read_uint16(self, address: int) -> int:
"""Read an unsigned 16 bits int on 1 register (like read(address)[0])."""
return int(self.read_values(address, _UINT16)[0])
[docs]
def write_uint16(self, address: int, value: int) -> None:
"""Write an unsigned 16 bits int on 1 register (ValueError out of 0 to 65535)."""
self.write_values(address, [value], _UINT16)
[docs]
def read_int16(self, address: int) -> int:
"""Read a signed 16 bits int (2's complement) on 1 register."""
return int(self.read_values(address, _INT16)[0])
[docs]
def write_int16(self, address: int, value: int) -> None:
"""Write a signed 16 bits int (2's complement) on 1 register (ValueError out of -32768 to 32767)."""
self.write_values(address, [value], _INT16)
[docs]
def read_uint32(self, address: int, byte_order: ByteOrder = ByteOrder.ABCD) -> int:
"""Read an unsigned 32 bits int on 2 registers."""
return int(self.read_values(address, Codec(DataType.UINT32, byte_order))[0])
[docs]
def write_uint32(self, address: int, value: int, byte_order: ByteOrder = ByteOrder.ABCD) -> None:
"""Write an unsigned 32 bits int on 2 registers (ValueError out of 0 to 2**32 - 1)."""
self.write_values(address, [value], Codec(DataType.UINT32, byte_order))
[docs]
def read_int32(self, address: int, byte_order: ByteOrder = ByteOrder.ABCD) -> int:
"""Read a signed 32 bits int (2's complement) on 2 registers."""
return int(self.read_values(address, Codec(DataType.INT32, byte_order))[0])
[docs]
def write_int32(self, address: int, value: int, byte_order: ByteOrder = ByteOrder.ABCD) -> None:
"""Write a signed 32 bits int (2's complement) on 2 registers (ValueError out of -2**31 to 2**31 - 1)."""
self.write_values(address, [value], Codec(DataType.INT32, byte_order))
[docs]
def read_float32(self, address: int, byte_order: ByteOrder = ByteOrder.ABCD) -> float:
"""Read an IEEE 754 single precision float on 2 registers."""
return float(self.read_values(address, Codec(DataType.FLOAT32, byte_order))[0])
[docs]
def write_float32(self, address: int, value: float, byte_order: ByteOrder = ByteOrder.ABCD) -> None:
"""Write an IEEE 754 single precision float on 2 registers."""
self.write_values(address, [value], Codec(DataType.FLOAT32, byte_order))
[docs]
def read_uint64(self, address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> int:
"""Read an unsigned 64 bits int on 4 registers."""
return int(self.read_values(address, Codec(DataType.UINT64, byte_order))[0])
[docs]
def write_uint64(self, address: int, value: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> None:
"""Write an unsigned 64 bits int on 4 registers (ValueError out of 0 to 2**64 - 1)."""
self.write_values(address, [value], Codec(DataType.UINT64, byte_order))
[docs]
def read_int64(self, address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> int:
"""Read a signed 64 bits int (2's complement) on 4 registers."""
return int(self.read_values(address, Codec(DataType.INT64, byte_order))[0])
[docs]
def write_int64(self, address: int, value: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> None:
"""Write a signed 64 bits int (2's complement) on 4 registers (ValueError out of -2**63 to 2**63 - 1)."""
self.write_values(address, [value], Codec(DataType.INT64, byte_order))
[docs]
def read_float64(self, address: int, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> float:
"""Read an IEEE 754 double precision float on 4 registers."""
return float(self.read_values(address, Codec(DataType.FLOAT64, byte_order))[0])
[docs]
def write_float64(self, address: int, value: float, byte_order: ByteOrder | ByteOrder64 = ByteOrder.ABCD) -> None:
"""Write an IEEE 754 double precision float on 4 registers."""
self.write_values(address, [value], Codec(DataType.FLOAT64, byte_order))
# a 16 bits value is on 1 register: no word order (a byte swapped register: read_values() with a Codec)
_UINT16 = Codec(DataType.UINT16)
_INT16 = Codec(DataType.INT16)
[docs]
class AppAccess:
"""The access of the application to a store (store.app): no client context, the wrappers don't apply."""
def __init__(self, store: DataStore) -> None:
self.store = store
self.coils = SpaceAccess(store, Space.COILS)
self.discrete_inputs = SpaceAccess(store, Space.DISCRETE_INPUTS)
self.holding_registers = RegistersAccess(store, Space.HOLDING_REGISTERS)
self.input_registers = RegistersAccess(store, Space.INPUT_REGISTERS)
[docs]
def transaction(self) -> AbstractContextManager[Transaction]:
"""An atomic transaction of the application, to change several values (of several spaces) at once."""
return self.store.transaction(None)
[docs]
def read(self, space: Space, address: int, count: int = 1) -> list[Any]:
"""Read count values of a space from address."""
return SpaceAccess(self.store, space).read(address, count)
[docs]
def write(self, space: Space, address: int, values: Iterable[Any]) -> None:
"""Write values in a space from address."""
SpaceAccess(self.store, space).write(address, values)