I am trying to parse data continuously coming in via serial port connection. I am having difficulty printing variable 'extracted_vals' in the correct format.
import serial
import time
import re
ser = serial.Serial( #drop down to change name or baudrate etc.
port='name',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
print("connected to: " + ser.portstr)
extracted_vals = []
while True:
for line in ser.readline():
time.sleep(.1)
signal = chr(line)
regex = "(?:.*\s)?\nX\n=\n(?P<X>-?\d+)\s\nY\n=\n(?P<Y>.*)"
parts = signal.split(r'\n\n\n')
for part in parts:
m = re.match(regex, part)
if m is None:
continue
X,Y = m.groupdict().values()
extracted_vals.append(dict(X=int(X),
Y=[Y[i:i+2] for i in range(0,len(Y),2)]))
print(extracted_vals)
ser.close()
When I print(signal),I see a continuous output in the form:
0
0
0
:
0
0
B
K
O
0
0
D
0
X
=
-
9
0
Y
=
A
3
4
2
D
5
S
3
9
8
X
=
-
1
0
1
Y
=
I first want to extract substrings in the form 'X=-98 Y=FF32A4DE'. The substrings repeat in the continuous output above and each is unique. As the serial port in connected the data just keep coming in continuously, I am thinking I maybe need some sort of time interval loop to extract substrings stepwise and parse the data.
I want the output of print(extracted_vals) to look like, with X as integers:
[{'X': -90, 'Y': ['43', '01', 'BB', 'C6', '2D', '87', 'E4', '68']}, {'X': -74, 'Y': ['43', '21', '67']}, {'X': -88, 'Y': ['CF', 'BA','03']}]