MicrowareRF.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using System.Threading.Tasks;
  9. using Aitex.Core.Common.DeviceData;
  10. using Aitex.Core.RT.DataCenter;
  11. using Aitex.Core.RT.Device;
  12. using Aitex.Core.RT.Event;
  13. using Aitex.Core.RT.IOCore;
  14. using Aitex.Core.RT.Log;
  15. using Aitex.Core.RT.OperationCenter;
  16. using Aitex.Core.RT.SCCore;
  17. using Aitex.Core.RT.Tolerance;
  18. using Aitex.Core.Util;
  19. using MECF.Framework.Common.Communications;
  20. using MECF.Framework.Common.DataCenter;
  21. using MECF.Framework.Common.Device.Bases;
  22. using MECF.Framework.Common.Equipment;
  23. namespace JetVirgoPM.Devices
  24. {
  25. static class MicrowareRFCommand
  26. {
  27. public const ushort PowerOnOrOff = 0x0080; //1:开 0:关 RW
  28. public const ushort RFPowerOnOrOff = 0x0081; //1:开 0:关 RW
  29. public const ushort PowerSetPoint = 0x0082; //功率设定值(W) RW
  30. public const ushort State = 0x008C; //设备故障 R
  31. public const ushort Reset = 0x009F; //清除异常 RW
  32. public const ushort Warning = 0x00A0; //整机预警 R
  33. public const ushort ForwardPower = 0x00A1; //整机输出功率 R
  34. public const ushort ReflectedPower = 0x00B2; //整机反射功率 R
  35. }
  36. class MicrowareRF : RfPowerBase
  37. {
  38. // ----------------------------Fields--------------------------
  39. //
  40. private int Write_INTERVAL = 400;
  41. private readonly DeviceTimer _timerWriteStatus = new DeviceTimer();
  42. private int QUERY_INTERVAL = 5000;
  43. private double _total;
  44. private double _fromLast;
  45. private bool _bRFPowerOn = false;
  46. private readonly AsyncSerialPort _serial;
  47. private readonly DeviceTimer _timerQueryStatus = new DeviceTimer();
  48. private readonly DeviceTimer _timerTotal = new DeviceTimer();
  49. private readonly DeviceTimer _timerFromLast = new DeviceTimer();
  50. private readonly DeviceTimer _timerRFTurnOn = new DeviceTimer();
  51. private DateTime _powerOnStartTime;
  52. private TimeSpan _powerOnElapsedTime;
  53. private readonly RD_TRIG _rfOnTrigger = new RD_TRIG();
  54. private readonly R_TRIG _ErrTrigger = new R_TRIG();
  55. private readonly R_TRIG _trigPMNeeded = new R_TRIG();
  56. private readonly RD_TRIG _trigOnOff = new RD_TRIG();
  57. private ToleranceChecker _alarmChecker;
  58. private ToleranceChecker _warningChecker;
  59. private ToleranceChecker _checkerReflectPower;
  60. private readonly double _scPowerAlarmTime;
  61. private readonly double _scPowerAlarmRange;
  62. private readonly double _scPowerWarningTime;
  63. private readonly double _scPowerWarningRange;
  64. private readonly double _scReflectPowerAlarmTime;
  65. private readonly double _scReflectPowerAlarmRange;
  66. private readonly double _scPowerRange;
  67. private readonly DIAccessor _diIntlk;
  68. private StatsDataItemRFAndPump _statRFOnTime;
  69. private ushort _currentCommandNumber = 0;
  70. private byte[] _sendData;
  71. private Queue<ushort> _readCommand;
  72. private GeneratorStatus PreStatus { get; set; }
  73. private ushort _setPowerFlag { get; set; }
  74. private ushort _stateErrorFlag { get; set; }
  75. private ushort _warningErrorFlag { get; set; }
  76. // --------------------------Properties------------------------
  77. //
  78. protected float _recipeAlarmRange;
  79. protected float _recipeWarningRange;
  80. protected int _recipeIgnoreTimeMS;
  81. protected ToleranceChecker _recipeAlarmChecker = new ToleranceChecker();
  82. protected ToleranceChecker _recipeWarningChecker = new ToleranceChecker();
  83. protected DeviceTimer _recipeIgnoreTimer = new DeviceTimer();
  84. public bool ConnectedStatus { get; set; }
  85. public override float ScalePower => (float)_scPowerRange;
  86. public GeneratorStatus Status { get; private set; }
  87. public string LastPMTime
  88. {
  89. get
  90. {
  91. return _statRFOnTime != null ? _statRFOnTime.LastPMTime.ToString() : "";
  92. }
  93. }
  94. public double DaysFromLastPM
  95. {
  96. get
  97. {
  98. return _statRFOnTime == null ? 0 : _statRFOnTime.fromLastPM;
  99. }
  100. set
  101. {
  102. if (_statRFOnTime != null)
  103. _statRFOnTime.fromLastPM = value;
  104. }
  105. }
  106. public double TotalDays
  107. {
  108. get
  109. {
  110. return _statRFOnTime != null ? _statRFOnTime.Total : 0;
  111. }
  112. set
  113. {
  114. if (_statRFOnTime != null)
  115. _statRFOnTime.Total = value;
  116. }
  117. }
  118. public double PMIntervalDays
  119. {
  120. get
  121. {
  122. return _statRFOnTime != null ? _statRFOnTime.PMInterval : 0;
  123. }
  124. }
  125. public bool IsPMNeeded
  126. {
  127. get
  128. {
  129. return DaysFromLastPM > PMIntervalDays;
  130. }
  131. }
  132. public bool EnableAlarm
  133. {
  134. get
  135. {
  136. return _statRFOnTime == null || _statRFOnTime.AlarmEnable;
  137. }
  138. }
  139. public override bool IsPowerOn
  140. {
  141. get => Status == GeneratorStatus.ON;
  142. set { }
  143. }
  144. public override bool IsError
  145. {
  146. get => Status == GeneratorStatus.ERROR;
  147. set { }
  148. }
  149. [Subscription("PowerOnTime")]
  150. public string PowerOnTime
  151. {
  152. get
  153. {
  154. if (_bRFPowerOn)
  155. _powerOnElapsedTime = DateTime.Now - _powerOnStartTime;
  156. return $"{(int)_powerOnElapsedTime.TotalHours:00}:{_powerOnElapsedTime.Minutes:00}:{(_powerOnElapsedTime.Seconds > 0 ? (_powerOnElapsedTime.Seconds + 1) : 0):00}";
  157. }
  158. }
  159. public bool RFInterlock => _diIntlk == null || _diIntlk.Value;
  160. private float _forwardPower;
  161. public override float ForwardPower
  162. {
  163. get
  164. {
  165. return _forwardPower;
  166. }
  167. set
  168. {
  169. _forwardPower = CalibrationData(value, false);
  170. }
  171. }
  172. public new AITRfData DeviceData =>
  173. new AITRfData
  174. {
  175. Module = Module,
  176. DeviceName = Name,
  177. ScalePower = ScalePower,
  178. ForwardPower = ForwardPower,
  179. ReflectPower = ReflectPower,
  180. MatchPositionC1 = CLoad,
  181. MatchPositionC2 = CTune,
  182. IsRfOn = IsPowerOn,
  183. PowerSetPoint = PowerSetPoint,
  184. PowerOnElapsedTime = PowerOnTime,
  185. IsInterlockOk = RFInterlock,
  186. WorkMode = (int)RfMode.ContinuousWaveMode,
  187. DisplayName = "Microware RF",
  188. };
  189. // --------------------------Constructor-----------------------
  190. //
  191. public MicrowareRF(ModuleName mod, string name) : base(mod.ToString(), name)
  192. {
  193. var portNum = SC.GetStringValue($"{mod}.{name}.Port");
  194. this.Status = GeneratorStatus.Unknown;
  195. this.PreStatus = this.Status;
  196. this._stateErrorFlag = 0;
  197. this._warningErrorFlag = 0;
  198. _serial = new AsyncSerialPort(portNum, 9600, 8, System.IO.Ports.Parity.None, System.IO.Ports.StopBits.One, "\r\r", false);
  199. _scPowerAlarmTime = SC.GetValue<double>($"{Module}.{Name}.PowerAlarmTime");
  200. _scPowerAlarmRange = SC.GetValue<double>($"{Module}.{Name}.PowerAlarmRange");
  201. _scPowerWarningTime = SC.GetValue<double>($"{Module}.{Name}.PowerWarningTime");
  202. _scPowerWarningRange = SC.GetValue<double>($"{Module}.{Name}.PowerWarningRange");
  203. _scReflectPowerAlarmTime = SC.GetValue<double>($"{Module}.{Name}.ReflectPowerAlarmTime");
  204. _scReflectPowerAlarmRange = SC.GetValue<double>($"{Module}.{Name}.ReflectPowerAlarmRange");
  205. _scPowerRange = SC.GetValue<double>($"{Module}.{Name}.PowerRange");
  206. _scEnableCalibration = SC.GetConfigItem($"{Module}.{Name}.EnableCalibration");
  207. _scCalibrationTable = SC.GetConfigItem($"{Module}.{Name}.CalibrationTable");
  208. _scRFPhysicalMaxPower = SC.GetConfigItem($"{Module}.{Name}.RFPhysicalMaxPower");
  209. _scCurrentRFMaxPower = SC.GetConfigItem($"{Module}.{Name}.CurrentRFMaxPower");
  210. _serial.EnableLog = SC.GetValue<bool>($"{Module}.{Name}.EnableLog");
  211. _diIntlk = IO.DI[$"{Module}.DI_Generator_Hardware_Interlock"];
  212. }
  213. ~MicrowareRF()
  214. {
  215. _serial?.Close();
  216. }
  217. private void InitReadQueue()
  218. {
  219. _readCommand = new Queue<ushort>();
  220. _readCommand.Enqueue(MicrowareRFCommand.RFPowerOnOrOff);
  221. _readCommand.Enqueue(MicrowareRFCommand.PowerSetPoint);
  222. _readCommand.Enqueue(MicrowareRFCommand.State);
  223. _readCommand.Enqueue(MicrowareRFCommand.Reset);
  224. _readCommand.Enqueue(MicrowareRFCommand.Warning);
  225. _readCommand.Enqueue(MicrowareRFCommand.ForwardPower);
  226. _readCommand.Enqueue(MicrowareRFCommand.ReflectedPower);
  227. }
  228. public override bool Initialize()
  229. {
  230. base.Initialize();
  231. DATA.Subscribe($"{Module}.{Name}.DeviceData", () => DeviceData);
  232. OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetPowerOnOff}", (out string reason, int time, object[] param) =>
  233. {
  234. SetPowerOnOff(Convert.ToBoolean((string)param[0]), out reason);
  235. return true;
  236. });
  237. OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetPower}", (out string reason, int time, object[] param) =>
  238. {
  239. reason = "";
  240. ushort val = Convert.ToUInt16(param[0]);
  241. SetPower(val);
  242. return true;
  243. });
  244. OP.Subscribe($"{Module}.{Name}.{AITRfOperation.SetContinuousPower}", (out string reason, int time, object[] param) =>
  245. {
  246. reason = "";
  247. ushort val = Convert.ToUInt16(param[0]);
  248. SetPower(val);
  249. return true;
  250. });
  251. OP.Subscribe($"{Module}.{Name}.SetRecipeTolerance", (out string reason, int time, object[] param) =>
  252. {
  253. reason = string.Empty;
  254. _recipeIgnoreTimeMS = Convert.ToInt32(param[0]) * 1000;
  255. _recipeWarningRange = Convert.ToSingle(param[1]);
  256. _recipeAlarmRange = Convert.ToSingle(param[2]);
  257. _recipeAlarmChecker.RST = true;
  258. _recipeWarningChecker.RST = true;
  259. if (_recipeIgnoreTimeMS > 0)
  260. _recipeIgnoreTimer.Start(0);
  261. return true;
  262. });
  263. if (_serial.Open())
  264. {
  265. this.ConnectedStatus = true;
  266. _serial.OnBinaryDataChanged += SerialPortDataReceived;
  267. _serial.OnErrorHappened += SerialPortErrorOccurred;
  268. _setPowerFlag = 1;
  269. SendCmd(Mode.Write, MicrowareRFCommand.PowerOnOrOff, 1);
  270. InitReadQueue();
  271. }
  272. else
  273. {
  274. this.ConnectedStatus = false;
  275. EV.PostAlarmLog(this.Module, "Microware 射频发生器串口无法打开");
  276. return false;
  277. }
  278. _statRFOnTime = StatsDataManager.Instance.GetItemRFAndPump($"{Module}.{Name}.RfOnTime");
  279. _timerQueryStatus.Start(QUERY_INTERVAL);
  280. _alarmChecker = new ToleranceChecker(_scPowerAlarmTime);
  281. _warningChecker = new ToleranceChecker(_scPowerWarningTime);
  282. _checkerReflectPower = new ToleranceChecker(_scReflectPowerAlarmTime);
  283. _recipeAlarmChecker = new ToleranceChecker(0);
  284. _recipeWarningChecker = new ToleranceChecker(0);
  285. _timerWriteStatus.Start(Write_INTERVAL);
  286. //SetCommunicationMode(1);
  287. return true;
  288. }
  289. public override void Monitor()
  290. {
  291. if(_timerWriteStatus.IsTimeout())
  292. {
  293. this.WriteCommand();
  294. _timerWriteStatus.Start(Write_INTERVAL);
  295. }
  296. // 状态查询
  297. if (_timerQueryStatus.IsTimeout())
  298. {
  299. this.QueryCommand();
  300. _timerQueryStatus.Start(QUERY_INTERVAL);
  301. }
  302. // power on triggered
  303. _rfOnTrigger.CLK = IsPowerOn;
  304. if (_rfOnTrigger.R)
  305. {
  306. _total = TotalDays;
  307. _fromLast = DaysFromLastPM;
  308. _timerTotal.Start(0);
  309. _timerFromLast.Start(0);
  310. _alarmChecker.Reset(_scPowerAlarmTime);
  311. _warningChecker.Reset(_scPowerWarningTime);
  312. _checkerReflectPower.Reset(_scReflectPowerAlarmTime);
  313. }
  314. if (_rfOnTrigger.M)
  315. {
  316. TotalDays = _total + _timerTotal.GetElapseTime() / 1000 / 60 / 60;
  317. DaysFromLastPM = _fromLast + _timerFromLast.GetElapseTime() / 1000 / 60 / 60;
  318. //_checkerPower.Monitor(ForwardPower, PowerSetPoint - _scPowerAlarmRange, PowerSetPoint + _scPowerAlarmRange, _scPowerAlarmTime);
  319. //if (_checkerPower.Trig)
  320. //{
  321. // EV.PostAlarmLog($"{Module}",
  322. // $"{Display} Forward power {ForwardPower:0} out of range[{PowerSetPoint - _scPowerAlarmRange:0},{PowerSetPoint + _scPowerAlarmRange:0}] in {_scPowerAlarmTime:0} seconds");
  323. // SetPowerOnOff(false, out _);
  324. //}
  325. if (_recipeAlarmRange > 0 && _recipeAlarmRange / 100.0 * PowerSetPoint < _scPowerAlarmRange)
  326. {
  327. if (_recipeIgnoreTimer.GetElapseTime() > _recipeIgnoreTimeMS)
  328. {
  329. _recipeAlarmChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint), PowerSetPoint + Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint), _scPowerAlarmTime);
  330. if (_recipeAlarmChecker.Trig)
  331. {
  332. EV.PostAlarmLog(Module, Display + $" Microware ForwardPower={ForwardPower }, PowerSetPoint ={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint)},{PowerSetPoint + Math.Abs(_recipeAlarmRange / 100.0 * PowerSetPoint)}) in {_scPowerAlarmTime:0} seconds");
  333. SetPowerOnOff(false, out _);
  334. }
  335. }
  336. }
  337. else
  338. {
  339. _alarmChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_scPowerAlarmRange), PowerSetPoint + Math.Abs(_scPowerAlarmRange), _scPowerAlarmTime);
  340. if (_alarmChecker.Trig)
  341. {
  342. EV.PostAlarmLog(Module, Display + $" Microware ForwardPower={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({ PowerSetPoint - Math.Abs(_scPowerAlarmRange)},{PowerSetPoint + Math.Abs(_scPowerAlarmRange)}) in {_scPowerAlarmTime:0} seconds");
  343. }
  344. }
  345. if (_recipeWarningRange > 0 && _recipeWarningRange / 100.0 * PowerSetPoint < _scPowerWarningRange)
  346. {
  347. if (_recipeIgnoreTimer.GetElapseTime() > _recipeIgnoreTimeMS)
  348. {
  349. _recipeWarningChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint), PowerSetPoint + Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint), _scPowerWarningTime);
  350. if (_recipeWarningChecker.Trig)
  351. {
  352. EV.PostWarningLog(Module, Display + $" Microware ForwardPower={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint)},{PowerSetPoint + Math.Abs(_recipeWarningRange / 100.0 * PowerSetPoint)}) in {_scPowerWarningTime:0} seconds");
  353. }
  354. }
  355. }
  356. else
  357. {
  358. _warningChecker.Monitor(ForwardPower, PowerSetPoint - Math.Abs(_scPowerWarningRange), PowerSetPoint + Math.Abs(_scPowerWarningRange), _scPowerWarningTime);
  359. if (_warningChecker.Trig)
  360. {
  361. EV.PostWarningLog(Module, Display + $" Microware Pressure={ForwardPower}, PowerSetPoint={PowerSetPoint} out of tolerance({PowerSetPoint - Math.Abs(_scPowerWarningRange)},{PowerSetPoint + Math.Abs(_scPowerWarningRange)}) in {_scPowerWarningTime:0} seconds");
  362. }
  363. }
  364. _checkerReflectPower.Monitor(ReflectPower, double.MinValue, _scReflectPowerAlarmRange, _scReflectPowerAlarmTime);
  365. if (_checkerReflectPower.Trig)
  366. {
  367. EV.PostAlarmLog($"{Module}",
  368. $" Microware {Display} Reflect power {ReflectPower:0} out of range[0,{_scReflectPowerAlarmRange:0}] in {_scReflectPowerAlarmTime:0} seconds");
  369. SetPowerOnOff(false, out _);
  370. }
  371. }
  372. if (PMIntervalDays > 0)
  373. {
  374. _trigPMNeeded.CLK = IsPMNeeded;
  375. if (_trigPMNeeded.Q)
  376. {
  377. if (EnableAlarm)
  378. {
  379. EV.PostAlarmLog($"{Module}", $"Microware {Module} {Name} rf on time value larger than setting interval days");
  380. }
  381. }
  382. }
  383. if (_rfOnTrigger.T)
  384. StatsDataManager.Instance.Increase($"{Module}.{Name}.RfOnTime", $"{Module} {Name} RfOnTime", DaysFromLastPM, TotalDays);
  385. if (!_rfOnTrigger.CLK)
  386. {
  387. ForwardPower = 0;
  388. ReflectPower = 0;
  389. }
  390. // 通信 checking, 2 second 一次
  391. //if (_timerComm.IsTimeout() && !_bQueryComm)
  392. //{
  393. // this.SendCmd(AdTecRfMessage.CHK_COMM);
  394. // _bQueryComm = true;
  395. // _timerComm.Start(CHK_COMM_INTERVAL);
  396. //}
  397. // RF Turn On & Off Timeout Check
  398. _trigOnOff.CLK = _bRFPowerOn;
  399. if (_trigOnOff.R) //RF Turn On
  400. {
  401. _timerRFTurnOn.Start(SC.GetValue<int>($"{Module}.{Name}.RFTurnOnTimeout") * 1000);
  402. }
  403. if (_trigOnOff.M) //RF Stay On
  404. {
  405. if (_timerRFTurnOn.IsTimeout())
  406. {
  407. if (!IsPowerOn)
  408. {
  409. EV.PostAlarmLog($"{Module}", $"Microware {Module} {Name} Turn On Failed");
  410. _timerRFTurnOn.Stop();
  411. }
  412. }
  413. }
  414. if (_trigOnOff.T)
  415. {
  416. _timerRFTurnOn.Stop();
  417. }
  418. base.Monitor();
  419. }
  420. public override void Terminate()
  421. {
  422. _serial?.Close();
  423. }
  424. public override void Reset()
  425. {
  426. _rfOnTrigger.RST = true;
  427. _ErrTrigger.RST = true;
  428. _trigPMNeeded.RST = true;
  429. this.SetCommand(MicrowareRFCommand.Reset, 1);
  430. this.Status = GeneratorStatus.OFF;
  431. this.PreStatus = this.Status;
  432. this._stateErrorFlag = 0;
  433. this._warningErrorFlag = 0;
  434. _bRFPowerOn = false;
  435. }
  436. public void SetRfMode(RfMode mode)
  437. {
  438. throw new NotImplementedException();
  439. }
  440. public override float CLoad
  441. {
  442. get
  443. {
  444. string matchName = "";
  445. if (Name.StartsWith("Rf"))
  446. {
  447. matchName = Name.Replace("Rf", "match");
  448. }
  449. if (Name.StartsWith("BiasRf"))
  450. {
  451. matchName = Name + "Match";
  452. }
  453. if (SC.ContainsItem($"{Module}.{matchName}.EnableMatch") &&
  454. SC.GetValue<bool>($"{Module}.{matchName}.EnableMatch") &&
  455. SC.GetValue<int>($"{Module}.{matchName}.CommunicationType") == (int)CommunicationType.RS232 &&
  456. SC.GetValue<int>($"{Module}.{matchName}.MFG") == (int)MatchMFG.AdTec)
  457. {
  458. var match = DEVICE.GetDevice<AdTecMatch>($"{Module}.{matchName}");
  459. if (match != null)
  460. return match.TunePosition1;
  461. }
  462. return 0;
  463. }
  464. }
  465. public override float CTune
  466. {
  467. get
  468. {
  469. string matchName = "";
  470. if (Name.StartsWith("Rf"))
  471. {
  472. matchName = Name.Replace("Rf", "match");
  473. }
  474. if (Name.StartsWith("BiasRf"))
  475. {
  476. matchName = Name + "Match";
  477. }
  478. if (SC.ContainsItem($"{Module}.{matchName}.EnableMatch") &&
  479. SC.GetValue<bool>($"{Module}.{matchName}.EnableMatch") &&
  480. SC.GetValue<int>($"{Module}.{matchName}.CommunicationType") == (int)CommunicationType.RS232 &&
  481. SC.GetValue<int>($"{Module}.{matchName}.MFG") == (int)MatchMFG.AdTec)
  482. {
  483. var match = DEVICE.GetDevice<AdTecMatch>($"{Module}.{matchName}");
  484. if (match != null)
  485. return match.TunePosition2;
  486. }
  487. return 0;
  488. }
  489. }
  490. //public override void SetCommunicationMode(int mode)
  491. //{
  492. // CommunicationType t1 = (CommunicationType)mode;
  493. // switch (t1)
  494. // {
  495. // case CommunicationType.Analogue:
  496. // this.SendCmd(AdTecRfMessage.ANALOG);
  497. // break;
  498. // case CommunicationType.RS232:
  499. // this.SendCmd(AdTecRfMessage.RS232);
  500. // break;
  501. // default:
  502. // throw new ArgumentOutOfRangeException("Communication mode error");
  503. // }
  504. //}
  505. public override void SetPower(float val)
  506. {
  507. //if (!(this.ControlMode == EnumRfPowerControlMode.RS232Mode)) SetCommunicationMode(1);
  508. ushort a = !_scEnableCalibration.BoolValue ? (ushort)val : (ushort)CalibrationData(val, true);
  509. //if (SendCmd($"{a:D4}{AdTecRfMessage.SET_POWER}"))
  510. if(SetCommand(MicrowareRFCommand.PowerSetPoint, a))
  511. {
  512. PowerSetPoint = val;
  513. }
  514. }
  515. public override bool SetPowerOnOff(bool on, out string str)
  516. {
  517. if (!(this.ControlMode == EnumRfPowerControlMode.RS232Mode)) SetCommunicationMode(1);
  518. str = "";
  519. if (on)
  520. {
  521. SetCommand(MicrowareRFCommand.RFPowerOnOrOff, 1);
  522. _bRFPowerOn = true;
  523. _powerOnStartTime = DateTime.Now;
  524. QUERY_INTERVAL = 500;
  525. }
  526. else
  527. {
  528. SetCommand(MicrowareRFCommand.RFPowerOnOrOff, 0);
  529. _bRFPowerOn = false;
  530. ForwardPower = 0;
  531. ReflectPower = 0;
  532. QUERY_INTERVAL = 500;
  533. _ErrTrigger.RST = true;
  534. }
  535. _timerQueryStatus.Start(QUERY_INTERVAL);
  536. return true;
  537. }
  538. //----------------------------------Private Method-------------------------------
  539. //
  540. private void SerialPortDataReceived(byte[] receiveContent)
  541. {
  542. if (receiveContent == null || receiveContent.Length == 0)
  543. {
  544. EV.PostAlarmLog(Module, $"{Module} {Name} Microware 无数据反馈");
  545. return;
  546. }
  547. //string str2 = str.Trim('\r');
  548. //if (str2 == AdTecRfMessage.ERR_RES)
  549. //{
  550. // EV.PostWarningLog(Module, $"AdTEC 收到 [{str2}]");
  551. // return;
  552. //}
  553. //try
  554. //{
  555. // //LOG.Info($"{Module} Generator rec [{str2}]");
  556. // Match match1 = Regex.Match(str2, INFO_PATTERN);
  557. // if (!match1.Success)
  558. // {
  559. // LOG.Write($"{Module}, AdTec 数据格式错误");
  560. // return;
  561. // }
  562. // string[] str1 =
  563. // {
  564. // match1.Groups[1].Value,
  565. // match1.Groups[2].Value,
  566. // match1.Groups[3].Value,
  567. // match1.Groups[4].Value,
  568. // match1.Groups[5].Value
  569. // };
  570. // this.ParseQueryData(str1);
  571. try
  572. {
  573. var addr = receiveContent[0];
  574. var functionCode = receiveContent[1];
  575. if(functionCode == 0x03)
  576. {
  577. _readTimeOut.TryRemove(_currentCommandNumber, out DateTime _);
  578. var len = receiveContent[2];
  579. var dh = receiveContent[3];
  580. var dl = receiveContent[4];
  581. ushort data = BitConverter.ToUInt16(new byte[] { dl, dh }, 0 );
  582. ParseData(data, _currentCommandNumber);
  583. }
  584. else if(functionCode == 0x06)
  585. {
  586. var ah = receiveContent[2];
  587. var al = receiveContent[3];
  588. ushort address = BitConverter.ToUInt16(new byte[] { al,ah }, 0);
  589. var dh = receiveContent[4];
  590. var dl = receiveContent[5];
  591. ushort data = BitConverter.ToUInt16(new byte[] { dl, dh }, 0);
  592. ParseData(data, address);
  593. }
  594. }
  595. catch (Exception ex)
  596. {
  597. LOG.Write(ex);
  598. }
  599. }
  600. private void ParseData(ushort data, ushort cmd)
  601. {
  602. //_readCommand.Enqueue(MicrowareRFCommand.PowerOnOrOff);
  603. //_readCommand.Enqueue(MicrowareRFCommand.PowerSetPoint);
  604. //_readCommand.Enqueue(MicrowareRFCommand.State);
  605. //_readCommand.Enqueue(MicrowareRFCommand.Reset);
  606. //_readCommand.Enqueue(MicrowareRFCommand.Warning);
  607. //_readCommand.Enqueue(MicrowareRFCommand.ForwardPower);
  608. //_readCommand.Enqueue(MicrowareRFCommand.ReflectedPower);
  609. switch (cmd)
  610. {
  611. case MicrowareRFCommand.RFPowerOnOrOff:
  612. {
  613. if (PreStatus != Status) LOG.Info($"{Module} {Name} Microware Source Generator status change, data=[{data}]");
  614. Status = data == 1 ? GeneratorStatus.ON : data == 0 ? GeneratorStatus.OFF : GeneratorStatus.ERROR;
  615. PreStatus = Status;
  616. break;
  617. }
  618. case MicrowareRFCommand.PowerSetPoint:
  619. {
  620. break;
  621. }
  622. case MicrowareRFCommand.State:
  623. {
  624. if(data != 0 && _stateErrorFlag != data)
  625. {
  626. EV.PostAlarmLog(Module, $"{Module} {Name} Microware Source Generator error code [{data}] ");
  627. _stateErrorFlag = data;
  628. }
  629. break;
  630. }
  631. case MicrowareRFCommand.Reset:
  632. {
  633. break;
  634. }
  635. case MicrowareRFCommand.Warning:
  636. {
  637. if (data != 0 && _warningErrorFlag != data)
  638. {
  639. EV.PostWarningLog(Module, $"{Module} {Name} Microware Source Generator warning code " + data);
  640. _warningErrorFlag = data;
  641. }
  642. break;
  643. }
  644. case MicrowareRFCommand.ForwardPower:
  645. {
  646. this.ForwardPower = Convert.ToUInt64(data);
  647. break;
  648. }
  649. case MicrowareRFCommand.ReflectedPower:
  650. {
  651. this.ReflectPower = Convert.ToUInt64(data);
  652. break;
  653. }
  654. case MicrowareRFCommand.PowerOnOrOff:
  655. {
  656. if(_setPowerFlag != data)
  657. {
  658. EV.PostWarningLog(Module, $"{Module} {Name} Microware Source Generator power code " + data);
  659. _setPowerFlag = data;
  660. }
  661. break;
  662. }
  663. }
  664. }
  665. private void ParseQueryData(string[] strInfo)
  666. {
  667. //// Control mode
  668. //string s2 = strInfo[0].Substring(0, 1);
  669. //this.ControlMode = (EnumRfPowerControlMode)Convert.ToUInt16(s2);
  670. //// output mode
  671. //string s0 = strInfo[0].Substring(1, 1);
  672. //this.WorkMode = (EnumRfPowerWorkMode)Convert.ToUInt16(s0);
  673. //// ON/OFF
  674. //char s1 = strInfo[0][2];
  675. //if (s1 == '1')
  676. //{
  677. // Status = GeneratorStatus.ON;
  678. //}
  679. //else if (s1 == '0')
  680. //{
  681. // Status = GeneratorStatus.OFF;
  682. //}
  683. //// error code
  684. //string alarm = strInfo[0].Substring(5, 2);
  685. //byte errCode = Convert.ToByte(alarm);
  686. //_ErrTrigger.CLK = errCode > 0;
  687. //if (_ErrTrigger.Q)
  688. //{
  689. // string code = errCode == 1 ? "Ref Over" :
  690. // errCode == 2 ? "Ref Limit" :
  691. // errCode == 3 ? "Cur Over" :
  692. // errCode == 4 ? "Cur Limit" :
  693. // errCode == 5 ? "Temp Over" :
  694. // errCode == 6 ? "Temp Sensor Short" :
  695. // errCode == 7 ? "Temp Sensor Open" :
  696. // errCode == 8 ? "Sensor Error" :
  697. // errCode == 9 ? "Fwd Power Over" :
  698. // errCode == 10 ? "RF ON Timer" :
  699. // errCode == 11 ? "RS232C error" :
  700. // errCode == 12 ? "Amp Unbalance" :
  701. // errCode == 14 ? "Fan error" :
  702. // errCode == 15 ? "Coolant Error" :
  703. // errCode == 16 ? "Voltage Error" :
  704. // errCode == 17 ? "Fwd Power Down" :
  705. // errCode == 22 ? "PD Over" :
  706. // errCode == 23 ? "PD Limit" :
  707. // errCode == 26 ? "Dew Condensation" :
  708. // errCode == 29 ? "SW Failure" :
  709. // errCode == 99 ? "Safety Lock" : string.Empty;
  710. // if (!string.IsNullOrEmpty(code))
  711. // {
  712. // if (errCode == 99)
  713. // EV.PostInfoLog(Module, "Source Generator " + code);
  714. // else
  715. // EV.PostAlarmLog(Module, "Source Generator " + code);
  716. // }
  717. //}
  718. //// forward power
  719. //this.ForwardPower = Convert.ToUInt64(strInfo[2]);
  720. //// reflect power
  721. //this.ReflectPower = Convert.ToUInt64(strInfo[3]);
  722. }
  723. private void SerialPortErrorOccurred(string obj)
  724. {
  725. Status = GeneratorStatus.ERROR;
  726. this.PreStatus = this.Status;
  727. EV.PostAlarmLog(this.Module, $"{Module} {Name} Microware RF 串口出错, [{obj}]");
  728. }
  729. private ConcurrentDictionary<ushort, DateTime> _readTimeOut = new ConcurrentDictionary<ushort, DateTime>();
  730. private void QueryCommand()
  731. {
  732. if (!ConnectedStatus)
  733. return;
  734. if(_readTimeOut.Count == 0)
  735. {
  736. var readCommand = _readCommand.Dequeue();
  737. ReadCommand(readCommand, 0);
  738. _readCommand.Enqueue(readCommand);
  739. _currentCommandNumber = readCommand;
  740. _readTimeOut.TryAdd(_currentCommandNumber, DateTime.Now);
  741. }
  742. else
  743. {
  744. if(_readTimeOut.TryGetValue(_currentCommandNumber, out DateTime dateTime))
  745. {
  746. var ts = DateTime.Now - dateTime;
  747. if(ts.TotalSeconds < 1)
  748. {
  749. ReadCommand(_currentCommandNumber, 0);
  750. }
  751. else if(ts.TotalSeconds >= 2)
  752. {
  753. _readTimeOut.TryRemove(_currentCommandNumber, out DateTime dateTime2);
  754. LOG.Info($"{Module} {Name} Microware command address=[{_currentCommandNumber}] read timeout(2s), first send time = [{dateTime2}] ");
  755. }
  756. }
  757. }
  758. }
  759. //private ConcurrentDictionary<ushort, ushort> _writeCommand = new ConcurrentDictionary<ushort, ushort>();
  760. private ConcurrentQueue<RFHelper> _writeCommand = new ConcurrentQueue<RFHelper>();
  761. private void WriteCommand()
  762. {
  763. if(_writeCommand.Count > 0)
  764. {
  765. if(_writeCommand.TryDequeue(out RFHelper comandAndArgument))
  766. {
  767. var command = comandAndArgument.Command;
  768. var argument = comandAndArgument.Argument;
  769. if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 0)
  770. {
  771. EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send off");
  772. }
  773. else if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 1)
  774. {
  775. EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send on");
  776. }
  777. else if (command == MicrowareRFCommand.PowerSetPoint)
  778. {
  779. EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send [{argument}W]");
  780. }
  781. else if (command == MicrowareRFCommand.PowerOnOrOff)
  782. {
  783. EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send, {(argument == 0 ? "power off" : "power on")}");
  784. }
  785. if (_serial.Write(BuildMessage(Mode.Write, command, argument)))
  786. {
  787. LOG.Info($" {Module} {Name} Send command=[{command}] value=[{argument}] and remove comand from list. ");
  788. }
  789. }
  790. }
  791. }
  792. private bool SetCommand(ushort command, ushort argument)
  793. {
  794. return SendCmd(Mode.Write, command, argument);
  795. }
  796. private bool ReadCommand(ushort command, ushort argument)
  797. {
  798. return SendCmd(Mode.Read, command, argument);
  799. }
  800. private bool SendCmd(Mode mode, ushort command, ushort argument)
  801. {
  802. if(mode == Mode.Write)
  803. {
  804. _writeCommand.Enqueue(new RFHelper() {Command = command,Argument = argument });
  805. //if (_writeCommand.AddOrUpdate(command, argument, (item1, item2) => argument) != argument)
  806. //{
  807. // EV.PostAlarmLog(this.Module, $"Microware {Module} {Name} command={command} value={argument} add command list failed ");
  808. // return false;
  809. //}
  810. return true;
  811. //if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 0)
  812. //{
  813. // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send off");
  814. //}
  815. //else if (command == MicrowareRFCommand.RFPowerOnOrOff && argument == 1)
  816. //{
  817. // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send on");
  818. //}
  819. //else if (command == MicrowareRFCommand.PowerSetPoint)
  820. //{
  821. // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send [{argument}W]");
  822. //}
  823. //else if(command == MicrowareRFCommand.PowerOnOrOff)
  824. //{
  825. // EV.PostInfoLog(Module, $"{Module} {Name} Microware RF send, {(argument == 0 ? "power off" : "power on")}");
  826. //}
  827. }
  828. return _serial.Write(BuildMessage(mode, command, argument));
  829. }
  830. protected byte[] BuildMessage(Mode mode, ushort commandNumber, ushort argumentNumber, byte readCount = 0x01)
  831. {
  832. List<byte> buffer = new List<byte>();
  833. buffer.Add(0x0A); //机器识别码
  834. if (mode == Mode.Read)
  835. {
  836. buffer.Add(0x03);
  837. }
  838. else if (mode == Mode.Write)
  839. {
  840. buffer.Add(0x06);
  841. }
  842. buffer.Add(BitConverter.GetBytes(commandNumber)[1]);
  843. buffer.Add(BitConverter.GetBytes(commandNumber)[0]);//起始地址
  844. if (mode == Mode.Read)
  845. {
  846. buffer.Add(0x00);
  847. buffer.Add(readCount);//读寄存器个数
  848. }
  849. else if (mode == Mode.Write)
  850. {
  851. buffer.Add(BitConverter.GetBytes(argumentNumber)[1]);
  852. buffer.Add(BitConverter.GetBytes(argumentNumber)[0]);
  853. }
  854. buffer.AddRange(CRC16(buffer.ToArray()));
  855. return buffer.ToArray();
  856. }
  857. public static byte[] CRC16(byte[] data)
  858. {
  859. ushort crc = 0xFFFF;
  860. for (int i = 0; i < data.Length; i++)
  861. {
  862. crc = (ushort)(crc ^ (data[i]));
  863. for (int j = 0; j < 8; j++)
  864. {
  865. crc = (crc & 1) != 0 ? (ushort)((crc >> 1) ^ 0xA001) : (ushort)(crc >> 1);
  866. }
  867. }
  868. byte hi = (byte)((crc & 0xFF00) >> 8); //高位置
  869. byte lo = (byte)(crc & 0x00FF); //低位置
  870. return new byte[] { hi, lo };
  871. }
  872. }
  873. public class RFHelper
  874. {
  875. public ushort Command { get; set; }
  876. public ushort Argument { get; set; }
  877. public DateTime SendTime { get; set; }
  878. }
  879. }