summaryrefslogtreecommitdiff
path: root/serial
diff options
context:
space:
mode:
authorChris Liechti <cliechti@gmx.net>2016-04-24 23:50:32 +0200
committerChris Liechti <cliechti@gmx.net>2016-04-24 23:50:32 +0200
commitfa62bd94456ae16531b4db2bd2c1de2398fad355 (patch)
tree271c5aabe5ad593c36609923d089435f63e360bc /serial
parentb30d90a05e93956ac8c6d7596b13d08e5be7baaf (diff)
downloadpyserial-git-fa62bd94456ae16531b4db2bd2c1de2398fad355.tar.gz
FramedPacket: add new Packetizer variant that is looking for START and STOP
Diffstat (limited to 'serial')
-rw-r--r--serial/threaded/__init__.py48
1 files changed, 48 insertions, 0 deletions
diff --git a/serial/threaded/__init__.py b/serial/threaded/__init__.py
index 00bf405..5fd3bc9 100644
--- a/serial/threaded/__init__.py
+++ b/serial/threaded/__init__.py
@@ -66,6 +66,54 @@ class Packetizer(Protocol):
raise NotImplementedError('please implement functionality in handle_packet')
+class FramedPacket(Protocol):
+ """
+ Read binary packets. Packets are expected to have a start and stop marker.
+
+ The class also keeps track of the transport.
+ """
+
+ START = b'('
+ STOP = b')'
+
+ def __init__(self):
+ self.packet = bytearray()
+ self.in_packet = False
+ self.transport = None
+
+ def connection_made(self, transport):
+ """Store transport"""
+ self.transport = transport
+
+ def connection_lost(self, exc):
+ """Forget transport"""
+ self.transport = None
+ self.in_packet = False
+ del self.packet[:]
+
+ def data_received(self, data):
+ """Find data enclosed in START/STOP, call handle_packet"""
+ for byte in serial.iterbytes(data):
+ if byte == self.START:
+ self.in_packet = True
+ elif byte == self.STOP:
+ self.in_packet = False
+ self.handle_packet(packet)
+ del self.packet[:]
+ elif self.in_packet:
+ self.packet.append(byte)
+ else:
+ self.handle_out_of_packet_data(byte)
+
+ def handle_packet(self, packet):
+ """Process packets - to be overridden by subclassing"""
+ raise NotImplementedError('please implement functionality in handle_packet')
+
+ def handle_out_of_packet_data(self, data):
+ """Process data that is received outside of packets"""
+ pass
+
+
class LineReader(Packetizer):
"""
Read and write (Unicode) lines from/to serial port.