简体   繁体   中英

howto clear previous data from buffer on a hotplug using pyserial

I am writing a script to test hotplugging a serial device using the pyserial module. The script has one main thread which handles writing and a read thread for reading data.

The main thread sends a hotplug signal which then stops the read thread until the device is detected again when it starts the read thread again. The main thread waits for a hotplug success message to confirm hotplug success ( with a timeout ) and starts again from sending hotplug message.The issue occurs when the serial device sends initialization messages after the first hotplug success message on connection.

The script runs good for the first time. But for the second time, the input serial buffer still has some data ( the init messages ) that needs to be read first before reading any new success and initialization messages. Doing this make the script loose the success message as it times out.

I wish to flush the serial buffer completely and discard any content before I start the read thread on a hotswap ( which is, I don't care what messages were received before hotswap ). I tried using the ser.flushInput()/flushOutput()/flush() method after receiving the hotplug success message, but it does nothing. The data is still read from the buffer. I can do a workaround by introducing a time.sleep(5) before the next iteration ( to read all init from buffer ), but want a cleaner approach to this.

How do I completely discard the previous init messages in the input buffer once I get the success message, such that next iteration has nothing to read before hotswap. I hope the issue is clear with a sequence diagram below, because the code is too big to post.

Update: I have read somewhere that one can't flush the input, it is one of those undefined behaviors like in C. Got to read until EOF/EOL ...

   Device           Main              Read         Device
                            -start->
                <-Hotplug-  -stop->
-DevcieAlive->
                <-open--    -start->
                                             <-( success + init )-
                            <-success-
                    ok

                <-Hotplug-  -stop->
-DeviceAlive->
                <-open-     -start->
                                             <-( old init + success + init )
                  timeout
                <-close-    -stop->

You can flush values using py.flushOutput and py.flushInput . If this doesnt work, just set the value to be sent as any garbage value before closing the serial port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM