title: How to deal with multiple serial ports for R/W using twisted?
body: <p>Going through the twisted finger tutorial and seen the SO questions:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/17739955/twisted-python-script-on-raspberry-pi-debian-to-communicate-with-arduino-via-u">Question-1</a></li>
  <li><a href="https://stackoverflow.com/questions/18116670/twisted-python-pausing-a-serial-port-read">Question-2</a></li>
  </ul>
  
  <p>However, I can't (yet) write a twisted program that can read &amp; write from multiple serial ports, especially where the protocol involves reading single or multiple lines, and writing back to the device accordingly.</p>
  
  <p>What I am trying to do is open 2 pairs (i.e. total of 4) serial ports, for 2 modems. Communication with modems is using Hayes AT command set. While most of the command/response exchanges with modem is via the command-port, there are few diagnostic information that are available only via the diagnostic-port, for each modem. The diagnostic information should lead to a state-machine (device-state, connection-state) to be modified.</p>
  
  <p>Here is a rough skeletal program of what I understand as the potential approach (based on single port examples):</p>
  
  <pre><code>class CommandProtocol(LineOnlyReceiver):
      def connectionMade(self):
          log.msg("Connected to command port")
  
      def lineReceived(self, line):
          print repr(line)
          processCommandLine(line)
  
  class DiagnosticProtocol(LineOnlyReceiver):
      def connectionMade(self):
          log.msg("Connected to diag port")
  
      def lineReceived(self, line):
          print repr(line)
          processDiagnosticLine(line)
  
  ...
  
  # modem1 ports
  cmdPort[0] = SerialPort(CommandProtocol, "/dev/ttyUSB0", reactor, 115200)
  diagPort[0] = SerialPort(DiagnosticProtocol, "/dev/ttyUSB1", reactor, 115200)
  # modem2 ports
  cmdPort[1] = SerialPort(CommandProtocol, "/dev/ttyUSB3", reactor, 115200)
  diagPort[1] = SerialPort(DiagnosticProtocol, "/dev/ttyUSB4", reactor, 115200)
  </code></pre>
  
  <p>However, I am at loss, as to how do I do the following:</p>
  
  <ul>
  <li>How/where do I accept CLI input from user, that then triggers sending a set of AT command to the modems ?</li>
  <li>Correlate the information received on command port for ttyUSB0 &amp; ttyUSB1 for modem1, and similarly for the other pair for modem2 ? Note that each modem has it's own state-machine (device-state and connection-state)</li>
  <li>Does twisted provide any mechanism for management of multiple state-machines by application ?</li>
  <li>It is possible that the USB-serial connection to the modem is destroyed due to the modem being unplugged, and re-established on being plugged back-in. How can I detect such events and add the monitoring of the corresponding device-ports to the reactor ? Currently, I'm doing it statically in the main application.</li>
  </ul>