title: Using asyncio to read the output of a serial port
body: <p>I have been doing some port-reading for work, and I need to know if I should use asyncIO to read the data that comes in from this port.</p>
  
  <p>Here's some details about the way in which the system is constructed.</p>
  
  <ol>
  <li><p>Multiple sensors are being read at the same time and might produce output that goes in at the same time. (all data comes in through a probee ZU10 connected to a usb port) All data must be timestamped as soon as it comes in.</p></li>
  <li><p>The data is supposed to be processed and then sent to a django webapp through a REST API.</p></li>
  </ol>
  
  <p>The thing Is, it's really important not to lose any data, I'm asking about this because I believe there must be an easier way to do this than the one I'm thinking of. </p>
  
  <p>The way I want the data to come in is through an asyncronous process that takes in the data into a queue and timestamps it, this way there is no way in which loss of data is present, and timestamping may be no more than a few fractions of a second off, which is not a problem.</p>
  
  <p>If anyone has got any ideas I would be thankful for them</p>
  
  <p>Here's the code I'm using to open the port, take the data in and what I've got so far on the actually reading the meaningful data.</p>
  
  <p>Here's the reading part:</p>
  
  <pre><code>import serial #for port opening
  import sys #for exceptions
  
  #
  
  #configure the serial connections (the parameters differs on the device you are connecting to)
  
  class Serializer: 
      def __init__(self, port, baudrate=9600, timeout=.1): 
          self.port = serial.Serial(port = port, baudrate=baudrate, 
          timeout=timeout, writeTimeout=timeout)
  
      def open(self): 
          ''' Abre Puerto Serial'''
          self.port.open()
  
      def close(self): 
          ''' Cierra Puerto Serial'''
          self.port.close() 
  
      def send(self, msg):
          ''' envía mensaje a dispositivo serial'''
          self.port.write(msg)
  
      def recv(self):
          ''' lee salidas del dispositivo serial '''
          return self.port.readline()
  
  PORT = '/dev/ttyUSB0' #Esto puede necesitar cambiarse
  
  
  # test main class made for testing
  def main():
      test_port = Serializer(port = PORT)
  
      while True:
          print(test_port.recv())
  
  if __name__ == "__main__":
      main()
  </code></pre>
  
  <p>And a bit of what I'm going to be using to filter out the meaningful reads (bear with it, it might be full of awful errors and maybe a terrible RegEx):</p>
  
  <pre><code>import re
  from Lector import ChecaPuertos
  from Lector import entrada
  
  
  patterns = [r'^{5}[0-9],2[0-9a-fA-F] $'] #pattern list
  
  class IterPat:
      def __init__(self, lect, pat = patterns):
          self.pat = pat  # lista de patrones posibles para sensores
          self.lect = lect  # lectura siendo analizada
          self.patLen = len(pat)  #Largo de patrones
  
      def __iter__(self):
          self.iteracion = 0 #crea la variable a iterar.
  
      def __next__(self):
          '''
          Primero revisa si ya pasamos por todas las iteraciones posibles
          luego revisa si la iteración es la que pensabamos, de ser así regresa una
          tupla con el patrón correspondiente, y la lectura
          de otra forma para el valor de ser mostrado
          '''
          pattern = re.compile(self.pat[self.iteracion])
          comp = pattern.match(self.lect)
          if comp == True:
              re_value = (self.pattern, self.lect)
              return re_value
          else:
              self.iteración += 1
  
  def main():
      puerto = ChecaPuertos.serial_ports()
      serial = entrada.Serializer(port = puerto[0])
  
      if serial != open:
          serial.open()
      while True:
          iter = IterPat()
  
       #This is incomplete right here.
  </code></pre>