Skip to content

Instantly share code, notes, and snippets.

@melvinlee
Last active August 29, 2015 14:25
Show Gist options
  • Save melvinlee/70c0736ba52faa9bb0d4 to your computer and use it in GitHub Desktop.
Save melvinlee/70c0736ba52faa9bb0d4 to your computer and use it in GitHub Desktop.
Receive bits from comm port using SerialPort
internal class FromSerialPort : BasedSource
{
private readonly CommPort _commPort;
private static System.IO.Ports.SerialPort _serialPort;
public FromSerialPort(CommPort commPort)
{
if (commPort == null) throw new ArgumentNullException("CommPort");
_commPort = commPort;
}
public override void Run()
{
if (_serialPort == null) _serialPort = new SerialPort();
try
{
_serialPort.PortName = _commPort.Port;
_serialPort.BaudRate = _commPort.BaudRate;
_serialPort.DataBits = _commPort.Databits;
_serialPort.Parity = (Parity)_commPort.Parity;
_serialPort.StopBits = (StopBits)_commPort.StopBits;
_serialPort.Handshake = (Handshake)_commPort.HandShake;
ConfigureSerialPort(_serialPort);
ReadData(_serialPort);
Logging(string.Format("CommPort Observer ready listen on CommPort [{0}].", _commPort.Port));
}
catch (Exception exp)
{
Logging(string.Format("CommPort Observer encounter an error [{0}].", exp.Message));
}
}
protected virtual void ConfigureSerialPort(SerialPort serialPort)
{
serialPort.RtsEnable = true;
serialPort.DtrEnable = true;
serialPort.DiscardNull = true;
serialPort.ReadTimeout = 500;
}
protected virtual void ReadData(SerialPort serialPort)
{
_serialPort.Open();
_serialPort.DataReceived += (s, e) =>
{
try
{
var data = _serialPort.ReadLine();
data = data.Replace("\r", "");
data = data.Replace("\n", "");
Logging("Comm >> " + data);
if (Callback != null && !string.IsNullOrEmpty(data))
Callback(data ,false);
}
catch (TimeoutException exp)
{
Logging(string.Format("CommPort timeout: {0}", exp.Message));
}
};
}
public override void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// free managed resources
try
{
if (_serialPort != null)
{
_serialPort.Close();
_serialPort.Dispose();
}
}
// ReSharper disable EmptyGeneralCatchClause
catch
// ReSharper restore EmptyGeneralCatchClause
{
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment