OmronV640Serial.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 (CarrierIDBeRead.Contains("\0"))
  102. CarrierIDBeRead = CarrierIDBeRead.Split('\0')[0];
  103. if (SC.ContainsItem("LoadPort.CarrierIdNeedTrimSpace") && SC.GetValue<bool>("LoadPort.CarrierIdNeedTrimSpace"))
  104. {
  105. CarrierIDBeRead = CarrierIDBeRead.Trim();
  106. }
  107. OnCarrierIDRead(CarrierIDBeRead);
  108. }
  109. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  110. {
  111. OnCarrierIDWrite();
  112. }
  113. }
  114. }
  115. }
  116. catch (Exception ex)
  117. {
  118. LOG.Write(ex);
  119. }
  120. }
  121. public string Address { get; set; }
  122. public bool IsConnected => _port.IsOpen();
  123. public bool Connect()
  124. {
  125. return _port.Open();
  126. }
  127. public bool Disconnect()
  128. {
  129. return _port.Close();
  130. }
  131. protected override bool fStartWriteCarrierID(object[] param)
  132. {
  133. try
  134. {
  135. _startTime = DateTime.Now;
  136. CarrierIDToBeWriten = param[0].ToString();
  137. int offset = 0;
  138. int length = 16;
  139. if (param.Length == 3)
  140. {
  141. offset = (int)param[1];
  142. length = (int)param[2];
  143. }
  144. string msgdata = string.Format("{0}{1}{2}\r", "0200", GetPage(offset + 1, length), ASCII2HEX(CarrierIDToBeWriten, length));
  145. return _port.Write(msgdata);
  146. }
  147. catch (Exception ex)
  148. {
  149. LOG.Write(ex);
  150. return false;
  151. }
  152. }
  153. protected override bool fStartReadCarrierID(object[] param)
  154. {
  155. try
  156. {
  157. _startTime = DateTime.Now;
  158. int offset = 0;
  159. int length = 16;
  160. if (param != null)
  161. {
  162. offset = (int)param[0];
  163. length = (int)param[1];
  164. }
  165. string msgdata = string.Format("{0}{1}\r", "0100", GetPage(offset + 1, length));
  166. return _port.Write(msgdata);
  167. }
  168. catch (Exception ex)
  169. {
  170. LOG.Write(ex);
  171. return false;
  172. }
  173. }
  174. protected override bool fMonitorReadCarrierID(object[] param)
  175. {
  176. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  177. {
  178. OnCarrierIDReadFailed("Timeout");
  179. return true;
  180. }
  181. return base.fMonitorReadCarrierID(param);
  182. }
  183. protected override bool fMonitorWriteCarrierID(object[] param)
  184. {
  185. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  186. {
  187. OnCarrierIDWriteFailed("Timeout");
  188. return true;
  189. }
  190. return base.fMonitorReadCarrierID(param);
  191. }
  192. private string getErrMsg(string error)
  193. {
  194. string msg = "";
  195. switch (error)
  196. {
  197. case "14":
  198. msg = "Format error There is a mistake in the command format";
  199. break;
  200. case "70":
  201. msg = "Communications error Noise or another hindrance occurs during communications with an ID Tag, and communications cannot be completed normally.";
  202. break;
  203. case "71":
  204. msg = "Verification error Correct data cannot be written to an ID Tag";
  205. break;
  206. case "72":
  207. 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";
  208. break;
  209. case "7B":
  210. 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";
  211. break;
  212. case "7E":
  213. msg = "ID system error (1) The ID Tag is in a status where it cannot execute command processing";
  214. break;
  215. case "7F":
  216. msg = "ID system error (2) An inapplicable ID Tag has been used";
  217. break;
  218. case "9A":
  219. msg = "Hardware error in CPU An error occurred when writing to EEPROM.";
  220. break;
  221. }
  222. return msg;
  223. }
  224. public string HEX2ASCII(string hex)
  225. {
  226. string res = String.Empty;
  227. try
  228. {
  229. for (int a = 0; a < hex.Length; a = a + 2)
  230. {
  231. string Char2Convert = hex.Substring(a, 2);
  232. int n = Convert.ToInt32(Char2Convert, 16);
  233. char c = (char)n;
  234. res += c.ToString();
  235. }
  236. }
  237. catch (Exception e)
  238. {
  239. LOG.Write(e);
  240. }
  241. return res;
  242. }
  243. private string GetPage(int startpage, int length)
  244. {
  245. double dpage = 0;
  246. for (int i = 0; i < length; i++)
  247. {
  248. dpage = dpage + Math.Pow(2, startpage + 1 + i);
  249. }
  250. string pageret = String.Format("{0:X}", Convert.ToInt32(dpage));
  251. for (int j = pageret.Length; j < 8; j++)
  252. {
  253. pageret = "0" + pageret;
  254. }
  255. return pageret;
  256. }
  257. private string ASCII2HEX(string src,int length)
  258. {
  259. while (src.Length < length * 8)
  260. {
  261. src = src + '\0';
  262. }
  263. if (src.Length > length * 8)
  264. {
  265. src = src.Substring(0, length * 8);
  266. LOG.Write($"RFID support max {(length * 8).ToString()} characters");
  267. }
  268. string res = String.Empty;
  269. try
  270. {
  271. char[] charValues = src.ToCharArray();
  272. string hexOutput = "";
  273. foreach (char _eachChar in charValues)
  274. {
  275. // Get the integral value of the character.
  276. int value = Convert.ToInt32(_eachChar);
  277. // Convert the decimal value to a hexadecimal value in string form.
  278. hexOutput += String.Format("{0:X2}", value);
  279. // to make output as your eg
  280. // hexOutput +=" "+ String.Format("{0:X}", value);
  281. }
  282. return hexOutput;
  283. }
  284. catch (Exception e)
  285. {
  286. LOG.Write(e);
  287. }
  288. return res;
  289. }
  290. }
  291. }