title: howto clear previous data from buffer on a hotplug using pyserial
body: <p>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. </p>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <p>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 ...</p>
  
  <pre><code>   Device           Main              Read         Device
                              -start-&gt;
                  &lt;-Hotplug-  -stop-&gt;
  -DevcieAlive-&gt;
                  &lt;-open--    -start-&gt;
                                               &lt;-( success + init )-
                              &lt;-success-
                      ok
  
                  &lt;-Hotplug-  -stop-&gt;
  -DeviceAlive-&gt;
                  &lt;-open-     -start-&gt;
                                               &lt;-( old init + success + init )
                    timeout
                  &lt;-close-    -stop-&gt;
  </code></pre>