1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
#!/usr/bin/env python3
import serial
import json
import re
class Usv(object):
def __init__(self, device, baudrate, json_file):
self._serial_port = serial.Serial(device,
baudrate=baudrate,
timeout=0.8)
# force a clean prompt
#self._serial_port.write(b"\r")
self._read_until_prompt("\r")
#print("cleaned prompt")
with open(json_file) as fhandle:
self.json_params = json.load(fhandle)
def _read_until_prompt(self, outbuf):
# match on "\n=>"
self._serial_port.write(outbuf.encode())
inbuf = self._serial_port.read(100)
sbuf = inbuf.decode("utf-8")
#prompt = False
#inbuf = []
#while not prompt:
# pending = self._serial_port.read(1)
# if len(pending) == 0:
# self._serial_port.write(b"\r")
# else:
# inbuf.append(pending)
# print(pending)
#if len(sbuf) > 2:
# if sbuf[-3] == "\n" and \
# sbuf[-2] == "=" and sbuf[-1] == ">":
# return sbuf
# else:
# sbuf = self._read_until_prompt(outbuf)
return sbuf
def get_parameters(self):
# [{'name': 'acvoltsin', 'index': 1},
results = {}
for parameter in self.json_params:
outbuf = "d %s\r" % parameter['num']
inbuf = self._read_until_prompt(outbuf)
regex = parameter['regex']
match = re.search(regex, inbuf, re.MULTILINE)
if match:
name = parameter['name']
value = float(match.group(1))
results.setdefault(name, value)
#print("MATCH: %s: %f" % (name,value))
return results
if __name__ == "__main__":
import pprint
usv = Usv("/dev/ttyU0", 600, "usv_param.json")
parameters = usv.get_parameters()
pprint.pprint(parameters)
|