MainViewModel.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Input;
  14. using System.Windows.Threading;
  15. using Aitex.Core.Account;
  16. using Aitex.Core.Common.DeviceData;
  17. using Aitex.Core.RT.Event;
  18. using Aitex.Core.RT.Log;
  19. using Aitex.Core.Util;
  20. using Aitex.Core.WCF;
  21. using Caliburn.Micro;
  22. using EfemDualUI.Views.History.ProcessHistory;
  23. using EfemDualUI.Views.PMs;
  24. using MECF.Framework.Common.Account.Extends;
  25. using MECF.Framework.Common.DataCenter;
  26. using MECF.Framework.Common.OperationCenter;
  27. using MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory;
  28. using MECF.Framework.UI.Client.CenterViews.LogOnOff;
  29. using MECF.Framework.UI.Client.ClientBase;
  30. using MECF.Framework.UI.Core.Accounts;
  31. using OpenSEMI.ClientBase;
  32. using OpenSEMI.ClientBase.Command;
  33. using OpenSEMI.ClientBase.Utility;
  34. using SciChart.Charting.ChartModifiers;
  35. using SciChart.Charting.Visuals;
  36. using SciChart.Charting.Visuals.Annotations;
  37. using SciChart.Charting.Visuals.Axes;
  38. using Cali = Caliburn.Micro.Core;
  39. using CalibrationTableViewModel = MECF.Framework.UI.Client.CenterViews.Maitenances.CalibrationTable.CalibrationTableViewModel;
  40. namespace EfemDualUI
  41. {
  42. public class TimeredMainViewModel : Cali.Conductor<Cali.Screen>.Collection.OneActive
  43. {
  44. PeriodicJob _timer;
  45. ConcurrentBag<string> _subscribedKeys = new ConcurrentBag<string>();
  46. Func<object, bool> _isSubscriptionAttribute;
  47. Func<MemberInfo, bool> _hasSubscriptionAttribute;
  48. public TimeredMainViewModel()
  49. {
  50. _timer = new PeriodicJob(1000, this.OnTimer, "UIUpdaterThread - " + GetType().Name);
  51. _isSubscriptionAttribute = attribute => attribute is SubscriptionAttribute;
  52. _hasSubscriptionAttribute = mi => mi.GetCustomAttributes(false).Any(_isSubscriptionAttribute);
  53. SubscribeKeys(this);
  54. }
  55. [StructLayout(LayoutKind.Sequential)]
  56. internal struct LASTINPUTINFO
  57. {
  58. [MarshalAs(UnmanagedType.U4)]
  59. public int cbSize;
  60. [MarshalAs(UnmanagedType.U4)]
  61. public int dwTime;
  62. }
  63. [DllImport("user32.dll")]
  64. internal static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
  65. /// <summary>
  66. /// 获取鼠标键盘不活动的时间
  67. /// </summary>
  68. /// <returns>结果</returns>
  69. public static int GetLastInputTime()
  70. {
  71. LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
  72. lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
  73. lastInputInfo.dwTime = 0;
  74. int idleTime = 0;
  75. if (GetLastInputInfo(ref lastInputInfo))
  76. {
  77. idleTime = Environment.TickCount - lastInputInfo.dwTime;
  78. }
  79. return ((idleTime > 0) ? (idleTime / 1000) : 0);
  80. }
  81. protected virtual bool OnTimer()
  82. {
  83. try
  84. {
  85. Poll();
  86. }
  87. catch (Exception ex)
  88. {
  89. LOG.Error(ex.Message);
  90. }
  91. return true;
  92. }
  93. public virtual void EnableTimer(bool enable)
  94. {
  95. if (enable) _timer.Start();
  96. else _timer.Pause();
  97. }
  98. protected virtual void Poll()
  99. {
  100. if (_subscribedKeys.Count > 0)
  101. {
  102. Dictionary<string, object> result = QueryDataClient.Instance.Service.PollData(_subscribedKeys);
  103. if (result == null)
  104. {
  105. LOG.Error("获取RT数据失败");
  106. return;
  107. }
  108. if (result.Count != _subscribedKeys.Count)
  109. {
  110. string unknowKeys = string.Empty;
  111. foreach (string key in _subscribedKeys)
  112. {
  113. if (!result.ContainsKey(key))
  114. {
  115. unknowKeys += key + "\r\n";
  116. }
  117. }
  118. //System.Diagnostics.Debug.Assert(false, unknowKeys);
  119. }
  120. InvokeBeforeUpdateProperty(result);
  121. UpdateValue(result);
  122. Application.Current.Dispatcher.Invoke(new System.Action(() =>
  123. {
  124. InvokePropertyChanged();
  125. InvokeAfterUpdateProperty(result);
  126. }));
  127. }
  128. }
  129. private void InvokePropertyChanged()
  130. {
  131. Refresh();
  132. }
  133. protected virtual void InvokeBeforeUpdateProperty(Dictionary<string, object> data)
  134. {
  135. }
  136. protected virtual void InvokeAfterUpdateProperty(Dictionary<string, object> data)
  137. {
  138. }
  139. void UpdateValue(Dictionary<string, object> data)
  140. {
  141. if (data == null)
  142. return;
  143. UpdateSubscribe(data, this);
  144. var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionModuleAttribute>() != null);
  145. foreach (var property in properties)
  146. {
  147. var moduleAttr = property.GetCustomAttribute<SubscriptionModuleAttribute>();
  148. UpdateSubscribe(data, property.GetValue(this), moduleAttr.Module);
  149. }
  150. }
  151. protected void Subscribe(string key)
  152. {
  153. if (!string.IsNullOrEmpty(key))
  154. {
  155. _subscribedKeys.Add(key);
  156. }
  157. }
  158. public void SubscribeKeys(TimeredMainViewModel target)
  159. {
  160. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  161. property =>
  162. {
  163. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  164. string key = subscription.ModuleKey;
  165. if (!_subscribedKeys.Contains(key))
  166. _subscribedKeys.Add(key);
  167. });
  168. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  169. method =>
  170. {
  171. SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  172. string key = subscription.ModuleKey;
  173. if (!_subscribedKeys.Contains(key))
  174. _subscribedKeys.Add(key);
  175. });
  176. }
  177. public void UpdateSubscribe(Dictionary<string, object> data, object target, string module = null)
  178. {
  179. Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
  180. property =>
  181. {
  182. PropertyInfo pi = (PropertyInfo)property;
  183. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  184. string key = subscription.ModuleKey;
  185. key = module == null ? key : string.Format("{0}.{1}", module, key);
  186. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  187. {
  188. try
  189. {
  190. var convertedValue = Convert.ChangeType(data[key], pi.PropertyType);
  191. var originValue = Convert.ChangeType(pi.GetValue(target, null), pi.PropertyType);
  192. if (originValue != convertedValue)
  193. {
  194. if (pi.Name == "PumpLimitSetPoint")
  195. pi.SetValue(target, convertedValue, null);
  196. else
  197. pi.SetValue(target, convertedValue, null);
  198. }
  199. }
  200. catch (Exception ex)
  201. {
  202. LOG.Error("由RT返回的数据更新失败" + key, ex);
  203. }
  204. }
  205. });
  206. Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
  207. property =>
  208. {
  209. FieldInfo pi = (FieldInfo)property;
  210. SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
  211. string key = subscription.ModuleKey;
  212. if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
  213. {
  214. try
  215. {
  216. var convertedValue = Convert.ChangeType(data[key], pi.FieldType);
  217. pi.SetValue(target, convertedValue);
  218. }
  219. catch (Exception ex)
  220. {
  221. LOG.Error("由RT返回的数据更新失败" + key, ex);
  222. }
  223. }
  224. });
  225. }
  226. }
  227. public class MainViewModel : TimeredMainViewModel
  228. {
  229. #region Menus
  230. public string NowDateTime { get; set; }
  231. private bool _IsLogin = false;
  232. public bool IsLogin
  233. {
  234. get { return _IsLogin; }
  235. set { _IsLogin = value; NotifyOfPropertyChange("IsLogin"); }
  236. }
  237. private List<Role> roles;
  238. public List<Role> Roles
  239. {
  240. get { return this.roles; }
  241. set { this.roles = value; this.RaisePropertyChangedEventImmediately("Roles"); }
  242. }
  243. private ICommand menuItemClickCommand;
  244. public ICommand MenuItemClickCommand
  245. {
  246. get
  247. {
  248. if (this.menuItemClickCommand == null)
  249. this.menuItemClickCommand = new BaseCommand<AppMenu>((AppMenu menuViewItem) => this.SwitchMenuItem(menuViewItem));
  250. return this.menuItemClickCommand;
  251. }
  252. }
  253. private ICommand mainmenuItemClickCommand;
  254. public ICommand MainMenuItemClickCommand
  255. {
  256. get
  257. {
  258. if (this.mainmenuItemClickCommand == null)
  259. this.mainmenuItemClickCommand = new BaseCommand<AppMenu>((AppMenu menuViewItem) => this.MainSwitchMenuItem(menuViewItem));
  260. return this.mainmenuItemClickCommand;
  261. }
  262. }
  263. public List<AppMenu> MenuItems
  264. {
  265. get { return this.menuItems; }
  266. set { this.menuItems = value; this.NotifyOfPropertyChange("MenuItems"); }
  267. }
  268. public List<AppMenu> SubMenuItems
  269. {
  270. get { return this.subMenuItems; }
  271. set { this.subMenuItems = value; this.NotifyOfPropertyChange("SubMenuItems"); }
  272. }
  273. public ObservableCollection<AppMenu> HistoryMenus
  274. {
  275. get { return this.historyItems; }
  276. set { this.historyItems = value; this.NotifyOfPropertyChange("HistoryMenus"); }
  277. }
  278. public string Context
  279. {
  280. get { return this.context; }
  281. set { this.context = value; this.NotifyOfPropertyChange("Context"); }
  282. }
  283. public BaseModel CurrentViewModel { get; private set; }
  284. public UserContext User { get { return BaseApp.Instance.UserContext; } }
  285. private AppMenu _currentMenuItem;
  286. private List<AppMenu> menuItems;
  287. private List<AppMenu> subMenuItems;
  288. private ObservableCollection<AppMenu> historyItems;
  289. private string context;
  290. private MainView _view;
  291. private Dictionary<Type, BaseModel> _models;
  292. #endregion
  293. public bool IsPermission { get; set; }
  294. public bool IsAutoLogout { get; set; }
  295. public int LogoutTime { get; set; }
  296. public ObservableCollection<EventItem> WarnEventLogList { get; set; }
  297. public ObservableCollection<EventItem> EventLogList { get; set; }
  298. public Visibility AllEventsVisibility { get; set; }
  299. public Visibility WarnEventsVisibility { get; set; }
  300. [Subscription("Rt.Status")]
  301. public string RtStatus { get; set; }
  302. public string RtStatusBackground
  303. {
  304. get { return ModuleStatusBackground.GetStatusBackground(RtStatus); }
  305. }
  306. [Subscription("EFEM.Status")]
  307. public string EfemStatus { get; set; }
  308. public string EfemStatusBackground
  309. {
  310. get { return ModuleStatusBackground.GetStatusBackground(EfemStatus); }
  311. }
  312. [Subscription("TM.Status")]
  313. public string TMStatus { get; set; }
  314. public string TMStatusBackground
  315. {
  316. get { return ModuleStatusBackground.GetStatusBackground(TMStatus); }
  317. }
  318. #region FA
  319. [Subscription("System.ControlStatus")]
  320. public string SystemControlStatus
  321. {
  322. get;
  323. set;
  324. }
  325. public string ControlStatus
  326. {
  327. get
  328. {
  329. return SystemControlStatus;
  330. }
  331. set
  332. {
  333. }
  334. }
  335. public string ControlStatusBackground
  336. {
  337. get
  338. {
  339. switch (SystemControlStatus)
  340. {
  341. case "Unknown":
  342. return "Yellow";
  343. case "EquipmentOffline":
  344. case "AttemptOnline":
  345. case "HostOffline":
  346. return "Yellow";
  347. case "OnlineLocal":
  348. case "OnlineRemote":
  349. return "LawnGreen";
  350. default:
  351. return "Yellow";
  352. }
  353. }
  354. }
  355. /// Disabled = 0,
  356. /// Enabled = 1,
  357. /// EnabledNotCommunicating = 2,
  358. /// EnabledCommunicating = 3,
  359. /// WaitCRA = 4,
  360. /// WaitDelay = 5,
  361. /// WaitCRFromHost = 6,
  362. public string HostStatusBackground
  363. {
  364. get
  365. {
  366. switch (HostCommunicationStatus)
  367. {
  368. case "EnabledNotCommunicating":
  369. case "WaitCRA":
  370. case "Enabled":
  371. case "WaitDelay":
  372. case "WaitCRFromHost":
  373. return "Yellow";
  374. case "EnabledCommunicating":
  375. if (SystemControlStatus == "OnlineRemote") return "LawnGreen";
  376. return "White";
  377. default:
  378. return "Yellow";
  379. }
  380. }
  381. }
  382. /// <summary>
  383. ///Disabled,
  384. ///Enabled,
  385. ///EnabledNotCommunicating,
  386. ///EnabledCommunicating,
  387. ///WaitCRA,
  388. ///WaitDelay,
  389. ///WaitCRFromHost,
  390. /// </summary>
  391. public string HostStatus
  392. {
  393. get
  394. {
  395. switch (HostCommunicationStatus)
  396. {
  397. case "EnabledNotCommunicating":
  398. case "WaitCRA":
  399. case "Enabled":
  400. case "WaitDelay":
  401. case "WaitCRFromHost":
  402. return "Connecting";
  403. case "EnabledCommunicating":
  404. if (SystemControlStatus == "OnlineRemote") return "OnlineRemote";
  405. if (SystemControlStatus == "OnlineLocal") return "OnlineLocal";
  406. return "Offline";
  407. default:
  408. return "Disconnect";
  409. }
  410. }
  411. set
  412. {
  413. }
  414. }
  415. [Subscription("System.CommunicationStatus")]
  416. public string HostCommunicationStatus
  417. {
  418. get;
  419. set;
  420. }
  421. public bool IsEnableFAEnable
  422. {
  423. get
  424. {
  425. return HostCommunicationStatus == "Disabled";
  426. }
  427. }
  428. public bool IsDisableFAEnable
  429. {
  430. get
  431. {
  432. return HostCommunicationStatus != "Disabled";
  433. }
  434. }
  435. #endregion
  436. #region LP
  437. [Subscription("LP1.IsPlaced")]
  438. public bool IsLP1Placed { get; set; }
  439. [Subscription("LP2.IsPlaced")]
  440. public bool IsLP2Placed { get; set; }
  441. [Subscription("LP3.IsPlaced")]
  442. public bool IsLP3Placed { get; set; }
  443. #endregion
  444. public string PMAStatus
  445. {
  446. get { return $"{PMAEntityStatus}"; }
  447. set { }
  448. }
  449. [Subscription("PMA.Chamber.ServiceStatus")]
  450. public string PMAServiceStatus { get; set; }
  451. [Subscription("PMA.Status")]
  452. public string PMAEntityStatus { get; set; }
  453. public string PMAStatusBackground
  454. {
  455. get { return ModuleStatusBackground.GetStatusBackground(PMAEntityStatus); }
  456. }
  457. public string PMBStatus
  458. {
  459. get { return $"{PMBEntityStatus}"; }
  460. set { }
  461. }
  462. [Subscription("PMB.Chamber.ServiceStatus")]
  463. public string PMBServiceStatus { get; set; }
  464. [Subscription("PMB.Status")]
  465. public string PMBEntityStatus { get; set; }
  466. public string PMBStatusBackground
  467. {
  468. get { return ModuleStatusBackground.GetStatusBackground(PMBEntityStatus); }
  469. }
  470. [Subscription("System.SignalTower.DeviceData")]
  471. public AITSignalTowerData SignalTowerData { get; set; }
  472. public string SoftwareVersion
  473. {
  474. get;
  475. set;
  476. }
  477. public string RunTime
  478. {
  479. get
  480. {
  481. return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  482. }
  483. }
  484. public string LogoTooltip
  485. {
  486. get
  487. {
  488. return $"Software Version: {SoftwareVersion}";
  489. }
  490. }
  491. [Subscription("PMA.IsOnline")]
  492. public bool IsOnlinePMA { get; set; }
  493. [Subscription("PMB.IsOnline")]
  494. public bool IsOnlinePMB { get; set; }
  495. [Subscription("System.HasActiveAlarm")]
  496. public bool SystemHasAlarm { get; set; }
  497. private AppMenu _alarmMenu;
  498. public MainViewModel()
  499. {
  500. BaseApp.Instance.Initialize();
  501. ((ClientApp)BaseApp.Instance).ViewModelSwitcher = this;
  502. this._models = new Dictionary<Type, BaseModel>();
  503. //for login part
  504. Roles = RoleAccountProvider.Instance.GetRoles();
  505. EventLogList = new ObservableCollection<EventItem>();
  506. WarnEventLogList = new ObservableCollection<EventItem>();
  507. SoftwareVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
  508. EventClient.Instance.OnEvent += Instance_OnEvent;
  509. EventClient.Instance.OnDisconnectedWithRT += Instance_OnDisconnectedWithRT;
  510. EventClient.Instance.Start();
  511. //Reset();
  512. }
  513. private void Instance_OnDisconnectedWithRT()
  514. {
  515. MessageBox.Show("Disconnected with RT, UI will exit", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  516. Environment.Exit(0);
  517. }
  518. public void ShowAlarmEvents()
  519. {
  520. AllEventsVisibility = Visibility.Hidden;
  521. WarnEventsVisibility = Visibility.Visible;
  522. this.NotifyOfPropertyChange("AllEventsVisibility");
  523. this.NotifyOfPropertyChange("WarnEventsVisibility");
  524. }
  525. public void ShowAllEvents()
  526. {
  527. AllEventsVisibility = Visibility.Visible;
  528. WarnEventsVisibility = Visibility.Hidden;
  529. this.NotifyOfPropertyChange("AllEventsVisibility");
  530. this.NotifyOfPropertyChange("WarnEventsVisibility");
  531. }
  532. private void PopDialog(EventItem obj)
  533. {
  534. Application.Current.Dispatcher.Invoke(() =>
  535. {
  536. DialogBox.ShowInfo(obj.Explaination);
  537. });
  538. //MessageBox.Show(obj.Explaination,"Information",MessageBoxButton.OK,MessageBoxImage.Information);
  539. }
  540. private void Instance_OnEvent(EventItem obj)
  541. {
  542. switch (obj.Type)
  543. {
  544. case EventType.EventUI_Notify:
  545. LogEvent(obj);
  546. break;
  547. case EventType.Dialog_Nofity:
  548. PopDialog(obj);
  549. break;
  550. case EventType.KickOut_Notify:
  551. if (obj.Description == "ShutDown")
  552. {
  553. AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
  554. ShutdownThread = ShutdownExecute;
  555. ShutdownThread.BeginInvoke(ShutdownCallBack, ShutdownThread);
  556. }
  557. break;
  558. case EventType.Sound_Notify:
  559. break;
  560. case EventType.UIMessage_Notify:
  561. //PopUIMessage(obj);
  562. break;
  563. }
  564. }
  565. void LogEvent(EventItem obj)
  566. {
  567. if (obj.Type != EventType.EventUI_Notify)
  568. return;
  569. Application.Current.Dispatcher.Invoke(() =>
  570. {
  571. while (EventLogList.Count > 100)
  572. {
  573. EventLogList.RemoveAt(0);
  574. }
  575. EventLogList.Add(obj);
  576. if (obj.Level == EventLevel.Alarm)
  577. this.WarnEventLogList.Add(obj);
  578. });
  579. }
  580. public void FAEnable()
  581. {
  582. InvokeClient.Instance.Service.DoOperation("FACommand", "FAEnable");
  583. }
  584. public void FADisable()
  585. {
  586. InvokeClient.Instance.Service.DoOperation("FACommand", "FADisable");
  587. }
  588. #region login part
  589. public void Enter(KeyEventArgs args, string loginName, PasswordBox password, Role role)
  590. {
  591. if (args.Key == Key.Enter)
  592. this.Login(loginName, password, role);
  593. }
  594. public void Login(string loginName, PasswordBox password, Role role)
  595. {
  596. try
  597. {
  598. LoginResult result = AccountClient.Instance.Service.LoginEx(loginName, password.Password, role.RoleID);
  599. if (result.ActSucc)
  600. {
  601. ClientApp.Instance.UserContext.LoginId = result.SessionId;
  602. ClientApp.Instance.UserMode = UserMode.Normal;
  603. ClientApp.Instance.UserContext.LoginName = loginName;
  604. ClientApp.Instance.UserContext.Role = role;
  605. ClientApp.Instance.UserContext.RoleID = role.RoleID;
  606. ClientApp.Instance.UserContext.RoleName = role.RoleName;
  607. ClientApp.Instance.UserContext.LoginTime = DateTime.Now;
  608. //ClientApp.Instance.UserContext.Token = token;
  609. ClientApp.Instance.UserContext.LastAccessTime = DateTime.Now;
  610. ClientApp.Instance.UserContext.IsLogin = true;
  611. //Load menu by role
  612. //filer menu if necessary...
  613. ClientApp.Instance.MenuManager.LoadMenu(RoleAccountProvider.Instance.GetMenusByRole(role.RoleID, ClientApp.Instance.MenuLoader.MenuList));
  614. IsAutoLogout = role.IsAutoLogout;
  615. LogoutTime = role.LogoutTime;
  616. IsPermission = RoleAccountProvider.Instance.GetMenuPermission(role.RoleID, "Header") == 3;
  617. InitMenu(); //bind menu to main view
  618. IsLogin = true; //control the display logic of main view
  619. LOG.Info(string.Format("{0} login as {1}", loginName, role.RoleName));
  620. }
  621. else
  622. {
  623. Enum.TryParse(result.Description, out AuthorizeResult errCode);
  624. switch (errCode)
  625. {
  626. case AuthorizeResult.None:
  627. DialogBox.ShowError("Not connected with RT.");
  628. break;
  629. case AuthorizeResult.WrongPwd:
  630. DialogBox.ShowError("Invalid password.");
  631. break;
  632. case AuthorizeResult.HasLogin:
  633. DialogBox.ShowError("{0} has already logged in.", loginName);
  634. break;
  635. case AuthorizeResult.NoMatchRole:
  636. DialogBox.ShowError("{0} does not match {1} role.", loginName, role.RoleName);
  637. break;
  638. case AuthorizeResult.NoMatchUser:
  639. DialogBox.ShowError("{0} does not exists.", loginName);
  640. break;
  641. case AuthorizeResult.NoSession:
  642. DialogBox.ShowError("The current session is invalid.");
  643. break;
  644. }
  645. }
  646. password.Clear();
  647. }
  648. catch (Exception ex)
  649. {
  650. LOG.Error(ex.Message, ex);
  651. }
  652. }
  653. #endregion
  654. public void PutModuleOnline(string module)
  655. {
  656. InvokeClient.Instance.Service.DoOperation($"{module}.PutOnline");
  657. }
  658. public void PutModuleOffline(string module)
  659. {
  660. InvokeClient.Instance.Service.DoOperation($"{module}.PutOffline");
  661. }
  662. public void Logout()
  663. {
  664. this.OnLogoutCommand();
  665. }
  666. public void OnLogoutCommand()
  667. {
  668. WindowManager windowmanager = new WindowManager();
  669. var logoffViewmodel = new LogoffViewModel();
  670. windowmanager.ShowDialog(logoffViewmodel);
  671. BaseApp.Instance.UserMode = logoffViewmodel.DialogResult;
  672. switch (logoffViewmodel.DialogResult)
  673. {
  674. case UserMode.Logoff:
  675. Logoff();
  676. break;
  677. case UserMode.Exit:
  678. AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
  679. BaseApp.Instance.UserMode = UserMode.Exit;
  680. LOG.Info(string.Format("{0} exit as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
  681. this.TryClose();
  682. break;
  683. case UserMode.Shutdown:
  684. InvokeClient.Instance.Service.DoOperation("System.ShutDown");
  685. break;
  686. }
  687. }
  688. public void Logoff()
  689. {
  690. BaseApp.Instance.UserMode = UserMode.Logoff;
  691. if (BaseApp.Instance.UserContext.IsLogin)
  692. {
  693. try
  694. {
  695. AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
  696. BaseApp.Instance.UserContext.IsLogin = false;
  697. LOG.Info(string.Format("{0} logoff as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
  698. }
  699. catch (Exception exp)
  700. {
  701. LOG.Write(exp);
  702. }
  703. }
  704. IsLogin = false; //no independent login page
  705. Roles = RoleAccountProvider.Instance.GetRoles();
  706. }
  707. public void Reset()
  708. {
  709. InvokeClient.Instance.Service.DoOperation("System.Reset");
  710. }
  711. public void BuzzerOff()
  712. {
  713. InvokeClient.Instance.Service.DoOperation($"System.SignalTower.{AITSignalTowerOperation.SwitchOffBuzzer}");
  714. }
  715. #region override functions
  716. public override void CanClose(Action<bool> callback)
  717. {
  718. if (BaseApp.Instance.UserMode == UserMode.Normal)
  719. {
  720. callback(false);
  721. Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)delegate
  722. {
  723. this.OnLogoutCommand();
  724. });
  725. }
  726. else
  727. callback(true);
  728. }
  729. protected override void OnInitialize()
  730. {
  731. //display system version or other info...
  732. this.DisplayName = $"Efem Dual Tool (V{SoftwareVersion})";
  733. base.OnInitialize();
  734. this.StartTimer();
  735. //DrawSciChart();
  736. if (Debugger.IsAttached)
  737. {
  738. Login("admin", new PasswordBox() { Password = "admin" }, Roles.Find(x => x.RoleName == "Manager"));
  739. }
  740. }
  741. protected override void OnActivate()
  742. {
  743. base.OnActivate();
  744. this.ShowAllEvents();
  745. EnableTimer(true);
  746. }
  747. void DrawSciChart()
  748. {
  749. // Create the chart surface
  750. var sciChartSurface = new SciChartSurface();
  751. // Create the X and Y Axis
  752. var xAxis = new NumericAxis() { AxisTitle = "Number of Samples (per series)" };
  753. var yAxis = new NumericAxis() { AxisTitle = "Value" };
  754. sciChartSurface.XAxis = xAxis;
  755. sciChartSurface.YAxis = yAxis;
  756. // Specify Interactivity Modifiers
  757. sciChartSurface.ChartModifier = new ModifierGroup(new RubberBandXyZoomModifier(), new ZoomExtentsModifier());
  758. // Add annotation hints to the user
  759. var textAnnotation = new TextAnnotation()
  760. {
  761. Text = "Hello World!",
  762. X1 = 5.0,
  763. Y1 = 5.0
  764. };
  765. sciChartSurface.Annotations.Add(textAnnotation);
  766. }
  767. protected override void OnViewLoaded(object view)
  768. {
  769. base.OnViewLoaded(view);
  770. this._view = view as MainView;
  771. //this._view.tbLoginName.Focus();
  772. }
  773. protected override void OnDeactivate(bool close)
  774. {
  775. base.OnDeactivate(close);
  776. EnableTimer(false);
  777. }
  778. #endregion
  779. #region
  780. #region Sync ShutDown Thread
  781. public delegate void ShutDownSysncThread();
  782. ShutDownSysncThread ShutdownThread = null;
  783. ShutdownViewModel ShutdownWindow = null;
  784. private void ShutdownExecute()
  785. {
  786. BaseApp.Instance.UserMode = UserMode.Shutdown;
  787. BaseApp.Instance.UserContext.IsLogin = false;
  788. LOG.Info(string.Format("{0} shutdown as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
  789. this.TryClose();
  790. }
  791. private void ShutdownCallBack(IAsyncResult result)
  792. {
  793. if (ShutdownWindow != null)
  794. {
  795. ShutdownWindow.TryClose();
  796. }
  797. ShutdownThread.EndInvoke(result);
  798. }
  799. #endregion
  800. #region Menu Control and page switch
  801. private void InitMenu()
  802. {
  803. this.MenuItems = BaseApp.Instance.MenuManager.MenuItems;
  804. this.SubMenuItems = new List<AppMenu>();
  805. this.HistoryMenus = new ObservableCollection<AppMenu>();
  806. if (this.MenuItems.Count > 0)
  807. {
  808. AppMenu _default = null;
  809. foreach (AppMenu menuitem in this.MenuItems)
  810. {
  811. if (menuitem.MenuItems.Count > 0)
  812. {
  813. if (menuitem.AlarmModule == "System")
  814. {
  815. _alarmMenu = menuitem;
  816. break;
  817. }
  818. if (_default == null)
  819. _default = menuitem.MenuItems[0];
  820. }
  821. }
  822. this.SwitchMenuItem(_default);
  823. }
  824. }
  825. public void MainSwitchMenuItem(AppMenu menuViewItem)
  826. {
  827. if (menuViewItem.MenuItems.Count > 0)
  828. {
  829. if (menuViewItem.LastSelectedSubMenu != null)
  830. SwitchMenuItem(menuViewItem.LastSelectedSubMenu);
  831. else
  832. SwitchMenuItem(menuViewItem.MenuItems[0]);
  833. }
  834. }
  835. Stopwatch _sw = new Stopwatch();
  836. public void SwitchMenuItem(AppMenu menuViewItem, object parameter = null)
  837. {
  838. _sw.Restart();
  839. if (menuViewItem.ViewModel != null && menuViewItem.ViewModel != string.Empty)
  840. {
  841. if (menuViewItem.Model == null)
  842. {
  843. menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType(menuViewItem.ViewModel));
  844. ((BaseModel)menuViewItem.Model).Permission = menuViewItem.Permission;
  845. ((BaseModel)menuViewItem.Model).Token = BaseApp.Instance.UserContext.Token;
  846. if (menuViewItem.Model is ISupportMultipleSystem)
  847. (menuViewItem.Model as ISupportMultipleSystem).SystemName = menuViewItem.System;
  848. if (menuViewItem.Model is CalibrationTableViewModel)
  849. {
  850. var viewModel = (menuViewItem.Model as CalibrationTableViewModel);
  851. if (viewModel.CustomParameter == null)
  852. viewModel.CustomParameter = new CustomCalibration(viewModel.SystemName);
  853. }
  854. }
  855. this.ActivateItem(((BaseModel)menuViewItem.Model));
  856. CurrentViewModel = ((BaseModel)menuViewItem.Model);
  857. //if (((BaseModel)menuViewItem.Model).Page != PageID.MAX_PAGE)
  858. // BaseApp.Instance.SetCurrentPage(((BaseModel)menuViewItem.Model).Page);
  859. this.HandleSubAndHistoryMenu(menuViewItem);
  860. if (this._currentMenuItem != null)
  861. {
  862. this._currentMenuItem.Selected = false;
  863. this._currentMenuItem.Parent.Selected = false;
  864. }
  865. menuViewItem.Selected = true;
  866. menuViewItem.Parent.Selected = true;
  867. menuViewItem.Parent.LastSelectedSubMenu = menuViewItem;
  868. this._currentMenuItem = menuViewItem;
  869. if (menuViewItem.Model is DataViewModel && parameter != null)
  870. {
  871. Task.Delay(1000).ContinueWith((x) =>
  872. {
  873. var viewModel = (menuViewItem.Model as DataViewModel);
  874. viewModel.Query(parameter);
  875. });
  876. }
  877. if (menuViewItem.Model is ProcessHistoryViewModel && parameter != null)
  878. {
  879. Task.Delay(1000).ContinueWith((x) =>
  880. {
  881. var viewModel = (menuViewItem.Model as ProcessHistoryViewModel);
  882. viewModel.Query(parameter);
  883. });
  884. }
  885. }
  886. float elapsed = _sw.ElapsedMilliseconds;
  887. System.Diagnostics.Trace.WriteLine($"===>SwitchMenuItem time consume: {elapsed} MS");
  888. _sw.Stop();
  889. }
  890. private void HandleSubAndHistoryMenu(AppMenu menuitem)
  891. {
  892. this.SubMenuItems = menuitem.Parent.MenuItems;
  893. if (!this.HistoryMenus.Contains(menuitem))
  894. {
  895. if (this.HistoryMenus.Count >= 8)
  896. this.HistoryMenus.RemoveAt(7);
  897. this.HistoryMenus.Insert(0, menuitem);
  898. }
  899. else
  900. {
  901. this.HistoryMenus.Remove(menuitem);
  902. this.HistoryMenus.Insert(0, menuitem);
  903. }
  904. }
  905. public bool SwitchPage(string firstLevelMenuID, string secondLevelMenuID, object parameter)
  906. {
  907. foreach (AppMenu menuitem in BaseApp.Instance.MenuManager.MenuItems)
  908. {
  909. if (menuitem.MenuID == firstLevelMenuID)
  910. {
  911. foreach (AppMenu menu in menuitem.MenuItems)
  912. {
  913. if (menu.MenuID == secondLevelMenuID)
  914. {
  915. SwitchMenuItem(menu, parameter);
  916. return true;
  917. }
  918. }
  919. }
  920. }
  921. return false;
  922. }
  923. #endregion
  924. #region Refresh Date Time on page
  925. protected override void InvokeAfterUpdateProperty(Dictionary<string, object> data)
  926. {
  927. if (_alarmMenu != null)
  928. _alarmMenu.IsAlarm = SystemHasAlarm;
  929. }
  930. protected override bool OnTimer()
  931. {
  932. try
  933. {
  934. base.Poll();
  935. List<Role> roles = RoleAccountProvider.Instance.GetRoles();
  936. if (!string.IsNullOrEmpty(ClientApp.Instance.UserContext.RoleName))
  937. {
  938. Role role = roles.Find(x => x.RoleName == ClientApp.Instance.UserContext.RoleName);
  939. LogoutTime = role.LogoutTime;
  940. IsAutoLogout = role.IsAutoLogout;
  941. int intervaltime = GetLastInputTime();
  942. //if (System.DateTime.Now >= ClientApp.Instance.UserContext.LoginTime.AddMinutes(LogoutTime) && IsLogin && IsAutoLogout)
  943. if (intervaltime >= LogoutTime * 60 && IsLogin && IsAutoLogout)
  944. Logoff();
  945. }
  946. App.Current.Dispatcher.Invoke((System.Action)(() =>
  947. {
  948. foreach (Window window in Application.Current.Windows)
  949. {
  950. var mdv = window.Content as MessageDialogView;
  951. if (mdv != null)
  952. {
  953. var mdvm = mdv.DataContext as MessageDialogViewModel;
  954. if (mdvm != null && mdvm.DisplayName == "Dialog Box")
  955. {
  956. if ((!IsLP1Placed && mdvm.Text.Contains("LP1"))
  957. || (!IsLP2Placed && mdvm.Text.Contains("LP2"))
  958. || (!IsLP3Placed && mdvm.Text.Contains("LP3")))
  959. mdvm.TryClose();
  960. }
  961. }
  962. }
  963. }));
  964. }
  965. catch (Exception ex)
  966. {
  967. LOG.Error(ex.Message);
  968. }
  969. return true;
  970. }
  971. private void StartTimer()
  972. {
  973. System.Windows.Threading.DispatcherTimer myDispatcherTimer =
  974. new System.Windows.Threading.DispatcherTimer();
  975. myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
  976. myDispatcherTimer.Tick += new EventHandler(Each_Tick);
  977. myDispatcherTimer.Start();
  978. }
  979. public void Each_Tick(object o, EventArgs sender)
  980. {
  981. this.NowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  982. this.NotifyOfPropertyChange("NowDateTime");
  983. }
  984. #endregion
  985. #endregion
  986. }
  987. }