OmronV640Serial.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using Aitex.Core.RT.Event;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.RT.SCCore;
  4. using MECF.Framework.Common.Communications;
  5. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.CarrierIDReaderBase;
  6. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts.LoadPortBase;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO.Ports;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Text.RegularExpressions;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.OmronV640
  16. {
  17. public class OmronV640Serial : CIDReaderBaseDevice, IConnection
  18. {
  19. private string _scRoot;
  20. private string _portName;
  21. private bool _enableLog;
  22. private int _baudRate;
  23. private int _dataBits;
  24. private Parity _parity;
  25. private int _stopBits;
  26. private AsyncSerialPort _port;
  27. private DateTime _startTime;
  28. public OmronV640Serial(string module,string name,string scRoot,LoadPortBaseDevice lp =null,int readerIndex=1):base(module,name,lp,readerIndex)
  29. {
  30. _scRoot = scRoot;
  31. _portName = SC.GetStringValue($"{_scRoot}.{Name}.PortName");
  32. _enableLog = SC.GetValue<bool>($"{_scRoot}.{Name}.EnableLogMessage");
  33. _baudRate = SC.GetValue<int>($"{_scRoot}.{Name}.BaudRate");
  34. _dataBits = SC.GetValue<int>($"{_scRoot}.{Name}.DataBits");
  35. _parity = (Parity)Enum.Parse(typeof(Parity), SC.GetStringValue($"{_scRoot}.{Name}.Parity"));
  36. _stopBits = SC.GetValue<int>($"{_scRoot}.{Name}.StopBits");
  37. _port = new AsyncSerialPort(_portName, _baudRate, 8, Parity.Even, StopBits.One, "\r", true);
  38. _port.OnDataChanged += _port_OnDataChanged;
  39. _port.OnErrorHappened += _port_OnErrorHappened;
  40. _port.EnableLog = _enableLog;
  41. Address = _portName;
  42. ConnectionManager.Instance.Subscribe($"{Name}", this);
  43. int count = SC.ContainsItem("System.ComPortRetryCount") ? SC.GetValue<int>("System.ComPortRetryCount") : 5;
  44. int sleep = SC.ContainsItem("System.ComPortRetryDelayTime") ? SC.GetValue<int>("System.ComPortRetryDelayTime") : 2;
  45. if (sleep <= 0 || sleep > 10)
  46. sleep = 2;
  47. int retry = 0;
  48. do
  49. {
  50. if (_port.Open())
  51. {
  52. EV.PostInfoLog(Module, $"Connected with {Module}.{Name} .");
  53. CheckToPostMessage((int)CIDMsg.StartInit, null);
  54. break;
  55. }
  56. else
  57. {
  58. EV.PostInfoLog(Module, $"Can't connected with {Module}.{Name},retry time {retry}.");
  59. _port.Close();
  60. Thread.Sleep(sleep * 1000);
  61. }
  62. if (count > 0 && retry++ > count)
  63. {
  64. EV.PostAlarmLog(Module, $"Can't connect to {Module}.{Name}.");
  65. break;
  66. }
  67. } while (true);
  68. }
  69. private void _port_OnErrorHappened(string obj)
  70. {
  71. ;
  72. }
  73. private void _port_OnDataChanged(string package)
  74. {
  75. try
  76. {
  77. package = package.ToUpper();
  78. string[] msgs = Regex.Split(package, "\r");
  79. foreach (string msg in msgs)
  80. {
  81. if (msg.Length > 0)
  82. {
  83. string type = msg.Substring(0, 2);
  84. if (type != "00")
  85. {
  86. EV.PostAlarmLog("RFID", $"{Name} occurred error:{getErrMsg(type)}");
  87. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  88. {
  89. OnCarrierIDReadFailed(type);
  90. }
  91. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  92. {
  93. OnCarrierIDWriteFailed(type);
  94. }
  95. return;
  96. }
  97. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  98. {
  99. string msgdata = msg.Substring(2, msg.Length - 2);
  100. CarrierIDBeRead = HEX2ASCII(msg).Trim('\0');
  101. if (SC.ContainsItem("LoadPort.CarrierIdNeedTrimSpace") && SC.GetValue<bool>("LoadPort.CarrierIdNeedTrimSpace"))
  102. {
  103. CarrierIDBeRead = CarrierIDBeRead.Trim();
  104. }
  105. OnCarrierIDRead(CarrierIDBeRead);
  106. }
  107. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  108. {
  109. OnCarrierIDWrite();
  110. }
  111. }
  112. }
  113. }
  114. catch (Exception ex)
  115. {
  116. LOG.Write(ex);
  117. }
  118. }
  119. public string Address { get; set; }
  120. public bool IsConnected => _port.IsOpen();
  121. public bool Connect()
  122. {
  123. return _port.Open();
  124. }
  125. public bool Disconnect()
  126. {
  127. return _port.Close();
  128. }
  129. protected override bool fStartWriteCarrierID(object[] param)
  130. {
  131. try
  132. {
  133. _startTime = DateTime.Now;
  134. CarrierIDToBeWriten = param[0].ToString();
  135. int offset = 0;
  136. int length = 16;
  137. if (param.Length == 3)
  138. {
  139. offset = (int)param[1];
  140. length = (int)param[2];
  141. }
  142. string msgdata = string.Format("{0}{1}{2}\r", "0200", GetPage(offset + 1, length), ASCII2HEX(CarrierIDToBeWriten, length));
  143. return _port.Write(msgdata);
  144. }
  145. catch (Exception ex)
  146. {
  147. LOG.Write(ex);
  148. return false;
  149. }
  150. }
  151. protected override bool fStartReadCarrierID(object[] param)
  152. {
  153. try
  154. {
  155. _startTime = DateTime.Now;
  156. int offset = 0;
  157. int length = 16;
  158. if (param != null)
  159. {
  160. offset = (int)param[0];
  161. length = (int)param[1];
  162. }
  163. string msgdata = string.Format("{0}{1}\r", "0100", GetPage(offset + 1, length));
  164. return _port.Write(msgdata);
  165. }
  166. catch (Exception ex)
  167. {
  168. LOG.Write(ex);
  169. return false;
  170. }
  171. }
  172. protected override bool fMonitorReadCarrierID(object[] param)
  173. {
  174. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  175. {
  176. OnCarrierIDReadFailed("Timeout");
  177. return true;
  178. }
  179. return base.fMonitorReadCarrierID(param);
  180. }
  181. protected override bool fMonitorWriteCarrierID(object[] param)
  182. {
  183. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  184. {
  185. OnCarrierIDWriteFailed("Timeout");
  186. return true;
  187. }
  188. return base.fMonitorReadCarrierID(param);
  189. }
  190. private string getErrMsg(string error)
  191. {
  192. string msg = "";
  193. switch (error)
  194. {
  195. case "14":
  196. msg = "Format error There is a mistake in the command format";
  197. break;
  198. case "70":
  199. msg = "Communications error Noise or another hindrance occurs during communications with an ID Tag, and communications cannot be completed normally.";
  200. break;
  201. case "71":
  202. msg = "Verification error Correct data cannot be written to an ID Tag";
  203. break;
  204. case "72":
  205. msg = "No Tag error Either there is no ID Tag in front of the CIDRW Head, or the CIDRW Head is unable to detect the ID Tag due to environmental factors";
  206. break;
  207. case "7B":
  208. msg = "Outside write area error A write operation was not completed normally because the ID Tag was in an area in which the ID Tag could be read but not written";
  209. break;
  210. case "7E":
  211. msg = "ID system error (1) The ID Tag is in a status where it cannot execute command processing";
  212. break;
  213. case "7F":
  214. msg = "ID system error (2) An inapplicable ID Tag has been used";
  215. break;
  216. case "9A":
  217. msg = "Hardware error in CPU An error occurred when writing to EEPROM.";
  218. break;
  219. }
  220. return msg;
  221. }
  222. public string HEX2ASCII(string hex)
  223. {
  224. string res = String.Empty;
  225. try
  226. {
  227. for (int a = 0; a < hex.Length; a = a + 2)
  228. {
  229. string Char2Convert = hex.Substring(a, 2);
  230. int n = Convert.ToInt32(Char2Convert, 16);
  231. char c = (char)n;
  232. res += c.ToString();
  233. }
  234. }
  235. catch (Exception e)
  236. {
  237. LOG.Write(e);
  238. }
  239. return res;
  240. }
  241. private string GetPage(int startpage, int length)
  242. {
  243. double dpage = 0;
  244. for (int i = 0; i < length; i++)
  245. {
  246. dpage = dpage + Math.Pow(2, startpage + 1 + i);
  247. }
  248. string pageret = String.Format("{0:X}", Convert.ToInt32(dpage));
  249. for (int j = pageret.Length; j < 8; j++)
  250. {
  251. pageret = "0" + pageret;
  252. }
  253. return pageret;
  254. }
  255. private string ASCII2HEX(string src,int length)
  256. {
  257. while (src.Length < length * 8)
  258. {
  259. src = src + '\0';
  260. }
  261. if (src.Length > length * 8)
  262. {
  263. src = src.Substring(0, length * 8);
  264. LOG.Write($"RFID support max {(length * 8).ToString()} characters");
  265. }
  266. string res = String.Empty;
  267. try
  268. {
  269. char[] charValues = src.ToCharArray();
  270. string hexOutput = "";
  271. foreach (char _eachChar in charValues)
  272. {
  273. // Get the integral value of the character.
  274. int value = Convert.ToInt32(_eachChar);
  275. // Convert the decimal value to a hexadecimal value in string form.
  276. hexOutput += String.Format("{0:X2}", value);
  277. // to make output as your eg
  278. // hexOutput +=" "+ String.Format("{0:X}", value);
  279. }
  280. return hexOutput;
  281. }
  282. catch (Exception e)
  283. {
  284. LOG.Write(e);
  285. }
  286. return res;
  287. }
  288. }
  289. }