AsyncSerial.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. using System;
  2. using System.IO.Ports;
  3. using Aitex.Core.RT.Log;
  4. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts
  5. {
  6. public class AsyncSerial : ICommunication, IDisposable
  7. {
  8. public delegate void ErrorHandler(ErrorEventArgs args);
  9. public event ErrorHandler OnErrorHappened;
  10. public delegate void MessageHandler(string message);
  11. public event MessageHandler OnDataChanged;
  12. private static Object _locker = new Object();
  13. private SerialPort _port;
  14. private string _buff = "";
  15. public AsyncSerial(string name, int baudRate, int dataBits, Parity parity = Parity.None, StopBits stopBits = StopBits.One, string newline ="\r")
  16. {
  17. _port = new SerialPort();
  18. _port.PortName = name;
  19. _port.BaudRate = baudRate;
  20. _port.DataBits = dataBits;
  21. _port.Parity = parity;
  22. _port.StopBits = stopBits;
  23. _port.RtsEnable = false;
  24. _port.DtrEnable = false;
  25. _port.ReadTimeout = 1000;
  26. _port.WriteTimeout = 1000;
  27. _port.NewLine = newline;
  28. _port.Handshake = Handshake.None;
  29. _port.DataReceived += new SerialDataReceivedEventHandler(DataReceived);
  30. _port.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceived);
  31. }
  32. public void Dispose()
  33. {
  34. Close();
  35. }
  36. public bool Open()
  37. {
  38. if (_port.IsOpen) Close();
  39. try
  40. {
  41. _port.Open();
  42. _port.DiscardInBuffer();
  43. _port.DiscardOutBuffer();
  44. _buff = "";
  45. }
  46. catch (Exception e)
  47. {
  48. // LOG.Write($"Port open failed, {e.Message}");
  49. string reason = _port.PortName + " port open failed,please check configuration." + e.Message;
  50. //OnErrorHappened(new ErrorEventArgs(reason));
  51. LOG.Write(reason);
  52. return false;
  53. }
  54. return true;
  55. }
  56. public bool Open(int retryTime, int delayTime )
  57. {
  58. if (_port.IsOpen) Close();
  59. try
  60. {
  61. _port.Open();
  62. _port.DiscardInBuffer();
  63. _port.DiscardOutBuffer();
  64. _buff = "";
  65. }
  66. catch (Exception e)
  67. {
  68. LOG.Write($"Port open failed, {e.Message}");
  69. string reason = _port.PortName + " port open failed,please check configuration." + e.Message;
  70. OnErrorHappened(new ErrorEventArgs(reason));
  71. return false;
  72. }
  73. return true;
  74. }
  75. public bool IsOpen()
  76. {
  77. return _port.IsOpen;
  78. }
  79. public bool Close()
  80. {
  81. if (_port.IsOpen)
  82. {
  83. try
  84. {
  85. _port.Close();
  86. }
  87. catch (Exception e)
  88. {
  89. string reason = _port.PortName + " port close failed." + e.Message;
  90. OnErrorHappened(new ErrorEventArgs(reason));
  91. return false;
  92. }
  93. }
  94. return true;
  95. }
  96. public bool Write(string msg)
  97. {
  98. try
  99. {
  100. lock (_locker)
  101. {
  102. if (_port.IsOpen)
  103. {
  104. _port.Write(msg);
  105. if (msg.Contains("\r"))
  106. msg = msg.Replace("\r", "\\r");
  107. if (msg.Contains("\n"))
  108. msg = msg.Replace("\n", "\\n");
  109. LOG.Info(string.Format("Communication {0} Sent {1}.", _port.PortName, msg));
  110. }
  111. }
  112. return true;
  113. }
  114. catch (Exception e)
  115. {
  116. string reason = string.Format("Communication {0} Send {1} failed. {2}.", _port.PortName, msg, e.Message);
  117. LOG.Info(reason);
  118. OnErrorHappened(new ErrorEventArgs(reason));
  119. return false;
  120. }
  121. }
  122. public void DataReceived(object sender, SerialDataReceivedEventArgs e)
  123. {
  124. if (_port.IsOpen)
  125. {
  126. string str = _port.ReadExisting();//字符串方式读
  127. _buff += str;
  128. int index = _buff.LastIndexOf(_port.NewLine);
  129. if (index > 0)
  130. {
  131. index += _port.NewLine.Length;
  132. string msg = _buff.Substring(0,index);
  133. _buff = _buff.Substring(index);
  134. var raw = msg;
  135. if (raw.Contains("\r"))
  136. raw = raw.Replace("\r", "\\r");
  137. if (raw.Contains("\n"))
  138. raw = raw.Replace("\n", "\\n");
  139. LOG.Info(string.Format("Communication {0} Receive {1}.", _port.PortName, raw));
  140. OnDataChanged(msg);
  141. }
  142. }
  143. }
  144. void ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
  145. {
  146. string reason = string.Format("Communication {0} {1}.", _port.PortName, e.EventType.ToString());
  147. LOG.Error(reason);
  148. OnErrorHappened(new ErrorEventArgs(reason));
  149. }
  150. public void ClearPortBuffer()
  151. {
  152. _port.DiscardInBuffer();
  153. _port.DiscardOutBuffer();
  154. }
  155. }
  156. }