3

I am developing a program that polls a device for actvity. In the past I have always used a USB device with a pure USB device driver. The upside of this was that that device was blazingly fast. The downside was that it limited me to the DLL the manufacturer distributed with it.

For certain reasons beyond my control I have to switch to a new USB device that emulates a serial port. In this case it uses an Atmel chip for that. I have also tried an FTDI-chip based device.

I have all of this working but there's a slight drawback. Connecting and disconnecting to the serial port is much slower. There is a noticable half to full second delay which the users that know the old situation complain about.

My strategy has always been to only be connected to the device when I needed to be. But I am starting to wonder if maybe I should change strategies and stay connected all day. But that has the obvious drawback of having to keep track of whether or not the connection is still up, and reconnecting if it's not.

Am I being overly cautious by connecting on demand, or is staying connected all day the obvious solution? Perhaps there is a third option I am missing here? Thanks.

StanB123
  • 131

1 Answers1

2

Keep the connection open and separate the logic of ensuring the connection is open from the actual using of the serial connection.

In C# I would provide the following methods for using the serial connection:

public T WithSerialConnection<T>(Func<MySerialConnection, T> f);

public void WithSerialConnection(Action<MySerialConnection> act);

MySerialConnection represents an open serial connection, replace it with your own class or with a stream from your language/library. f and act receive this as a parameter and are isolated from how you open and close the connection.

You can require that f and act can be called more than once with the same effect; i.e. they should be a kind of pure except for sending and receiving bytes via the serial port.
With this requirement the implementation of WithSerialConnection() can:

  1. at first, assume the serial connection is working (which is fast); and,
  2. only when catching an exception reveals that the connection is not available recover by closing and reopening the serial connection and calling f or act again.