using System; using System.IO.Ports; using System.Threading.Tasks; 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; /// /// Filed After Run() is called. /// 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; /// /// Run the service. Catch one communication to WaterMetrologyData field. /// 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; } } } }