Hoje mostro como verificar acessar a porta serial somente instanciando essa classe, você pode estender as funcionalidades conforme sua necessidade.
[sections] [section title=”Classe para acesso a porta serial”]

/// CommPort class creates a singleton instance
/// of SerialPort (System.IO.Ports)
/// When ready, you open the port.
/// <code>
/// CommPort com = CommPort.Instance;
/// com.StatusChanged += OnStatusChanged;
/// com.DataReceived += OnDataReceived;
/// com.Open();
/// </code>
/// Notice that delegates are used to handle status and data events.
/// When settings are changed, you close and reopen the port.
/// <code>
/// CommPort com = CommPort.Instance;
/// com.Close();
/// com.PortName = "COM4";
/// com.Open();
/// </code>
///
public sealed class CommPort: IDisposable
{
private readonly SerialPort _serialPort;
private Thread _readThread;
private volatile bool _keepReading;

//begin Singleton pattern
private static readonly CommPort InstanceComPort = new CommPort();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static CommPort()
{
}

private CommPort()
{
_serialPort = new SerialPort();
_readThread = null;
_keepReading = false;
_serialPort.PinChanged += PinChanged;
}

private void PinChanged(object sender, SerialPinChangedEventArgs e)
{
switch (e.EventType)
{
case SerialPinChange.CtsChanged:
PinChange("CTS," + _serialPort.CtsHolding);
break;
case SerialPinChange.DsrChanged:
PinChange("DSR," + _serialPort.DsrHolding);
break;
case SerialPinChange.CDChanged:
PinChange("CD," + _serialPort.CDHolding);
break;
case SerialPinChange.Break:
PinChange("BREAK," + _serialPort.BreakState);
break;
case SerialPinChange.Ring:
PinChange("RING");
break;
}
}

public static CommPort Instance
{
get { return InstanceComPort; }
}

public bool Rts
{
set { _serialPort.RtsEnable = value; }
get { return _serialPort.RtsEnable; }
}

public bool Dtr
{
set { _serialPort.DtrEnable = value; }
get { return _serialPort.DtrEnable; }
}

//end Singleton pattern

//begin Observer pattern
public delegate void EventHandler(string param);

public EventHandler StatusChanged;
public EventHandler DataReceived;
public EventHandler PinChange;

//end Observer pattern

private void StartReading()
{
if (!_keepReading)
{
_keepReading = true;
_readThread = new Thread(ReadPort);
_readThread.Start();
}
}

private void StopReading()
{
if (_keepReading)
{
_keepReading = false;
_readThread.Join(); //block until exits
_readThread = null;
}
}

/// Get the data and pass it on.
private void ReadPort()
{
while (_keepReading)
{
if (_serialPort.IsOpen)
{
var readBuffer = new byte[_serialPort.ReadBufferSize + 1];
try
{
// If there are bytes available on the serial port,
// Read returns up to "count" bytes, but will not block (wait)
// for the remaining bytes. If there are no bytes available
// on the serial port, Read will block until at least one byte
// is available on the port, up until the ReadTimeout milliseconds
// have elapsed, at which time a TimeoutException will be thrown.
int count = _serialPort.Read(readBuffer, 0, _serialPort.ReadBufferSize);
String serialIn = System.Text.Encoding.ASCII.GetString(readBuffer, 0, count);
DataReceived(serialIn);
}
catch (TimeoutException)
{
}
}
else
{
var waitTime = new TimeSpan(0, 0, 0, 0, 50);
Thread.Sleep(waitTime);
}
}
}

/// Open the serial port with current settings.
public void Open()
{
Close();

try
{
_serialPort.PortName = Settings.Port.PortName;
_serialPort.BaudRate = Settings.Port.BaudRate;
_serialPort.Parity = Settings.Port.Parity;
_serialPort.DataBits = Settings.Port.DataBits;
_serialPort.StopBits = Settings.Port.StopBits;
_serialPort.Handshake = Settings.Port.Handshake;

// Set the read/write timeouts
_serialPort.ReadTimeout = 50;
_serialPort.WriteTimeout = 50;

_serialPort.Open();
StartReading();
}
catch (IOException)
{
StatusChanged(String.Format("{0} não existe", Settings.Port.PortName));
}
catch (UnauthorizedAccessException)
{
StatusChanged(String.Format("{0} está em uso", Settings.Port.PortName));
}
catch (Exception ex)
{
StatusChanged(String.Format("{0}", ex));
}

// Update the status
if (_serialPort.IsOpen)
{
string p = _serialPort.Parity.ToString().Substring(0, 1); //First char
string h = _serialPort.Handshake.ToString();
if (_serialPort.Handshake == Handshake.None)
h = &amp;quot; sem handshake&amp;quot;; // more descriptive than &amp;quot;None&amp;quot;

StatusChanged(String.Format("{0}: {1} bps, {2}{3}{4}, {5}",
_serialPort.PortName, _serialPort.BaudRate,
_serialPort.DataBits, p, (int) _serialPort.StopBits, h));
}
else
{
StatusChanged(String.Format("{0} está em uso", Settings.Port.PortName));
}
}

/// Close the serial port.
public void Close()
{
if (!_serialPort.IsOpen) return;
StopReading();
_serialPort.Close();
StatusChanged("Conexão Fechada");
}

/// Get the status of the serial port.
public bool IsOpen
{
get { return _serialPort.IsOpen; }
}

/// Get a list of the available ports. Already opened ports
/// are not returend.
public string[] GetAvailablePorts()
{
return SerialPort.GetPortNames();
}

///Send data to the serial port after appending line ending.
///An string containing the data to send.
public void Send(string data)
{
if (IsOpen)
{
string lineEnding = "";
switch (Settings.Option.AppendToSend)
{
case Settings.Option.AppendType.AppendCR:
lineEnding = "\r";
break;
case Settings.Option.AppendType.AppendLF:
lineEnding = "\n";
break;
case Settings.Option.AppendType.AppendCRLF:
lineEnding = "\r\n";
break;
}

_serialPort.Write(data + lineEnding);
}
}

public void Dispose()
{
_serialPort.Dispose();
}
}

[/section] [/sections]
Obrigado e até o próximo post.

DATEK Tecnologia Eletrônica
[C#] Classe para acesso a porta serial
Tags:                 

Deixe uma resposta

%d blogueiros gostam disto: