Skip to content

Commit 44d4701

Browse files
Added Reading data in chunks (#72)
Adds an example of periodically reading data in chunks
1 parent 6abf007 commit 44d4701

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

documentation/shortintro.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,3 +87,43 @@ port asynchronously::
8787
loop.run_forever()
8888
loop.close()
8989

90+
Reading data in chunks
91+
----------------------
92+
93+
This example will read chunks from the serial port every 300ms::
94+
95+
96+
import asyncio
97+
import serial_asyncio
98+
99+
100+
class InputChunkProtocol(asyncio.Protocol):
101+
def connection_made(self, transport):
102+
self.transport = transport
103+
104+
def data_received(self, data):
105+
print('data received', repr(data))
106+
107+
# stop callbacks again immediately
108+
self.pause_reading()
109+
110+
def pause_reading(self):
111+
# This will stop the callbacks to data_received
112+
self.transport.pause_reading()
113+
114+
def resume_reading(self):
115+
# This will start the callbacks to data_received again with all data that has been received in the meantime.
116+
self.transport.resume_reading()
117+
118+
119+
async def reader():
120+
transport, protocol = await serial_asyncio.create_serial_connection(loop, InputChunkProtocol, '/dev/ttyUSB0', baudrate=115200)
121+
122+
while True:
123+
await asyncio.sleep(0.3)
124+
protocol.resume_reading()
125+
126+
127+
loop = asyncio.get_event_loop()
128+
loop.run_until_complete(reader())
129+
loop.close()

0 commit comments

Comments
 (0)