Modbus Event Connect
Read and write devices over Modbus and micro_nabto in Python, and be told when a value
changes.
A device is described once, as a model. The library then takes care of the rest:
- reading only what is needed, as often as it is needed, in as few requests as possible
- telling you when a value changes
- checking a value before it is written
- retrying and recovering when the device is busy or goes away
- saying how trustworthy every value is, so "offline", "no reading" and a real value never
look alike
Which part is for you
| You are... |
Read |
| Building an application for a device that already has a model |
Part 1: Using a device |
| Describing a new device: its registers, units and settings |
Part 2: Describing a device |
| Working on the library itself |
docs/design.md |
pip install modbus-event-connect
How the pieces fit
Model what the device is and how it is talked to: ModbusModel or (Part 2)
MicroNabtoModel - its points, how to decode them, its timing
Device where it is: ModbusDevice or MicroNabtoDevice, given the models (Part 1)
Client joins them: connect, subscribe, run, write (Part 1)
A model is locked to one protocol and says everything about how its unit behaves on it, read top
to bottom in one file. A device library keeps each model in a file of its own and lists the
models once; its create_client writes out what is needed before the model is known. An
application only says where the device is.
A point is one value the device has, such as a temperature or a setting. Its key,
Key("temperature", float), names it everywhere and says what its value is. A key is its text
wherever it is stored, and a type checker knows from it what reading the point gives and what
writing it takes.
Keys, values, points by their behaviour, the scheduling of reads and what a write or a change
sets off are those of event_connect, the
protocol-free core this library is built on; they are imported from here under the same names.
Everything is imported from four places. The modules inside them are internal, and may change in
any release.
| Import from |
For |
modbus_event_connect |
the client, values, errors, and what a model is made of |
modbus_event_connect.modbus |
Modbus: the connection, the device, register kinds and numbering |
modbus_event_connect.micro_nabto |
micro_nabto: discovery, the session, the device, register kinds |
modbus_event_connect.testing |
testing a model: simulated devices, a fake clock, the model walker |
Part 1: Using a device
A complete program
import asyncio
from my_devices import TARGET, TEMPERATURE, create_client # see Part 2
def on_change(key, old, new):
print(f"{key}: {new.value} ({new.quality.name})")
async def main():
client = create_client(host="<device-ip>", unit_id=1)
await client.connect() # reads every point once
client.subscribe(TEMPERATURE, on_change)
await client.write(TARGET, 21.5)
polling = asyncio.create_task(client.run()) # reads whatever is due, until cancelled
try:
await asyncio.sleep(3600)
finally:
polling.cancel()
await client.disconnect()
asyncio.run(main())
run() reads whatever is due, whenever it is due, until it is cancelled - it never ends by
itself - and is woken when a subscription, a refresh or a write makes something due sooner. While
the client is not connected - before connect(), or after disconnect() - it waits until it is.
A poll that raises is logged, the first of a run of failures as an error with its traceback, and
polling goes on after a pause. It waits on the client's clock, as every pause the client makes
does: a test that gives the client a FakeClock moves it on with clock.advance().
A program with its own loop calls poll() instead, which reads the points that are due. A call
when nothing is due returns at once without contacting the device; seconds_until_next_poll()
says how long until something is.
Connecting
A device library's create_client does this for you. Building one by hand, every value is
written out; none has a default but a protocol's own facts, such as its port:
from modbus_event_connect import CircuitBreaker, Exponential, Fixed, Retry
from modbus_event_connect.modbus import ModbusDevice, ModbusTcpConnection
from modbus_event_connect.micro_nabto import MicroNabtoDevice
import my_blinds, my_heating, my_devices, my_ventilation # each lists its models
# Modbus TCP, one device; once 3 requests in a row went unanswered, asked again 2, 4 and 8 s
# later, then every 10 s. A request waits as long as the model says its unit answers within,
# and timeout_margin more, for the network.
device = ModbusDevice.tcp("<device-ip>", unit_id=1, models=my_devices.MODELS, timeout_margin=2.5,
connect_timeout=3.0, frame_gap=0.0,
reconnect=CircuitBreaker(after=3, retry=Retry(Exponential(2.0, factor=2.0, max=10.0), None)))
# Several Modbus devices behind one gateway, sharing its connection, each with its own breaker
gateway = ModbusTcpConnection("<gateway-ip>", connect_timeout=3.0, frame_gap=0.0)
slowly = CircuitBreaker(after=3, retry=Retry(Exponential(10.0, factor=2.0, max=120.0), None))
heating = ModbusDevice(gateway, 1, reconnect=slowly, models=my_heating.MODELS, timeout_margin=2.5)
blinds = ModbusDevice(gateway, 3, reconnect=slowly, models=my_blinds.MODELS, timeout_margin=2.5)
# micro_nabto; with device_id, the device is found again if its address changes
ventilation = MicroNabtoDevice.udp("<email-paired-with-the-device>", host="<device-ip>",
device_id="<device-id>", models=my_ventilation.MODELS,
timeout=1.0, retries=2, session_idle=12.0, rediscovery_timeout=3.0,
rediscovery_resend=0.5, answer_wait=5.0,
reconnect=CircuitBreaker(after=1, retry=Retry(Fixed(5.0), None)))
Behind a gateway, a device that stops answering does not slow down the others, and each request
waits as long as its own unit needs.
A device is given every model it may turn out to be, of its own protocol only: a type checker
refuses a MicroNabtoModel given to a ModbusDevice. Once the client has chosen the model, it
tells the device with use(model), and the device talks to it as that model says. Until then it
asks as cautiously as any of its models needs: the fewest registers in one read, the longest
wait for an answer. A model the device was not given raises ModelError, and so does one given
twice.
A micro_nabto device says what it is when you connect. Give the client a function instead of a
model, and it picks one of the device's models from that:
def pick_model(identity):
return VENTILATION if identity["device_model"] == 1140 else None
client = Client(ventilation, pick_model, offline_after_intervals=1, level=Level.DOCUMENTED)
offline_after_intervals is how many reads of the chosen model's fastest poll rate the device
may leave unanswered before it counts as not answering; see
Connection state. level is which of the model's points the client uses;
see Levels and candidates.
micro_nabto devices on the local network are found with discover, which writes out how long
it searches and how often it asks again: await discover(timeout=2.0, resend=0.5, target=BROADCAST). Each answer is a DiscoveredDevice with its device_id, host and port.
Once connected, client.model is the model chosen and client.identity what the device reported
about itself, with what the model's identity points read.
connect() raises when it cannot finish:
| Error |
Meaning |
CannotConnectError |
The device could not be reached, or did not answer every read. Try again later. |
AuthenticationError |
A micro_nabto device refused the email. Ask the user to check it. |
UnsupportedDeviceError |
The device answered, but no model matches it. Its identity is what the device reported. |
Reading values
client.subscribe(key, callback) calls callback(key, old, new) at once with the current
value, then on every change. old is None the first time. It returns a function that
unsubscribes.
client.value(key) gives the current value at any time, or None while the unit has none.
Its type follows the key: client.value(TEMPERATURE) is a DataValue[float], and a key of
another type than the model gives the point raises TypeError.
Every value is a DataValue with .value, .quality, .timestamp, and .raw: what the
device answered, before it was decoded.
| Quality |
Meaning |
Show it as |
GOOD |
A real value. |
the value |
NO_DATA |
The device says it has no reading, such as a sensor not fitted, or sent a number no state names. |
unknown |
STALE |
The last read failed. .value and .timestamp are the last good read's. |
the value, or unavailable |
OFFLINE |
Something behind the device is not answering. It will come back. |
unavailable |
MISSING |
This device does not have the value. |
leave it out |
How often values are read
Every point is read once when connecting. After that, a point is read on its poll rate -
FAST, MEDIUM, SLOW, RARE, or STATIC, once when connecting - while someone subscribes
to it. How many seconds each rate is, the model says, for its own unit; nothing outside the
model changes it.
To read now, call await client.refresh([TEMPERATURE]). refresh(PollRate.SLOW) reads a
whole poll rate, and refresh() reads everything. subscribe(key, callback, poll=False) is
told about changes without asking for the point to be read on a timer. A key no model of the
client has raises KeyError, before connect() too.
client.set_scheduled_polling(False) stops reading on the schedule - every poll rate, and the
checks for whether the unit has changed. poll() then reads only what refresh() and writes ask
for, and a read that finds a point gone still has its part of the unit checked.
set_scheduled_polling(True) reads at once what has become due meanwhile.
Riding out failures
How a device is asked again is assembled from standard parts that every protocol shares: waits
(Fixed, Exponential, Steps, Jitter), stops (Attempts, Within, combined with |),
Retry, which puts a wait and a stop together, and CircuitBreaker, which stops asking a device
that has left requests unanswered.
Reconnecting is stated by whoever creates the device, as reconnect, a CircuitBreaker, and
nowhere else: how soon a silent device should be asked again depends on how it is reached, not on
what it is. It has no default. The breaker opens once after requests in a row went unanswered -
for micro_nabto, handshakes - and the device is not asked until its retry lets a probe through;
asking again reopens a closed link, and an answer closes the breaker. connect() closes it too.
Before each probe, await retry.ready() is asked: a subclass of Retry can check something
first, and a probe it refuses keeps the breaker open as long again.
reconnect=CircuitBreaker(after=3, retry=...) |
Once 3 requests in a row went unanswered, asks again |
Retry(Exponential(2.0, factor=2.0, max=10.0), None) |
after 2, 4 and 8 s, then every 10 s |
Retry(Fixed(60.0), None) |
every minute |
Retry(Exponential(2.0, factor=2.0, max=10.0), Attempts(8)) |
as the first, and gives up at the eighth opening |
Retry(Steps(2.0, 5.0, then=Fixed(60.0)), Within(3600.0)) |
after 2 and 5 s, then every minute, for an hour |
NO_RETRY |
only on connect() |
What the model states is about its unit itself, and has no default either: