MainViewModel.cs 42 KB

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