0
votes

I am read some data from serial port. Data are packed as 9 char. Not need for struct, I know wat the format is, but have 2 problems: 1) If I keep the port open, the answer is 1-3 seconds after the event(there is a led-panel where I can see in real time events and values that shoud be on serial). I supose it is related to some buffer that flush only when full(and I am force to work on Win32 as non-admin, so not very much control of that). The reading is perform periodicaly (200 ms) so opening/closing seems like a waste of resources. Is there a way of keeping the port open and just force the buffer to flush before reading?(from python!)

2)In order to get the values, I have to find a marker - 13 - as the end of struct, and read acordingly(next 8 char or previous 8). Looping is not most eficient python part, so is it a way of geting the index, and reading data without blocking everythings? (A continous read keep processor up, even if in other thread as non-blocking solution). If for any use:

class SeReader(object):
    def __init__(self, tata):
        self.ser = serial.Serial()
        self.ser.baudrate = 2400
        self.ser.port = "COM1"
        self.tata = tata # entry point for main gui notification
        self.val, self.status, self.semn, self.data, self.oldVal = None, None, None, None, None
        self.is_stable, self.on = False, False
        self.stable_count = 0
        self.on = False

    def read(self):
        if not self.on: return False
        self.ser.open()
        data = self.ser.read(18)
        self.ser.close()
        start = -1
        for x in xrange(18):
            if data[x] == '\r':
                start = x + 1
                break
        if start == -1:return True
        self.data = val = data[start:start + 9]
        try:
            self.status = val[0]
            self.val = val[2:8]
            self.semn = val[1]
            self.tata.write_data(self.semn, self.val)
        except Exception as e:
            self.tata.set_cs_unstable()
            self.tata.write_data("> ", "Eroare")
            print(self.val, e)
        if self.val == self.oldVal:
            self.stable_count += 1
        else:
            self.oldVal = self.val
            self.stable_count = 0
        if self.stable_count > 8:self.tata.set_cs_stable()
        else:self.tata.set_cs_unstable()
        return True

the self.tata and stuff are for notify the main GUI

1

1 Answers

0
votes

I use a check of my_serial.inWaiting() to find out if there are any bytes waiting to be read then read them all in a separate thread which then raises an event with the received data attached.

Once I have a block of data I can search it for a given start/end sequence using regular expressions, (re), if the blocks are mixed in with other data.