OmronV640Serial.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. try
  49. {
  50. do
  51. {
  52. if (_port.Open())
  53. {
  54. EV.PostInfoLog(Module, $"Connected with {Module}.{Name} .");
  55. CheckToPostMessage((int)CIDMsg.StartInit, null);
  56. break;
  57. }
  58. else
  59. {
  60. EV.PostInfoLog(Module, $"Can't connected with {Module}.{Name},retry time {retry}.");
  61. //_port.Close();
  62. Thread.Sleep(sleep * 1000);
  63. }
  64. if (count > 0 && retry++ > count)
  65. {
  66. EV.PostAlarmLog(Module, $"Can't connect to {Module}.{Name}.");
  67. break;
  68. }
  69. } while (true);
  70. }
  71. catch(Exception ex)
  72. {
  73. LOG.Write(ex);
  74. }
  75. }
  76. private void _port_OnErrorHappened(string obj)
  77. {
  78. ;
  79. }
  80. private void _port_OnDataChanged(string package)
  81. {
  82. try
  83. {
  84. package = package.ToUpper();
  85. string[] msgs = Regex.Split(package, "\r");
  86. foreach (string msg in msgs)
  87. {
  88. if (msg.Length > 0)
  89. {
  90. string type = msg.Substring(0, 2);
  91. if (type != "00")
  92. {
  93. EV.PostAlarmLog("RFID", $"{Name} occurred error:{getErrMsg(type)}");
  94. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  95. {
  96. OnCarrierIDReadFailed(type);
  97. }
  98. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  99. {
  100. OnCarrierIDWriteFailed(type);
  101. }
  102. return;
  103. }
  104. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  105. {
  106. string msgdata = msg.Substring(2, msg.Length - 2);
  107. CarrierIDBeRead = HEX2ASCII(msg).Trim('\0');
  108. if (CarrierIDBeRead.Contains("\0"))
  109. CarrierIDBeRead = CarrierIDBeRead.Split('\0')[0];
  110. if (IsNeedTrimSpace)
  111. {
  112. CarrierIDBeRead = CarrierIDBeRead.Trim();
  113. }
  114. OnCarrierIDRead(CarrierIDBeRead);
  115. }
  116. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  117. {
  118. OnCarrierIDWrite();
  119. }
  120. }
  121. }
  122. }
  123. catch (Exception ex)
  124. {
  125. LOG.Write(ex);
  126. }
  127. }
  128. public string Address { get; set; }
  129. public bool IsConnected => _port.IsOpen();
  130. public bool Connect()
  131. {
  132. return _port.Open();
  133. }
  134. public bool Disconnect()
  135. {
  136. return _port.Close();
  137. }
  138. protected override bool fStartWriteCarrierID(object[] param)
  139. {
  140. try
  141. {
  142. _startTime = DateTime.Now;
  143. CarrierIDToBeWriten = param[0].ToString();
  144. int offset = 0;
  145. int length = 16;
  146. if (param.Length == 3)
  147. {
  148. offset = (int)param[1];
  149. length = (int)param[2];
  150. }
  151. string msgdata = string.Format("{0}{1}{2}\r", "0200", GetPage(offset + 1, length), ASCII2HEX(CarrierIDToBeWriten, length));
  152. return _port.Write(msgdata);
  153. }
  154. catch (Exception ex)
  155. {
  156. LOG.Write(ex);
  157. return false;
  158. }
  159. }
  160. protected override bool fStartReadCarrierID(object[] param)
  161. {
  162. try
  163. {
  164. _startTime = DateTime.Now;
  165. int offset = 0;
  166. int length = 16;
  167. if (param != null)
  168. {
  169. offset = (int)param[0];
  170. length = (int)param[1];
  171. }
  172. string msgdata = string.Format("{0}{1}\r", "0100", GetPage(offset + 1, length));
  173. return _port.Write(msgdata);
  174. }
  175. catch (Exception ex)
  176. {
  177. LOG.Write(ex);
  178. return false;
  179. }
  180. }
  181. protected override bool fMonitorReadCarrierID(object[] param)
  182. {
  183. IsBusy = false;
  184. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  185. {
  186. OnCarrierIDReadFailed("Timeout");
  187. return true;
  188. }
  189. return base.fMonitorReadCarrierID(param);
  190. }
  191. protected override bool fMonitorWriteCarrierID(object[] param)
  192. {
  193. IsBusy = false;
  194. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(10))
  195. {
  196. OnCarrierIDWriteFailed("Timeout");
  197. return true;
  198. }
  199. return base.fMonitorReadCarrierID(param);
  200. }
  201. private string getErrMsg(string error)
  202. {
  203. string msg = "";
  204. switch (error)
  205. {
  206. case "14":
  207. msg = "Format error There is a mistake in the command format";
  208. break;
  209. case "70":
  210. msg = "Communications error Noise or another hindrance occurs during communications with an ID Tag, and communications cannot be completed normally.";
  211. break;
  212. case "71":
  213. msg = "Verification error Correct data cannot be written to an ID Tag";
  214. break;
  215. case "72":
  216. 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";
  217. break;
  218. case "7B":
  219. 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";
  220. break;
  221. case "7E":
  222. msg = "ID system error (1) The ID Tag is in a status where it cannot execute command processing";
  223. break;
  224. case "7F":
  225. msg = "ID system error (2) An inapplicable ID Tag has been used";
  226. break;
  227. case "9A":
  228. msg = "Hardware error in CPU An error occurred when writing to EEPROM.";
  229. break;
  230. }
  231. return msg;
  232. }
  233. public string HEX2ASCII(string hex)
  234. {
  235. string res = String.Empty;
  236. try
  237. {
  238. for (int a = 0; a < hex.Length; a = a + 2)
  239. {
  240. string Char2Convert = hex.Substring(a, 2);
  241. int n = Convert.ToInt32(Char2Convert, 16);
  242. char c = (char)n;
  243. res += c.ToString();
  244. }
  245. }
  246. catch (Exception e)
  247. {
  248. LOG.Write(e);
  249. }
  250. return res;
  251. }
  252. private string GetPage(int startpage, int length)
  253. {
  254. double dpage = 0;
  255. for (int i = 0; i < length; i++)
  256. {
  257. dpage = dpage + Math.Pow(2, startpage + 1 + i);
  258. }
  259. string pageret = String.Format("{0:X}", Convert.ToInt32(dpage));
  260. for (int j = pageret.Length; j < 8; j++)
  261. {
  262. pageret = "0" + pageret;
  263. }
  264. return pageret;
  265. }
  266. private string ASCII2HEX(string src,int length)
  267. {
  268. while (src.Length < length * 8)
  269. {
  270. src = src + '\0';
  271. }
  272. if (src.Length > length * 8)
  273. {
  274. src = src.Substring(0, length * 8);
  275. LOG.Write($"RFID support max {(length * 8).ToString()} characters");
  276. }
  277. string res = String.Empty;
  278. try
  279. {
  280. char[] charValues = src.ToCharArray();
  281. string hexOutput = "";
  282. foreach (char _eachChar in charValues)
  283. {
  284. // Get the integral value of the character.
  285. int value = Convert.ToInt32(_eachChar);
  286. // Convert the decimal value to a hexadecimal value in string form.
  287. hexOutput += String.Format("{0:X2}", value);
  288. // to make output as your eg
  289. // hexOutput +=" "+ String.Format("{0:X}", value);
  290. }
  291. return hexOutput;
  292. }
  293. catch (Exception e)
  294. {
  295. LOG.Write(e);
  296. }
  297. return res;
  298. }
  299. }
  300. }