'Pyserial might lose bytes and sometimes won't receive data at all

I'm using PySerial library in order to read 255-byte packets from nRF52 board. But I'm facing some issues:

  • as far as I know it needs 460800 baudrate, but Windows device manager reports 9600 and I don't understand how to set the required baudrate for the COM port driver (there is just no 460800 in dropdown menu).
  • script sporadically loses bytes, often It misses just a single byte somewhere. That leads to checksum mismatch while reading packet (I'm using CRC32)
  • sometimes it's impossible to run script if it was already used previously without replugging the board. E.g. script might freeze on the first read attempt and sit there sometimes even ignoring the timeout.

Please, give some advices. I never had a deal with PySerial library before.

PortSettings.py

# Port Settings script----

import serial
import serial.tools.list_ports
import platform
import _Config

Port = {"Num": str(_Config.PortNum),
        "Baud": 460800,  # 921600 - USB Dongle, 460800 - Debug PCB
        "Parity": serial.PARITY_NONE,
        "DataBits": serial.EIGHTBITS,
        "StopBits": serial.STOPBITS_ONE,
        "Translation": "binary"}

COM = ("tty" if (platform.system() == "Linux") else "COM")

def listPorts():
    availPorts = []
    ports = serial.tools.list_ports.comports();
    for port, desc, hwid in sorted(ports):
        availPorts.append(str(port))
    return availPorts

def tryOpenSerialPort():
    if not COM + Port["Num"] in listPorts():
        raise OSError("ERROR: " + COM + Port["Num"] + " does not exist")

    con = serial.Serial()
    con.baudrate = Port["Baud"]
    con.port = COM + Port["Num"]
    con.bytesize = Port["DataBits"]
    con.parity = Port["Parity"]
    con.stopbits = Port["StopBits"]
    # buffering none
    # newline 0
    # translation port["Translation"]
    # buffersize 16384*2
    con.open()
    print("INFO: Port opened")
    return con

MainScript.py

...
ds = makeDongleConfig()
con = tryOpenSerialPort()
...
if not con.is_open:
    print("COM" + Port["Num"] + " does not exist!")
    print("List of available ports: " + listPorts())
    quit()
else:
    print("INFO: COM" + str(_Config.PortNum) + " opened")
    ...
os.chdir(_Config.LogPath)
con.write(ds)
con.flush()
print("INFO: Settings sent")
Cons = 1
try:
    while Cons:
        Buf_Count = con.in_waiting
        if Buf_Count != 0:
            # print("Available: "+str(Buf_Count))
            RawInput = con.read(size=255)
            ...
except KeyboardInterrupt:
    print("Execution was interrupted by user")
except Exception as e:
    print("ERROR! "+str(e))
finally:
    con.flush()
    con.close()
    print("INFO: Close COM")


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source