InstrumentInterface.py 1.39 KB
Newer Older
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
from serial import Serial
from interfaces.Protocol.sadapmap_pb2 import MultiChannelReading, ReqMultiChannelReading

class InstrumentInterface(object):
    def __init__(self, logger, location, channels):
        self.channels = channels
        self.logger = logger
        logger("[ARDUINO]", "Opening serial port...")
        try:
            self.ser = Serial(location, 115200, timeout=0.05)
        except Exception as e:
            logger("[ARDUINO]", "ERROR: Could not open serial port")
            raise FileNotFoundError("Serial port not found") from e
        logger("[ARDUINO]", "Board started, good luck!")

    def read(self):
        pass

    def readAll(self):
        self.ser.flushInput()                                   # Limpeza do buffer de entrada
        req = ReqMultiChannelReading()
        [req.id.append(i['id']) for i in self.channels]
        self.ser.flushInput()
        self.ser.write(req.SerializeToString())
        reading = MultiChannelReading()
        data = self.ser.read(128)
        try:
            reading.ParseFromString(data)
        except:
            self.logger("[ARDUINO]", "Got invalid data")
            return [0 for i in range(len(self.channels))]
        if len(reading.channels) != len(self.channels):
            self.logger("[ARDUINO]", "Got null data")
            return [0 for i in range(len(self.channels))]
        return [i.value for i in reading.channels]