117 lines
2.8 KiB
C#
117 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.IO.Ports;
|
|
using System.Threading;
|
|
|
|
namespace bsmd.AISService.AIS
|
|
{
|
|
public class Serial_IO
|
|
{
|
|
#region private fields
|
|
private string stationName;
|
|
private SerialPort port;
|
|
private bool runReader = true;
|
|
private Thread readerThread = null;
|
|
#endregion
|
|
|
|
// event fired if input line is available
|
|
public delegate void LineReadHandler(string data);
|
|
public event LineReadHandler LineRead;
|
|
|
|
|
|
public Serial_IO()
|
|
{
|
|
this.port = new SerialPort();
|
|
}
|
|
|
|
public bool Open(ref string message)
|
|
{
|
|
bool retval = true;
|
|
try
|
|
{
|
|
this.port.Open();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
message = ex.Message;
|
|
retval = false;
|
|
}
|
|
if (retval)
|
|
{
|
|
this.readerThread = new Thread(new ThreadStart(this.Read));
|
|
this.runReader = true;
|
|
this.readerThread.Start();
|
|
}
|
|
return retval;
|
|
}
|
|
|
|
public void Close()
|
|
{
|
|
this.runReader = false;
|
|
if(readerThread != null)
|
|
if(readerThread.ThreadState == ThreadState.Running)
|
|
this.readerThread.Join();
|
|
if (this.port.IsOpen)
|
|
{
|
|
this.port.BaseStream.Flush();
|
|
this.port.Close();
|
|
}
|
|
}
|
|
|
|
public string[] GetComPorts()
|
|
{
|
|
return SerialPort.GetPortNames();
|
|
}
|
|
|
|
#region Properties
|
|
|
|
public int BaudRate
|
|
{
|
|
get { return this.port.BaudRate; }
|
|
set { this.port.BaudRate = value; }
|
|
}
|
|
|
|
public string ComPort
|
|
{
|
|
get { return this.port.PortName; }
|
|
set { this.port.PortName = value; }
|
|
}
|
|
|
|
public string StationName
|
|
{
|
|
get { return this.stationName; }
|
|
set { this.stationName = value; }
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region protected methods
|
|
|
|
protected void Read()
|
|
{
|
|
while (runReader)
|
|
{
|
|
try
|
|
{
|
|
string line = this.port.ReadLine();
|
|
this.OnInputLineRead(line);
|
|
}
|
|
catch (Exception) { }
|
|
}
|
|
}
|
|
|
|
protected void OnInputLineRead(string line)
|
|
{
|
|
if (this.LineRead != null)
|
|
this.LineRead(line);
|
|
}
|
|
|
|
#endregion
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|