OmronV640Tcp.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using Aitex.Core.RT.Event;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.RT.SCCore;
  4. using Aitex.Core.Util;
  5. using MECF.Framework.Common.Communications;
  6. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.CarrierIDReaderBase;
  7. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts;
  8. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.LoadPorts.LoadPortBase;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.CarrierIdReaders.OmronV640
  17. {
  18. public class OmronV640Tcp:CIDReaderBaseDevice,IConnection
  19. {
  20. private string _scRoot;
  21. private DateTime _startTime;
  22. private int _retryTime;
  23. public OmronV640Tcp(string module,string name,string scRoot,LoadPortBaseDevice lp =null,int offset=0,int length=16,int readerIndex=1,bool isUpdateLPCid = true)
  24. :base(module,name,lp,readerIndex, isUpdateLPCid)
  25. {
  26. _scRoot = scRoot;
  27. _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  28. Offset = offset;
  29. Length = length;
  30. _socket = new AsyncSocket(_address);
  31. _socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataChanged);
  32. _socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHandler);
  33. ConnectionManager.Instance.Subscribe($"{Name}", this);
  34. //int connecttime = 0;
  35. //_socket.Connect(_address);
  36. Reset();
  37. }
  38. private void OnErrorHandler(ErrorEventArgs args)
  39. {
  40. if (!_socket.IsConnected)
  41. return;
  42. EV.PostWarningLog(Module, $"{Name} occurred error:{args.Reason}.");
  43. //if (_socket.IsConnected)
  44. // return;
  45. //else
  46. //{
  47. // _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  48. // _socket.Connect(_address);
  49. //}
  50. //OnError();
  51. }
  52. private bool _isEnableSendError
  53. {
  54. get
  55. {
  56. if (SC.ContainsItem($"{_scRoot}.{Name}.EnableSendError"))
  57. return SC.GetValue<bool>($"{_scRoot}.{Name}.EnableSendError");
  58. return true;
  59. }
  60. }
  61. private void OnDataChanged(string package)
  62. {
  63. try
  64. {
  65. Thread.Sleep(500);
  66. package = package.ToUpper();
  67. string[] msgs = Regex.Split(package, "\r");
  68. foreach (string msg in msgs)
  69. {
  70. if (msg.Length > 0)
  71. {
  72. string type = msg.Substring(0, 2);
  73. if (type != "00")
  74. {
  75. EV.PostWarningLog("RFID", $"{Name} occurred error:{getErrMsg(type)}");
  76. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  77. {
  78. if(_retryTime < RetryTime)
  79. {
  80. EV.PostInfoLog(Module, $"{Name} retry {_retryTime + 1} time to read RFID due to received error");
  81. _retryTime++;
  82. _socket.Write(_sendMsg);
  83. return;
  84. }
  85. if(_isEnableSendError)
  86. OnCarrierIDReadFailed(type);
  87. else
  88. {
  89. SerializableDictionary<string, object> dvid = new SerializableDictionary<string, object>();
  90. dvid["PORT_ID"] = ReaderOnLP != null?ReaderOnLP.PortID:0;
  91. dvid["PortID"] = ReaderOnLP != null ? ReaderOnLP.PortID : 0;
  92. dvid["PORT_CTGRY"] = ReaderOnLP != null ? ReaderOnLP.SpecPortName : "";
  93. dvid["CarrierType"] = ReaderOnLP != null ? ReaderOnLP.SpecCarrierType : ""; ;
  94. dvid["CarrierIndex"] = ReaderOnLP != null ? ReaderOnLP.InfoPadCarrierIndex : 0;
  95. dvid["InfoPadSensorIndex"] = ReaderOnLP != null ? ReaderOnLP.InfoPadSensorIndex : 0;
  96. EV.Notify("CARRIER_ID_READ_FAILED", dvid);
  97. OnActionDone();
  98. }
  99. }
  100. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  101. {
  102. if (_retryTime < RetryTime)
  103. {
  104. EV.PostInfoLog(Module, $"{Name} retry {_retryTime + 1} time to write RFID due to received error");
  105. _retryTime++;
  106. _socket.Write(_sendMsg);
  107. return;
  108. }
  109. OnCarrierIDWriteFailed(type);
  110. }
  111. return;
  112. }
  113. if (DeviceState == CIDReaderStateEnum.ReadCarrierID)
  114. {
  115. string msgdata = msg.Substring(2, msg.Length - 2);
  116. string tempID = HEX2ASCII(msg);
  117. tempID = tempID.Trim('\0');
  118. if (tempID.Contains("\0"))
  119. tempID = tempID.Split('\0')[0];
  120. CarrierIDBeRead = tempID;
  121. if (IsNeedTrimSpace)
  122. {
  123. CarrierIDBeRead = CarrierIDBeRead.Trim();
  124. }
  125. OnCarrierIDRead(CarrierIDBeRead);
  126. }
  127. if (DeviceState == CIDReaderStateEnum.WriteCarrierID)
  128. {
  129. OnCarrierIDWrite();
  130. }
  131. }
  132. }
  133. }
  134. catch (Exception ex)
  135. {
  136. LOG.Write(ex);
  137. }
  138. }
  139. protected override bool fStartReset(object[] param)
  140. {
  141. _reconnectTimes = 0;
  142. if (_socket.IsConnected)
  143. return true;
  144. else
  145. {
  146. _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  147. //_socket.Dispose();
  148. //_socket = new AsyncSocket(_address);
  149. //_socket.OnDataChanged += new AsyncSocket.MessageHandler(OnDataChanged);
  150. //_socket.OnErrorHappened += new AsyncSocket.ErrorHandler(OnErrorHandler);
  151. _socket.Connect(_address);
  152. }
  153. return true;
  154. }
  155. private int _reconnectTimes;
  156. protected override bool fMonitorReset(object[] param)
  157. {
  158. IsBusy = false;
  159. if (!_socket.IsConnected)
  160. {
  161. _reconnectTimes++;
  162. _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  163. EV.PostWarningLog(Module, $"{Name} start to re-connect to {_address} for {_reconnectTimes} time");
  164. _socket.Connect(_address);
  165. if (!_socket.IsConnected)
  166. {
  167. EV.PostWarningLog(Module, $"{Name} failed to re-connect to {_address} on {_reconnectTimes} time");
  168. if (_reconnectTimes >10)
  169. {
  170. return true;
  171. }
  172. Thread.Sleep(200);
  173. return false;
  174. }
  175. else
  176. {
  177. EV.PostInfoLog(Module, $"{Name} success to connect to {_address}");
  178. return true;
  179. }
  180. }
  181. return true;
  182. }
  183. protected override bool fStartReadCarrierID(object[] param)
  184. {
  185. try
  186. {
  187. _retryTime = 0;
  188. _startTime = DateTime.Now;
  189. int offset = 0;
  190. int length = 16;
  191. if (param != null)
  192. {
  193. offset = (int)param[0];
  194. length = (int)param[1];
  195. }
  196. CarrierIDStartPage = offset + 1;
  197. CarrierIDPageLength = length;
  198. EV.PostInfoLog(Module, $"{Name} Start to read RFID from startpage:{CarrierIDStartPage}.with length:{CarrierIDPageLength}");
  199. _sendMsg = string.Format("{0}{1}\r", "0100", GetPage(offset + 1, length));
  200. return _socket.Write(_sendMsg);
  201. }
  202. catch(Exception ex)
  203. {
  204. LOG.Write(ex);
  205. return false;
  206. }
  207. }
  208. protected override bool fStartWriteCarrierID(object[] param)
  209. {
  210. try
  211. {
  212. _startTime = DateTime.Now;
  213. _retryTime = 0;
  214. CarrierIDToBeWriten = param[0].ToString();
  215. int offset = 0;
  216. int length = 16;
  217. if (param.Length == 3)
  218. {
  219. offset = (int)param[1];
  220. length = (int)param[2];
  221. }
  222. CarrierIDStartPage = offset + 1;
  223. CarrierIDPageLength = length;
  224. EV.PostInfoLog(Module, $"{Name} start to write RFID:{CarrierIDToBeWriten} from startpage:{CarrierIDStartPage}.with length:{CarrierIDPageLength}");
  225. _sendMsg = string.Format("{0}{1}{2}\r", "0200", GetPage(offset+1, length), ASCII2HEX(CarrierIDToBeWriten,length));
  226. return _socket.Write(_sendMsg);
  227. }
  228. catch(Exception ex)
  229. {
  230. LOG.Write(ex);
  231. return false;
  232. }
  233. }
  234. protected override bool fMonitorReadCarrierID(object[] param)
  235. {
  236. IsBusy = false;
  237. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(ActionTimeLimit))
  238. {
  239. if (_retryTime < RetryTime)
  240. {
  241. EV.PostInfoLog(Module, $"{Name} retry {_retryTime + 1} time to read RFID due to no return message");
  242. _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  243. _socket.Connect(_address);
  244. Thread.Sleep(500);
  245. _socket.Write(_sendMsg);
  246. _retryTime++;
  247. _startTime = DateTime.Now;
  248. return false;
  249. }
  250. if (_isEnableSendError)
  251. OnCarrierIDReadFailed("Timeout");
  252. else
  253. {
  254. SerializableDictionary<string, object> dvid = new SerializableDictionary<string, object>();
  255. dvid["PORT_ID"] = ReaderOnLP != null ? ReaderOnLP.PortID : 0;
  256. dvid["PortID"] = ReaderOnLP != null ? ReaderOnLP.PortID : 0;
  257. dvid["PORT_CTGRY"] = ReaderOnLP != null ? ReaderOnLP.SpecPortName : "";
  258. dvid["CarrierType"] = ReaderOnLP != null ? ReaderOnLP.SpecCarrierType : ""; ;
  259. dvid["CarrierIndex"] = ReaderOnLP != null ? ReaderOnLP.InfoPadCarrierIndex : 0;
  260. dvid["InfoPadSensorIndex"] = ReaderOnLP != null ? ReaderOnLP.InfoPadSensorIndex : 0;
  261. EV.Notify("CARRIER_ID_READ_FAILED", dvid);
  262. }
  263. return true;
  264. }
  265. return base.fMonitorReadCarrierID(param);
  266. }
  267. protected override bool fMonitorWriteCarrierID(object[] param)
  268. {
  269. IsBusy = false;
  270. if (DateTime.Now - _startTime > TimeSpan.FromSeconds(ActionTimeLimit))
  271. {
  272. if(_retryTime < RetryTime)
  273. {
  274. EV.PostInfoLog(Module, $"{Name} Retry {_retryTime+1} time to write RFID:{CarrierIDToBeWriten} due to no return message");
  275. _address = SC.GetStringValue($"{_scRoot}.{Name}.Address");
  276. _socket.Connect(_address);
  277. Thread.Sleep(500);
  278. _socket.Write(_sendMsg);
  279. _retryTime++;
  280. _startTime = DateTime.Now;
  281. return false;
  282. }
  283. OnCarrierIDWriteFailed("Timeout");
  284. return true;
  285. }
  286. return base.fMonitorReadCarrierID(param);
  287. }
  288. private string _sendMsg;
  289. public string Address => _address;
  290. private string _address;
  291. private AsyncSocket _socket;
  292. public bool IsConnected =>_socket.IsConnected;
  293. public int Offset { get; private set; }
  294. public int Length { get; private set; }
  295. public bool Connect()
  296. {
  297. _socket.Connect(_address);
  298. return true;
  299. }
  300. public bool Disconnect()
  301. {
  302. _socket.Dispose();
  303. return true;
  304. }
  305. private string getErrMsg(string error)
  306. {
  307. string msg = "";
  308. switch (error)
  309. {
  310. case "14":
  311. msg = "Format error There is a mistake in the command format";
  312. break;
  313. case "70":
  314. msg = "Communications error Noise or another hindrance occurs during communications with an ID Tag, and communications cannot be completed normally.";
  315. break;
  316. case "71":
  317. msg = "Verification error Correct data cannot be written to an ID Tag";
  318. break;
  319. case "72":
  320. 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";
  321. break;
  322. case "7B":
  323. 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";
  324. break;
  325. case "7E":
  326. msg = "ID system error (1) The ID Tag is in a status where it cannot execute command processing";
  327. break;
  328. case "7F":
  329. msg = "ID system error (2) An inapplicable ID Tag has been used";
  330. break;
  331. case "9A":
  332. msg = "Hardware error in CPU An error occurred when writing to EEPROM.";
  333. break;
  334. default:
  335. msg = "Unknow error.";
  336. break;
  337. }
  338. return msg;
  339. }
  340. public string HEX2ASCII(string hex)
  341. {
  342. string res = String.Empty;
  343. try
  344. {
  345. for (int a = 0; a < hex.Length; a = a + 2)
  346. {
  347. string Char2Convert = hex.Substring(a, 2);
  348. int n = Convert.ToInt32(Char2Convert, 16);
  349. char c = (char)n;
  350. res += c.ToString();
  351. }
  352. }
  353. catch (Exception e)
  354. {
  355. LOG.Write(e);
  356. }
  357. return res;
  358. }
  359. private string GetPage(int startpage, int length)
  360. {
  361. double dpage = 0;
  362. for (int i = 0; i < length; i++)
  363. {
  364. dpage = dpage + Math.Pow(2, startpage + 1 + i);
  365. }
  366. string pageret = String.Format("{0:X}", Convert.ToInt32(dpage));
  367. for (int j = pageret.Length; j < 8; j++)
  368. {
  369. pageret = "0" + pageret;
  370. }
  371. return pageret;
  372. }
  373. private string ASCII2HEX(string src,int length)
  374. {
  375. while (src.Length < length * 8)
  376. {
  377. src = src + '\0';
  378. }
  379. if (src.Length > length * 8)
  380. {
  381. src = src.Substring(0, length * 8);
  382. LOG.Write($"RFID support max {(length * 8).ToString()} characters");
  383. }
  384. string res = String.Empty;
  385. try
  386. {
  387. char[] charValues = src.ToCharArray();
  388. string hexOutput = "";
  389. foreach (char _eachChar in charValues)
  390. {
  391. // Get the integral value of the character.
  392. int value = Convert.ToInt32(_eachChar);
  393. // Convert the decimal value to a hexadecimal value in string form.
  394. hexOutput += String.Format("{0:X2}", value);
  395. // to make output as your eg
  396. // hexOutput +=" "+ String.Format("{0:X}", value);
  397. }
  398. return hexOutput;
  399. }
  400. catch (Exception e)
  401. {
  402. LOG.Write(e);
  403. }
  404. return res;
  405. }
  406. public override void Terminate()
  407. {
  408. _socket.Dispose();
  409. }
  410. }
  411. }