Ffu.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using Aitex.Core.RT.Device;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.RT.OperationCenter;
  4. using Aitex.Core.RT.Routine;
  5. using Aitex.Core.RT.SCCore;
  6. using Aitex.Core.Util;
  7. using athosRT.tool;
  8. using MECF.Framework.Common.Communications;
  9. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.OcrReaders.HST;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.IO.Ports;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. using System.Text;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using OP = Common.OP.OP;
  19. using DATA = Common.DataCenter.DATA;
  20. using FabConnect.SecsGemInterface.Application.Objects.ObjectService;
  21. namespace athosRT.Devices
  22. {
  23. public class Ffu : BaseDevice, IDevice, IConnection
  24. {
  25. private static SerialPort _port;
  26. private readonly object _locker = new object();
  27. private int _nMaxSpeed;
  28. public int NMaxSpeed => _nMaxSpeed;
  29. private int _ffuSpeed = 0;
  30. public int FFUSpeed
  31. {
  32. get
  33. {
  34. return _ffuSpeed;
  35. }
  36. set
  37. {
  38. _ffuSpeed = value;
  39. }
  40. }
  41. public Ffu(string module, string name, string station, string port)
  42. : base(module, name, name, "")
  43. {
  44. Ffu._port = new SerialPort()
  45. {
  46. PortName = port,
  47. BaudRate = 9600,
  48. DataBits = 8,
  49. Parity = Parity.None,
  50. StopBits = StopBits.One,
  51. RtsEnable = false,
  52. DtrEnable = false,
  53. ReadTimeout = 1000,
  54. WriteTimeout = 1000,
  55. NewLine = "\r",
  56. Handshake = Handshake.None
  57. };
  58. Ffu._port.DataReceived += new SerialDataReceivedEventHandler(this.OnDataChanged);
  59. Ffu._port.ErrorReceived += new SerialErrorReceivedEventHandler(this.OnErrorHandler);
  60. this.Initalized = false;
  61. this.Station = station;
  62. this.Address = port;
  63. //this.Initialize();
  64. }
  65. public static bool SpeedSet1 { get; private set; }
  66. public static bool SpeedSet2 { get; private set; }
  67. public string Station { get; }
  68. public bool Initalized { get; set; }
  69. public string Address { get; }
  70. public bool IsConnected => Ffu._port.IsOpen;
  71. public bool Connect()
  72. {
  73. Task.Factory.StartNew((Action)(() =>
  74. {
  75. int num1 = SC.ContainsItem("System.ComPortRetryCount") ? SC.GetValue<int>("System.ComPortRetryCount") : 3;
  76. int num2 = SC.ContainsItem("System.ComPortRetryDelayTime") ? SC.GetValue<int>("System.ComPortRetryDelayTime") : 2;
  77. if (num2 <= 0 || num2 > 10)
  78. num2 = 2;
  79. int num3 = 0;
  80. while (!this.Open())
  81. {
  82. if (num1 > 0 && num3++ > num1)
  83. {
  84. LogObject.Info(GetName.GetCurrentName(),"Retry connect " + this.Module + "." + this.Name + " stop retry.");
  85. EV.PostAlarmLog(this.Module, "Can't connect to " + this.Module + "." + this.Name + ".");
  86. return;
  87. }
  88. Thread.Sleep(num2 * 1000);//原本就有
  89. LogObject.Info(GetName.GetCurrentName(),string.Format("Retry connect {0}.{1} for the {2} time.", (object)this.Module, (object)this.Name, (object)(num3 + 1)));
  90. }
  91. EV.PostInfoLog(GetName.GetCurrentName(),this.Module, "Connected with " + this.Module + "." + this.Name + " .");
  92. }));
  93. return true;
  94. }
  95. public bool Disconnect() => true;
  96. private PeriodicJob _thread;
  97. public bool Initialize()
  98. {
  99. Singleton<ConnectionManager>.Instance.Subscribe(this.Name ?? "", (IConnection)this);
  100. _nMaxSpeed = SC.GetValue<int>("System.FFU.MaxSpeed");
  101. this.Connect();
  102. _thread = new PeriodicJob(1000, OnTimer, base.Name + " MonitorHandler", isStartNow: true);
  103. DATA.Subscribe(base.Name + ".FFUSpeed", () => _ffuSpeed);
  104. this.RegisterOperation();
  105. return true;
  106. }
  107. private bool OnTimer()
  108. {
  109. this.QuerySpeed();
  110. return true;
  111. }
  112. public void Monitor()
  113. {
  114. }
  115. public void Terminate() => this.Close();
  116. public void Reset()
  117. {
  118. }
  119. private void OnDataChanged(
  120. object sender,
  121. SerialDataReceivedEventArgs serialDataReceivedEventArgs)
  122. {
  123. try
  124. {
  125. if (!_port.IsOpen)
  126. return;
  127. BinaryDataReceived();
  128. }
  129. catch (Exception ex)
  130. {
  131. //LogObject.Error(GetName.GetCurrentName(), " " + this.Name + " has exception:" + ex.Message);
  132. }
  133. }
  134. public void BinaryDataReceived()
  135. {
  136. byte[] readBuffer = new byte[_port.BytesToRead];
  137. int readCount = _port.Read(readBuffer, 0, readBuffer.Length);
  138. if (readCount == 0)
  139. {
  140. //LOG.Write($"read zero length data, {_port.PortName}");
  141. return;
  142. }
  143. byte[] buffer = new byte[readCount];
  144. Buffer.BlockCopy(readBuffer, 0, buffer, 0, readCount);
  145. StringBuilder str = new StringBuilder(512);
  146. Array.ForEach(buffer, x => str.Append(x.ToString("X2") + " "));
  147. if (buffer[0] == 0x31)
  148. {
  149. if (buffer.Length >= 4)
  150. {
  151. FFUSpeed = ((int)buffer[3]) * NMaxSpeed / 250;
  152. Ffu.SpeedSet1 = true;
  153. // EV.PostInfoLog(this.Module, "FFU read speed "+ FFUSpeed+":" + str.ToString());
  154. }
  155. }
  156. else if (buffer[0] == 0x11)
  157. {
  158. EV.PostInfoLog(this.Module,"FFU's speed is successfully set:" +str.ToString());
  159. }
  160. //switch (buffer[0].ToString("X2"))
  161. //{
  162. // case "31":
  163. // if (buffer.Length >= 4) {
  164. // FFUSpeed =((int) buffer[3]) * NMaxSpeed / 250;
  165. // }
  166. // break;
  167. //}
  168. //
  169. }
  170. private void OnErrorHandler(
  171. object sender,
  172. SerialErrorReceivedEventArgs serialErrorReceivedEventArgs)
  173. {
  174. this.Initalized = false;
  175. EV.PostAlarmLog(this.Module, string.Format("{0} Communication error, {1}", (object)this.Display, (object)serialErrorReceivedEventArgs));
  176. }
  177. private void RegisterOperation()
  178. {
  179. OP.Subscribe(this.Name + ".SetSpeed", (Func<string, object[], bool>)((cmd, param) =>
  180. {
  181. int result= (int) param[0];
  182. //if (!int.TryParse((string)param[0], out result))
  183. //{
  184. // EV.PostWarningLogl(this.Module, "invalid speed.");
  185. // return false;
  186. //}
  187. this.StartAndSetSpeed(result);
  188. EV.PostInfoLog(this.Module, string.Format("{0} speed set to {1}", (object)this.Name, (object)result));
  189. return true;
  190. }));
  191. OP.Subscribe(this.Name + ".CheckSpeed", (Func<string, object[], bool>)((cmd, param) =>
  192. {
  193. this.QuerySpeed();
  194. EV.PostInfoLog(this.Module, "Query " + this.Name + " speed");
  195. return true;
  196. }));
  197. }
  198. public void StartAndSetSpeed(int speed)
  199. {
  200. lock (this._locker)
  201. {
  202. List<byte> baseBytes = new List<byte>() { 0x35, 0x41, 0x01 };
  203. int ffuspeed = speed * 250 / _nMaxSpeed;
  204. byte[] bytes = BitConverter.GetBytes(ffuspeed);
  205. baseBytes.Add(bytes[0]);
  206. baseBytes.Add(ModRTU_CRC(baseBytes.ToArray()));
  207. byte[] arr = baseBytes.ToArray();
  208. Ffu.SpeedSet1 = false;
  209. if (_port.IsOpen)
  210. {
  211. _port.Write(arr, 0, arr.Length);
  212. }
  213. }
  214. }
  215. public void QuerySpeed()
  216. {
  217. lock (this._locker)
  218. {
  219. List<byte> baseBytes = new List<byte>() { 0x15, 0x21, 0x01, 0xCA };
  220. byte[] arr = baseBytes.ToArray();
  221. //string array = "15 21 01 CA";
  222. if (_port.IsOpen)
  223. {
  224. _port.Write(arr, 0, arr.Length);
  225. // this.SendLog.AppendText(array + "\n");
  226. }
  227. }
  228. }
  229. public static string[] ParseSpeed(int speed)
  230. {
  231. byte[] bytes = BitConverter.GetBytes(speed);
  232. return new string[2]
  233. {
  234. bytes[1].ToString("X").Length < 2 ? string.Format("0{0:X}", (object) bytes[1]) : string.Format("{0:X}", (object) bytes[1]),
  235. bytes[0].ToString("X").Length < 2 ? string.Format("0{0:X}", (object) bytes[0]) : string.Format("{0:X}", (object) bytes[0])
  236. };
  237. }
  238. private bool Open()
  239. {
  240. lock (this._locker)
  241. {
  242. if (Ffu._port.IsOpen)
  243. this.Close();
  244. try
  245. {
  246. Ffu._port.Open();
  247. Ffu._port.DiscardInBuffer();
  248. Ffu._port.DiscardOutBuffer();
  249. }
  250. catch (Exception ex)
  251. {
  252. LogObject.Error(GetName.GetCurrentName(),Ffu._port.PortName + " port open failed,please check configuration。" + ex.Message);
  253. return false;
  254. }
  255. }
  256. return true;
  257. }
  258. private bool Close()
  259. {
  260. lock (this._locker)
  261. {
  262. if (Ffu._port.IsOpen)
  263. {
  264. try
  265. {
  266. Ffu._port.Close();
  267. }
  268. catch (Exception ex)
  269. {
  270. EV.PostInfoLog(this.Module, Ffu._port.PortName + " port close failed。" + ex.Message);
  271. return false;
  272. }
  273. }
  274. }
  275. return true;
  276. }
  277. private static byte ModRTU_CRC(byte[] buffer)
  278. {
  279. int num = buffer.Length;
  280. byte b = buffer[0];
  281. for (int i = 1; i < buffer.Length; i++)
  282. {
  283. b = (byte)(b ^ buffer[i]);
  284. }
  285. return (byte)(~b);
  286. }
  287. }
  288. }