title: Python's pyserial with interrupt mode
body: <p>I have a device which works on <code>serial communication</code>. I am writing python code which will send some commands to get the data from the device.</p>
  
  <p>There are three commands. </p>
  
  <pre><code>1.COMMAND - sop 
    Device does its internal calculation and sends below data
  
    Response - "b'SOP,0,921,34,40,207,0,x9A\r\n'"
  
  2.COMMAND - time
    This gives a date time values which normally do not change untill the device is restarted
  
  3.START - "\r\r" or (&lt;cr&gt;&lt;cr&gt;)
    This command puts the device in responsive mode after which it responds to above commands. This command is basically entering &lt;enter&gt; twice &amp; only have to do once at the start.
  </code></pre>
  
  <p>Now the problem which I am facing is that, frequency of data received from <code>sop</code> command is not fixed and hence the data is received anytime. This command can also not be stopped once started, so if I run another command like <code>time</code>, and read the data, I do not receive time values and they are merged with the <code>sop</code> data sometime. Below is the code, I am using:</p>
  
  <pre><code>port = serial.Serial('/dev/ttyS0',115200)  #Init serial port
  
  port.write(("\r\r".encode()))  #Sending the start command
  bytesToRead = port.in_waiting  #Checking data bytesize
  res = port.read(bytesToRead)   #Reading the data which is normally a welcome msg
  port.reset_input_buffer()      #Clearing the input serial buffer
  port.reset_output_buffer()     #Clearing the output serial buffer
  
  port.write(("sop\r".encode())) #Sending the command sop
  
  while True:
      time.sleep(5)
      bytesToRead = port.in_waiting
      print(bytesToRead)
      res = port.read(bytesToRead)
      print(res)
      port.reset_input_buffer()
  
      port.write(("time\r".encode()))
      res = port.readline()
      print(res)
  </code></pre>
  
  <p>Using the above command I sometimes do not receive the value of time after executing its command or sometimes it is merged with the <code>sop</code> command. Also with the sop command, I received a lot of data during the <code>sleep(5)</code> out of which I need to get the latest data. If I do not include <code>sleep(5)</code>, I miss the <code>sop</code> data and it is then received after executing the <code>time</code> command. </p>
  
  <p>I was hoping if anyone can point me to right direction of how to design it in a better way. Also, I think this can easily be done using interrupt handler but I didn't found any code about pyserial interrupts. Can anyone please suggest some good code for using interrupts in pyserial.</p>
  
  <p>Thanks</p>