[Python] pyserial Thread protocol relaunch conection

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    I've ans issue with pyserial threaded protocol I've overloaded protocol class (no detail on what is protocol is relevant here)

    class myProtocol(Protocol):
    def __init__(self):
    super().__init__()
    self._reader:ReaderThread=None
    self._frontend:MK3FrontEnd=None

    def connection_made(self, transport):
    super(myProtocol, self).connection_made(transport)
    self._reader=transport

    def connection_lost(self, exc):
    print("Connexion Lost")

    def data_received(self, data):
    super().data_received(data)
    def probe(self):
    pass # donc care for now


    in my main() function I'm starting serial and reader thread like follows :

    port=args.port
    try:
    serial_instance = serial.serial_for_url(port, default_baudrate, write_timeout=1)
    except serial.SerialException as e:
    sys.stderr.write('could not open port\n')
    exit()
    try:
    with ReaderThread(serial_instance, myProtocol) as Listener:
    Listener.setPortBaudrate(port,default_baudrate)
    Listener.Probe() # special function of my own to exchange a packet to
    # iddentify if it's the device I hope or not
    time.sleep(0.5) # time to wait response
    if not(Listener.ProbeOk):
    raise Exception('notGoodDevice')
    else:
    sys.stderr.write(f"MK3 Rx Found on {port}\n")
    Keyblistener = keyboard.Listener(on_press=on_press,on_release=on_release)
    Keyblistener.start()
    try:
    while True: # keep the reader alive until user press CTRL-C
    time.sleep(1)
    except KeyboardInterrupt:
    print("kill process");
    except:
    sys.stderr.write('this is not a reciever\n')
    exit()


    my point is that in case of serial error I well receive the connexion_lost() event in the protocol object but I dont find any solution to try and retry serial open until it's comming back I can close and reopen serial in case of a connexion lost but I dont find any good way to get a reader thread back as threads can only be start one time and I cant go back to main thread to re create a new reader thread do you have any idea to make it pythonic style ?? thank's for any idea

    Continue reading...

Compartilhe esta Página