Refactor `NfcHanler` namespace to `NfcHandler` and enhance code consistency.
109 lines
2.6 KiB
C#
109 lines
2.6 KiB
C#
using System.IO.Ports;
|
|
using NfcC7_DLL.NfcHandler.Protocols;
|
|
using NfcC7_DLL.NfcHandler.Utils;
|
|
|
|
namespace NfcC7_DLL.NfcHandler
|
|
{
|
|
public class OptoHeadService
|
|
{
|
|
|
|
public class Con
|
|
{
|
|
public string com = "COM5";
|
|
public int baudrate = 38400;
|
|
public int dataBits = 8;
|
|
public Parity parity = Parity.None;
|
|
public StopBits stopbits = StopBits.Two;
|
|
public int readTimeout = 5000;
|
|
public int writeTimeout = 1000;
|
|
}
|
|
|
|
private Con Connection { get; set; }
|
|
private SERIAL_Driver driver;
|
|
/// <summary>
|
|
/// Filed After Run() is called.
|
|
/// </summary>
|
|
public WaterMetrologyData WaterMetrologyData { get; private set; }
|
|
|
|
public OptoHeadService(Con con)
|
|
{
|
|
Connection = con;
|
|
driver = new SERIAL_Driver();
|
|
}
|
|
|
|
public bool CreateSerialConnection()
|
|
{
|
|
bool isopen = false;
|
|
Con con = Connection;
|
|
|
|
byte[] message = {0x00};
|
|
byte[] bytesReceived;
|
|
|
|
if (!driver.isOpen())
|
|
{
|
|
|
|
isopen = driver.OpenConnection(
|
|
con.com,
|
|
con.baudrate,
|
|
con.dataBits,
|
|
con.parity,
|
|
con.stopbits,
|
|
con.readTimeout,
|
|
con.writeTimeout);
|
|
}
|
|
|
|
return isopen;
|
|
}
|
|
|
|
public void CloseSerialConnection()
|
|
{
|
|
dissableRunLoop = true;
|
|
driver.Close();
|
|
}
|
|
|
|
public void RunLoop()
|
|
{
|
|
Task.Run(() => Run());
|
|
}
|
|
|
|
|
|
private bool dissableRunLoop = false;
|
|
/// <summary>
|
|
/// Run the service. Catch one communication to WaterMetrologyData field.
|
|
/// </summary>
|
|
public void Run()
|
|
{
|
|
while (!dissableRunLoop)
|
|
{
|
|
WaterMetrologyData = ParseData(RunReading());
|
|
}
|
|
|
|
}
|
|
|
|
byte[] RunReading()
|
|
{
|
|
if (driver.isOpen())
|
|
{
|
|
driver.SendMessage(new byte[] {0x00}, 1);
|
|
return driver.GetRawData();
|
|
}
|
|
else
|
|
{
|
|
dissableRunLoop = true;
|
|
}
|
|
|
|
return new byte[] {0xFF};
|
|
}
|
|
|
|
public WaterMetrologyData ParseData(byte[] data)
|
|
{
|
|
try
|
|
{
|
|
return WaterMetrologyData.Parse(data, DateTime.Now, "");
|
|
}catch(Exception e)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
}
|
|
} |