Skip to content

Commit ea2b2a7

Browse files
committed
Add curio based tcp client example
1 parent 20be348 commit ea2b2a7

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#!/usr/bin/env python
2+
# scripts/examples/simple_curio_tcp_client.py
3+
import curio
4+
5+
from umodbus import conf
6+
from umodbus.client import tcp
7+
from umodbus.client.tcp.asynch import send_message
8+
9+
10+
# Enable values to be signed (default is False).
11+
conf.SIGNED_VALUES = True
12+
13+
14+
class CurioStream:
15+
"""Adapter from curio socket to StreamReader/Writer"""
16+
17+
def __init__(self, sock):
18+
self.stream = sock.as_stream()
19+
self.data = None
20+
21+
def write(self, data):
22+
self._data = data
23+
24+
async def drain(self):
25+
if self._data:
26+
await self.stream.write(self._data)
27+
self._data = None
28+
29+
async def readexactly(self, n):
30+
return await self.stream.read_exactly(n)
31+
32+
33+
async def main():
34+
sock = await curio.open_connection('localhost', 502)
35+
stream = CurioStream(sock)
36+
37+
# Returns a message or Application Data Unit (ADU) specific for doing
38+
# Modbus TCP/IP.
39+
message = tcp.write_multiple_coils(slave_id=1, starting_address=1, values=[1, 0, 1, 1])
40+
41+
# Response depends on Modbus function code. This particular returns the
42+
# amount of coils written, in this case it is.
43+
response = await send_message(message, stream, stream)
44+
45+
await sock.close()
46+
47+
48+
curio.run(main)

0 commit comments

Comments
 (0)