CometRFMatch.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Ports;
  4. using System.Linq;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Aitex.Core.Common;
  8. using Aitex.Core.Common.DeviceData;
  9. using Aitex.Core.RT.DataCenter;
  10. using Aitex.Core.RT.Device;
  11. using Aitex.Core.RT.Device.Unit;
  12. using Aitex.Core.RT.Event;
  13. using Aitex.Core.RT.Log;
  14. using Aitex.Core.RT.OperationCenter;
  15. using Aitex.Core.RT.SCCore;
  16. using Aitex.Core.Util;
  17. using MECF.Framework.Common.Communications;
  18. using MECF.Framework.Common.Device.Bases;
  19. using MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Common;
  20. using Newtonsoft.Json;
  21. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.RFMatchs.Comet
  22. {
  23. public class CometRFMatch : RfMatchBase, IConnection
  24. {
  25. public string Address => Connection.Address;
  26. public override bool IsConnected => Connection.IsConnected && !_connection.IsCommunicationError;
  27. public bool Connect()
  28. {
  29. return _connection.Connect();
  30. }
  31. public bool Disconnect()
  32. {
  33. return _connection.Disconnect();
  34. }
  35. public string PortStatus { get; set; } = "Closed";
  36. private CometRFMatchConnection _connection;
  37. public CometRFMatchConnection Connection
  38. {
  39. get { return _connection; }
  40. }
  41. public override bool IsStable
  42. {
  43. get
  44. {
  45. if (_scStableCriteria == null || _scStableCriteria.DoubleValue == 0)
  46. return false;
  47. if (CapacitanceSetpoint == 0)
  48. return true;
  49. if (100 * Capacitance / CapacitanceSetpoint < _scStableCriteria.DoubleValue)
  50. _stableTimer.Stop();
  51. if (_stableTimer.IsIdle() && 100 * Capacitance / CapacitanceSetpoint >= _scStableCriteria.DoubleValue)
  52. _stableTimer.Start(_stableTime * 1000);
  53. return _stableTimer.IsTimeout();
  54. }
  55. }
  56. private int CapacitanceMaxValue => _scCapacitanceMaxValue != null ? _scCapacitanceMaxValue.IntValue : 0;
  57. private int CapacitanceMinValue => _scCapacitanceMinValue != null ? _scCapacitanceMinValue.IntValue : 0;
  58. private R_TRIG _trigError = new R_TRIG();
  59. private R_TRIG _trigCommunicationError = new R_TRIG();
  60. private R_TRIG _trigRetryConnect = new R_TRIG();
  61. private PeriodicJob _thread;
  62. private LinkedList<HandlerBase> _lstHandler = new LinkedList<HandlerBase>();
  63. private LinkedList<HandlerBase> _lstMonitorHandler = new LinkedList<HandlerBase>();
  64. //private DeviceTimer _QueryTimer = new DeviceTimer();
  65. //private readonly int _QueryInterval = 500;
  66. public List<IOResponse> IOResponseList { get; set; } = new List<IOResponse>();
  67. public Dictionary<int, string> ErrorCodeReference;
  68. private object _locker = new object();
  69. private SCConfigItem _scCapacitanceMaxValue;
  70. private SCConfigItem _scCapacitanceMinValue;
  71. private bool _isGotoCapCompleted = true;
  72. private const int _capacitanceSetpointMin = 5;//unit %
  73. private const int _capacitanceSetpointMax = 95;//unit %
  74. private double _RampInterval_Seconds = 0.5;
  75. private bool _enableLog;
  76. private string _address;
  77. private string _scRoot;
  78. public CometRFMatch(string module, string name, string scRoot) : base(module, name)
  79. {
  80. _scRoot = scRoot;
  81. }
  82. private void ResetPropertiesAndResponses()
  83. {
  84. foreach (var ioResponse in IOResponseList)
  85. {
  86. ioResponse.ResonseContent = null;
  87. ioResponse.ResonseRecievedTime = DateTime.Now;
  88. }
  89. }
  90. public override bool Initialize()
  91. {
  92. base.Initialize();
  93. ResetPropertiesAndResponses();
  94. _scCapacitanceMaxValue = SC.GetConfigItem($"{(!string.IsNullOrEmpty(_scRoot) ? _scRoot + "." : "")}{Module}.{Name}.CapacitanceMaxValue");
  95. _scCapacitanceMinValue = SC.GetConfigItem($"{(!string.IsNullOrEmpty(_scRoot) ? _scRoot + "." : "")}{Module}.{Name}.CapacitanceMinValue");
  96. _address = SC.GetStringValue($"{(!string.IsNullOrEmpty(_scRoot) ? _scRoot + "." : "")}{Module}.{Name}.Address");
  97. _enableLog = SC.GetValue<bool>($"{(!string.IsNullOrEmpty(_scRoot) ? _scRoot + "." : "")}{Module}.{Name}.EnableLogMessage");
  98. var item = SC.GetConfigItem($"{Module}.{Name}.CapRampIntervalSeconds");
  99. if (item != null)
  100. {
  101. double.TryParse(item.Default, out _RampInterval_Seconds);
  102. }
  103. _connection = new CometRFMatchConnection(_address);
  104. _connection.EnableLog(_enableLog);
  105. if (_connection.Connect())
  106. {
  107. PortStatus = "Open";
  108. EV.PostInfoLog(Module, $"{Module}.{Name} connected");
  109. }
  110. _lstMonitorHandler.AddLast(new CommetRFMatchGetActualCapHandler(this));
  111. _lstMonitorHandler.AddLast(new CommetRFMatchGetStatusHandler(this));
  112. _thread = new PeriodicJob(100, OnTimer, $"{Module}.{Name} MonitorHandler", true);
  113. //_QueryTimer.Start(_QueryInterval);
  114. ErrorCodeReference = new Dictionary<int, string>()
  115. {
  116. {0x00, "No error" },
  117. {0x01, "Overcurrent bridge A low side" },//ok: 0, error: 1
  118. {0x02, "Overcurrent bridge B low side" },//ok: 0, error: 1
  119. {0x04, "Overcurrent high side" },//ok: 0, error: 1
  120. {0x08, "Driver under voltage" },//ok: 0, error: 1
  121. {0x10, "Over temperature" },//ok: 0, overtemp: 1
  122. {0x20, "Reset indicator" },//ok: 0, reset actuated: 1
  123. };
  124. DATA.Subscribe($"{Module}.{Name}.IsConnected", () => IsConnected);
  125. DATA.Subscribe($"{Module}.{Name}.Address", () => Address);
  126. OP.Subscribe($"{Module}.{Name}.Reconnect", (string cmd, object[] args) =>
  127. {
  128. Disconnect();
  129. Connect();
  130. return true;
  131. });
  132. return true;
  133. }
  134. private bool OnTimer()
  135. {
  136. try
  137. {
  138. _connection.MonitorTimeout();
  139. if (!_connection.IsConnected || _connection.IsCommunicationError)
  140. {
  141. lock (_locker)
  142. {
  143. _lstHandler.Clear();
  144. }
  145. _trigRetryConnect.CLK = !_connection.IsConnected;
  146. if (_trigRetryConnect.Q)
  147. {
  148. _connection.SetPortAddress(SC.GetStringValue($"{(!string.IsNullOrEmpty(_scRoot) ? _scRoot + "." : "")}{Module}.{Name}.Address"));
  149. if (!_connection.Connect())
  150. {
  151. EV.PostAlarmLog(Module, $"Can not connect with {_connection.Address}, {Module}.{Name}");
  152. }
  153. else
  154. {
  155. //_lstHandler.AddLast(new CommetRFMatchQueryPinHandler(this, _deviceAddress));
  156. //_lstHandler.AddLast(new CommetRFMatchSetCommModeHandler(this, _deviceAddress, EnumRfPowerCommunicationMode.Host));
  157. }
  158. }
  159. return true;
  160. }
  161. HandlerBase handler = null;
  162. if (!_connection.IsBusy)
  163. {
  164. lock (_locker)
  165. {
  166. if (_lstHandler.Count == 0)
  167. {
  168. if (!_isGotoCapCompleted)
  169. _lstHandler.AddLast(new CommetRFMatchCheckGotoCapCompleteHandler(this));
  170. foreach (var monitorHandler in _lstMonitorHandler)
  171. {
  172. _lstHandler.AddLast(monitorHandler);
  173. }
  174. //if (_QueryTimer.IsTimeout())
  175. //{
  176. // _lstHandler.AddLast(new CommetRFMatchGetActualCapHandler(this));
  177. // _lstHandler.AddLast(new CommetRFMatchGetStatusHandler(this));
  178. // _QueryTimer.Start(_QueryInterval);
  179. //}
  180. }
  181. if (_lstHandler.Count > 0)
  182. {
  183. handler = _lstHandler.First.Value;
  184. _lstHandler.RemoveFirst();
  185. }
  186. }
  187. if (handler != null)
  188. {
  189. _connection.Execute(handler);
  190. }
  191. }
  192. }
  193. catch (Exception ex)
  194. {
  195. LOG.Write(ex);
  196. }
  197. return true;
  198. }
  199. internal void NoteNAK()
  200. {
  201. TriggerNAK = true;
  202. }
  203. public override void Monitor()
  204. {
  205. try
  206. {
  207. //_connection.EnableLog(_enableLog);
  208. _trigCommunicationError.CLK = _connection.IsCommunicationError;
  209. if (_trigCommunicationError.Q)
  210. {
  211. EV.PostAlarmLog(Module, $"{Module}.{Name} communication error, {_connection.LastCommunicationError}");
  212. }
  213. base.Monitor();
  214. }
  215. catch (Exception ex)
  216. {
  217. LOG.Write(ex);
  218. }
  219. }
  220. public override void Reset()
  221. {
  222. _trigError.RST = true;
  223. _connection.SetCommunicationError(false, "");
  224. _trigCommunicationError.RST = true;
  225. //_enableLog = SC.GetValue<bool>($"{ScBasePath}.{Name}.EnableLogMessage");
  226. _trigRetryConnect.RST = true;
  227. base.Reset();
  228. }
  229. #region Command Functions
  230. public void PerformRawCommand(string command, string completeEvent, string comandArgument)
  231. {
  232. lock (_locker)
  233. {
  234. _lstHandler.AddLast(new CommetRFMatchRawCommandHandler(this, command, completeEvent, comandArgument));
  235. }
  236. }
  237. internal void NoteActualCap(float value)
  238. {
  239. Capacitance = 100 * (value - CapacitanceMinValue) / (CapacitanceMaxValue - CapacitanceMinValue);
  240. }
  241. public void TriggerFullRefRun()
  242. {
  243. lock (_locker)
  244. {
  245. _lstHandler.AddLast(new CommetRFMatchTriggerFullRefRunHandler(this));
  246. }
  247. }
  248. protected float _rampTargetCap;
  249. protected bool _isLastSetCap = false;
  250. public void SetLastSetCap() { _isLastSetCap = true; }
  251. public bool IsLastSetCap => _isLastSetCap;
  252. public override bool SetCapacitance(float cap, out string reason)
  253. {
  254. return SetCapacitance(cap, 1, out reason);
  255. }
  256. public override bool SetCapacitance(float cap, float rampTimes, out string reason)
  257. {
  258. LOG.Info($"{Module}.{Name} Start SetCapacitance Target Cap={cap}, ramp times={rampTimes}");
  259. _isLastSetCap = false;
  260. reason = string.Empty;
  261. if (!_isGotoCapCompleted)
  262. {
  263. reason = $"last command set capacitance is not finished";
  264. return false;
  265. }
  266. if (cap < _capacitanceSetpointMin || cap > _capacitanceSetpointMax)
  267. {
  268. reason = $"set capacitance {cap} is not in the scope [{_capacitanceSetpointMin}, {_capacitanceSetpointMax}]";
  269. return false;
  270. }
  271. //_isGotoCapCompleted = false;
  272. float lastCap = CapacitanceSetpoint;
  273. CapacitanceSetpoint = cap;
  274. int times = (int)rampTimes;
  275. _rampTargetCap = (CapacitanceMaxValue - CapacitanceMinValue) * cap / 100 + CapacitanceMinValue;
  276. if (rampTimes > 1 && _RampInterval_Seconds > 0)
  277. {
  278. float rampInitCap = (CapacitanceMaxValue - CapacitanceMinValue) * lastCap / 100 + CapacitanceMinValue;
  279. //float rampInitCap = _rampTargetCap / rampTimes;
  280. Task.Run(() =>
  281. {
  282. for (int ii = 1; ii <= times; ii++)
  283. {
  284. if (ii == times)
  285. {
  286. lock (_locker)
  287. {
  288. LOG.Info($"{Module}.{Name} SetCap {_rampTargetCap} in {ii} times");
  289. _lstHandler.AddLast(new CommetRFMatchTriggerGotoCapHandler(this, _rampTargetCap, true));
  290. }
  291. }
  292. else
  293. {
  294. float toSendCap = (_rampTargetCap - rampInitCap) / rampTimes * ii + rampInitCap;
  295. lock (_locker)
  296. {
  297. LOG.Info($"{Module}.{Name} SetCap {toSendCap} in {ii} times");
  298. _lstHandler.AddLast(new CommetRFMatchTriggerGotoCapHandler(this, toSendCap, false));
  299. }
  300. }
  301. Thread.Sleep((int)(_RampInterval_Seconds * 1000));
  302. }
  303. });
  304. }
  305. else
  306. {
  307. _lstHandler.AddLast(new CommetRFMatchTriggerGotoCapHandler(this, _rampTargetCap, true));
  308. }
  309. return true;
  310. }
  311. public void SetAccelerationSpeedIndex(byte acceleration, byte speed)
  312. {
  313. lock (_locker)
  314. {
  315. _lstHandler.AddLast(new CommetRFMatchSetAccelerationSpeedIndexHandler(this, acceleration.ToString("X2") + "," + speed.ToString("X2")));
  316. }
  317. }
  318. public void SetAccelerationSpeedIndex(string acceleration, string speed)
  319. {
  320. lock (_locker)
  321. {
  322. _lstHandler.AddLast(new CommetRFMatchSetAccelerationSpeedIndexHandler(this, acceleration + "," + speed));
  323. }
  324. }
  325. public void GetActualCap(bool isSelected)
  326. {
  327. lock (_locker)
  328. {
  329. var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(CommetRFMatchGetActualCapHandler));
  330. if (isSelected)
  331. {
  332. if (!existHandlers.Any())
  333. _lstMonitorHandler.AddFirst(new CommetRFMatchGetActualCapHandler(this));
  334. }
  335. else
  336. {
  337. if (existHandlers.Any())
  338. {
  339. _lstMonitorHandler.Remove(existHandlers.First());
  340. }
  341. }
  342. }
  343. }
  344. internal void NoteFullRefRunCompleted()
  345. {
  346. FullRefRunCompleted = true;
  347. }
  348. public void MonitorRawCommand(bool isSelected, string command, string completeEvent, string comandArgument)
  349. {
  350. lock (_locker)
  351. {
  352. var existHandlers = _lstMonitorHandler.Where(handler => handler.GetType() == typeof(CommetRFMatchRawCommandHandler) && ((CometRFMatchHandler)handler)._command == command);
  353. if (isSelected)
  354. {
  355. if (!existHandlers.Any())
  356. _lstMonitorHandler.AddFirst(new CommetRFMatchRawCommandHandler(this, command, completeEvent, comandArgument));
  357. }
  358. else
  359. {
  360. if (existHandlers.Any())
  361. {
  362. _lstMonitorHandler.Remove(existHandlers.First());
  363. }
  364. }
  365. }
  366. }
  367. #endregion
  368. #region Properties
  369. public string Error { get; private set; }
  370. internal void NoteGotoCapCompleted()
  371. {
  372. _isGotoCapCompleted = true;
  373. }
  374. public bool TriggerNAK { get; private set; }
  375. public bool FullRefRunCompleted { get; private set; }
  376. public byte Acceleration { get; private set; }
  377. public byte SpeedIndex { get; private set; }
  378. #endregion
  379. #region Note Functions
  380. private R_TRIG _trigWarningMessage = new R_TRIG();
  381. public void NoteError(string reason)
  382. {
  383. if (reason != null)
  384. {
  385. _trigWarningMessage.CLK = true;
  386. if (_trigWarningMessage.Q)
  387. {
  388. EV.PostAlarmLog(Module, $"{Module}.{Name} error, {reason}");
  389. }
  390. Error = reason;
  391. }
  392. else
  393. {
  394. Error = null;
  395. }
  396. }
  397. internal void NoteRawCommandInfo(string command, string data)
  398. {
  399. //var curIOResponse = IOResponseList.Find(res => res.SourceCommandName == command);
  400. //if (curIOResponse != null)
  401. //{
  402. // IOResponseList.Remove(curIOResponse);
  403. //}
  404. //IOResponseList.Add(new IOResponse() { SourceCommand = command, ResonseContent = data, ResonseRecievedTime = DateTime.Now });
  405. }
  406. internal void NoteAccelerationSpeedIndex(string parameter)
  407. {
  408. var valueArray = parameter.Split(',');
  409. Acceleration = Convert.ToByte(valueArray[0], 16);
  410. SpeedIndex = Convert.ToByte(valueArray[1], 16);
  411. }
  412. #endregion
  413. }
  414. }