Search code examples
python-2.7pyserialtracers485

Pyserial readline() hangs the program forever without reading serial data


When calling the pyserial.readline() function my program hangs. I ran a trace on the program, and the bottom loop keeps repeating.

transport.py(47):             self.sensor_data = self.serif.readline()
 --- modulename: serialposix, funcname: read
serialposix.py(477):         if not self.is_open:
serialposix.py(479):         read = bytearray()
serialposix.py(480):         timeout = Timeout(self._timeout)
 --- modulename: serialutil, funcname: __init__
serialutil.py(125):         self.is_infinite = (duration is None)
serialutil.py(126):         self.is_non_blocking = (duration == 0)
serialutil.py(127):         self.duration = duration
serialutil.py(128):         if duration is not None:
serialutil.py(129):             self.target_time = self.TIME() + duration
serialposix.py(481):         while len(read) < size:
serialposix.py(482):             try:
serialposix.py(483):                 ready, _, _ = select.select([self.fd, self.pipe_abort_read_r], [], [], timeout.time_left())
 --- modulename: serialutil, funcname: time_left
serialutil.py(139):         if self.is_non_blocking:
serialutil.py(141):         elif self.is_infinite:
serialutil.py(144):             delta = self.target_time - self.TIME()
serialutil.py(145):             if delta > self.duration:
serialutil.py(150):                 return max(0, delta)
serialposix.py(484):                 if self.pipe_abort_read_r in ready:
serialposix.py(491):                 if not ready:
serialposix.py(493):                 buf = os.read(self.fd, size - len(read))
serialposix.py(496):                 if not buf:
serialposix.py(503):                 read.extend(buf)
serialposix.py(516):             if timeout.expired():
 --- modulename: serialutil, funcname: expired
serialutil.py(135):         return self.target_time is not None and self.time_left() <= 0
 --- modulename: serialutil, funcname: time_left
serialutil.py(139):         if self.is_non_blocking:
serialutil.py(141):         elif self.is_infinite:
serialutil.py(144):             delta = self.target_time - self.TIME()
serialutil.py(145):             if delta > self.duration:
serialutil.py(150):                 return max(0, delta)
serialposix.py(481):         while len(read) < size:
serialposix.py(518):         return bytes(read)

The serial settings I have driving my interface defined as "serif" are as follows.

    self.serif = serial.Serial('/dev/ttyS1', 9600)
    self.serif.bytesize = serial.EIGHTBITS
    self.serif.parity = serial.PARITY_NONE
    self.serif.stopbits = serial.STOPBITS_ONE
    self.serif.timeout = 0.3

I tried adding the function self.serif.reset_input_buffer() before starting my read function, however this seemed to have made things worse.

here is a copy of the function in question before the readline() function.

def rcv_data(self):
    """Receives data, cleans it and returns it to main()"""
    # CHECKS FOR DATA IN BUFFER
    serial_buffer = self.serif.inWaiting()
    if serial_buffer > 0:
        cnt = 0
        print("serial_buffer = %i" % serial_buffer)
        while self.serif.read().encode('hex') != '02':
            cnt += 1
            serial_buffer -= 1
        print("Eliminated %i peices of garbage" % (cnt))
        # Reads data from the buffer
        self.sensor_data = self.serif.readline()

I cannot figure out why this code seems to get stuck in the serialposix.py loop.. If anyone can help me out I would be grateful!

Thank you and let me know if I need to send any more information.


Solution

  • EDIT

    Why I had it working before is no longer a mystery. The power supply that I had powering both my device, and the RS485 circuit pull-up/pull-down resistors was unstable. As such I was recieving noise where my SOF or EOF was suppose to be, and so the program continued reading forever. That being said, I still kept the below workaround as it is more clear as to what I am doing (although longer...)

    Furthermore, I added in a break to the below answer in case that the SOF or EOF cannot be found in a certain number of read cycles.

    EDIT_END

    Not particularly an answer, but a workaround. I will start off by emphasizing the following.

    1. readline() was looping because it expects an EOF of \n (0x11 in hex) i and my serial data never provided this. Why I had it working before was a mystery.
    2. I still have no idea why this doesn't stop looping after the set timeout.

    My workaround involved essentially creating my own readline() function in a sense, and specifying my own EOF. I used the following code to do this.

    def readline(self):
        SOF = '02'
        EOF = '03'
        # FIND START OF FRAME
        while serif.read().encode('hex') != SOF:
            continue
        # RECORD UNTIL END OF FRAME
        while True:
            temp = serif.read()
            if temp.encode('hex') == EOF:
                break
            else:
                sensor_data += temp
    

    My original function will now look like this.

    def rcv_data(self):
        """Receives data cleans it and returns it to main()"""
        # CHECKS FOR DATA IN BUFFER
        if serif.inWaiting() > 0:
            readline()
        return sensor_data