using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DIT.Framework.Module._01_SerialModules { public class EnergyMax_PowerMeter { #region Field private const char _LF = '\n'; private const char _CR = '\r'; //object objlock; private SerialPort m_serialport; private string m_recvdata; #endregion #region Property public SerialPort SerialPort { get { return m_serialport; } private set { m_serialport = value; } } public string RecvData { get { return m_recvdata; } private set { m_recvdata = value; } } #endregion #region Constructor public EnergyMax_PowerMeter() { this.SerialPort = new SerialPort(); } #endregion #region Method public bool Connect(string port, int timeout) { if (port == null) return false; if (this.SerialPort.IsOpen == false) { this.SerialPort.PortName = port; this.SerialPort.WriteTimeout = timeout; this.SerialPort.ReadTimeout = timeout; this.SerialPort.Open(); } if (this.SerialPort.IsOpen == false) return false; return true; } public void DisConnect() { if (this.SerialPort.IsOpen == false) return; this.SerialPort.Close(); } public bool Send(string cmd) { string data = ""; data = cmd + _CR + _LF; try { this.SerialPort.Write(data); } catch (Exception) { return false; } return true; } public bool SendWaitReceive(string cmd) { string data = ""; data = cmd + _CR + _LF; try { this.SerialPort.Write(data); if (this.Receive() == false) return false; } catch (Exception) { return false; } return true; } public bool Receive() { DateTime starttime; try { starttime = DateTime.Now; while (true) { if((DateTime.Now - starttime).TotalMilliseconds > this.SerialPort.ReadTimeout) { this.RecvData = "Empty"; break; } else { this.RecvData = this.SerialPort.ReadLine(); if (this.RecvData == null) continue; break; } } } catch (Exception) { return false; } return true; } #endregion } }