4 from serial import Serial
5 from datetime import datetime
16 self.time = datetime.utcnow()
23 def __init__(self, config):
31 self.serial = Serial(self.port, \
32 baudrate = self.config.baudrate, \
33 parity = self.config.parity, \
34 bytesize = self.config.databits, \
35 stopbits = self.config.stopbits, \
38 self.serial.flushInput()
39 except Exception as ex:
43 if self.serial and self.serial.isOpen():
47 if self.serial == None:
49 if self.serial.isOpen() == False:
54 for key in list(self.config.enable.keys()):
55 state = self.config.enable[key]
56 rate = self.config.rate[key]
57 cmd = 'start' if state else 'stop'
58 self._write_ascii('%s %s' % (cmd, key))
59 self._write_ascii('set %s int %d' % (key, rate))
65 if not self.running():
67 while self.serial.readable():
69 char = self.serial.read().decode()
70 except Exception as ex:
74 if char == '\r' or char == '\n':
75 if len(self.inbuf) == 0:
77 line = "".join(self.inbuf)
78 print('read: [' + line + ']')
79 item = self._parse_ascii(line)
83 self.inbuf.append(char)
85 print("Error: exceeded read limit")
91 def _write_ascii(self, line):
93 print('write: [' + line + ']')
94 data = bytes(line+'\n', 'UTF-8')
95 self.serial.write(data)
99 def _parse_ascii(self, line):
100 acc_re = compile("\[ACC\] accX=(.*) accY=(.*) accZ=(.*)")
101 mag_re = compile("\[MAG\] magX=(.*) magY=(.*) magZ=(.*)")
102 lgt_re = compile("\[LGT\] Light Intensity=(.*)")
103 tch_re = compile("\[TCH\] Force=(.*) Distance=(.*)")
104 a2d_re = compile("\[A2D\] ...")
106 acc_m = acc_re.match(line)
107 mag_m = mag_re.match(line)
108 lgt_m = lgt_re.match(line)
109 tch_m = tch_re.match(line)
110 a2d_m = a2d_re.match(line)
114 state.acc[0] = float(acc_m.group(1))
115 state.acc[1] = float(acc_m.group(2))
116 state.acc[2] = float(acc_m.group(3))
118 state.mag[0] = float(mag_m.group(1))
119 state.mag[1] = float(mag_m.group(2))
120 state.mag[2] = float(mag_m.group(3))
122 state.light[0] = float(lgt_m.group(1))
124 state.touch[0] = float(tch_m.group(1))
126 state.a2d[0] = float(tch_m.group(1))
127 state.a2d[1] = float(tch_m.group(2))
128 state.a2d[2] = float(tch_m.group(3))
129 state.a2d[3] = float(tch_m.group(4))
130 state.a2d[4] = float(tch_m.group(5))
131 state.a2d[5] = float(tch_m.group(6))