MainViewModel.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211
  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. bool isTestXml = (bool)QueryDataClient.Instance.Service.GetConfig("System.IsGasXml");
  811. toolType = isTestXml ? "GasXml" : toolType;
  812. if (string.IsNullOrEmpty(toolType)) continue;
  813. foreach (var menuItemMenuItem in menuitem.MenuItems)
  814. {
  815. if (string.IsNullOrEmpty(menuItemMenuItem.Type))
  816. { continue; }
  817. else
  818. {
  819. if (!menuItemMenuItem.Type.Contains(toolType))
  820. filtered.Add(menuItemMenuItem);
  821. }
  822. }
  823. foreach (var appMenu in filtered)
  824. {
  825. menuitem.MenuItems.Remove(appMenu);
  826. }
  827. }
  828. #endregion
  829. if (menuitem.MenuItems.Count > 0 && _default == null)
  830. _default = menuitem.MenuItems[0];
  831. }
  832. this.SwitchMenuItem(_default);
  833. }
  834. }
  835. public void MainSwitchMenuItem(AppMenu menuViewItem)
  836. {
  837. if (menuViewItem.MenuItems.Count > 0)
  838. {
  839. if (menuViewItem.LastSelectedSubMenu != null)
  840. SwitchMenuItem(menuViewItem.LastSelectedSubMenu);
  841. else
  842. SwitchMenuItem(menuViewItem.MenuItems[0]);
  843. }
  844. }
  845. private Dictionary<string, object> _menus = new Dictionary<string, object>();
  846. public void SwitchMenuItem(AppMenu menuViewItem, object parameter = null)
  847. {
  848. if (menuViewItem != null && menuViewItem.ViewModel != null && menuViewItem.ViewModel != string.Empty)
  849. {
  850. if (menuViewItem.MenuID.ToLower() == "layoutrecipe")
  851. {
  852. if (parameter == null)
  853. parameter = "Layout.List";
  854. if (!_menus.ContainsKey(parameter.ToString()))
  855. {
  856. if (parameter.ToString() == "Layout.List")
  857. {
  858. menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType("FurnaceGasPanelUI.Views.Recipes.RecipeLayoutViewModel, FurnaceGasPanelUI"));
  859. _menus["Layout.List"] = menuViewItem.Model;
  860. }
  861. if (parameter.ToString() == "Layout.Editor")
  862. {
  863. menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType("FurnaceGasPanelUI.Views.Recipes.LayoutRecipes.LayoutRecipeEditorViewModel, FurnaceGasPanelUI"));
  864. _menus["Layout.Editor"] = menuViewItem.Model;
  865. }
  866. }
  867. else
  868. {
  869. menuViewItem.Model = _menus[parameter.ToString()];
  870. }
  871. }
  872. if (menuViewItem.Model == null)
  873. {
  874. menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType(menuViewItem.ViewModel));
  875. ((BaseModel)menuViewItem.Model).Permission = menuViewItem.Permission;
  876. ((BaseModel)menuViewItem.Model).Token = BaseApp.Instance.UserContext.Token;
  877. if (menuViewItem.Model is ISupportMultipleSystem)
  878. (menuViewItem.Model as ISupportMultipleSystem).SystemName = menuViewItem.System;
  879. }
  880. switch (menuViewItem.MenuID.ToLower())
  881. {
  882. case "jobrecipe":
  883. ((BaseModel)menuViewItem.Model).CurrentMenuID = "Job";
  884. break;
  885. case "processrecipe":
  886. ((BaseModel)menuViewItem.Model).CurrentMenuID = "Process";
  887. break;
  888. case "subrecipe":
  889. ((BaseModel)menuViewItem.Model).CurrentMenuID = "sub";
  890. break;
  891. case "alarmrecipe":
  892. ((BaseModel)menuViewItem.Model).CurrentMenuID = "alarm";
  893. break;
  894. case "abortrecipe":
  895. ((BaseModel)menuViewItem.Model).CurrentMenuID = "abort";
  896. break;
  897. case "resetrecipe":
  898. ((BaseModel)menuViewItem.Model).CurrentMenuID = "reset";
  899. break;
  900. case "idlerecipe":
  901. ((BaseModel)menuViewItem.Model).CurrentMenuID = "idle";
  902. break;
  903. case "layoutrecipe":
  904. ((BaseModel)menuViewItem.Model).CurrentMenuID = "Layout";
  905. break;
  906. }
  907. this.ActivateItem(((BaseModel)menuViewItem.Model));
  908. CurrentViewModel = ((BaseModel)menuViewItem.Model);
  909. //if (((BaseModel)menuViewItem.Model).Page != PageID.MAX_PAGE)
  910. // BaseApp.Instance.SetCurrentPage(((BaseModel)menuViewItem.Model).Page);
  911. this.HandleSubAndHistoryMenu(menuViewItem);
  912. if (this._currentMenuItem != null)
  913. {
  914. this._currentMenuItem.Selected = false;
  915. this._currentMenuItem.Parent.Selected = false;
  916. }
  917. menuViewItem.Selected = true;
  918. menuViewItem.Parent.Selected = true;
  919. menuViewItem.Parent.LastSelectedSubMenu = menuViewItem;
  920. this._currentMenuItem = menuViewItem;
  921. if (menuViewItem.Model is DataViewModel && parameter != null)
  922. {
  923. Task.Delay(1000).ContinueWith((x) =>
  924. {
  925. var viewModel = (menuViewItem.Model as DataViewModel);
  926. viewModel.Query(parameter);
  927. });
  928. }
  929. }
  930. }
  931. private void HandleSubAndHistoryMenu(AppMenu menuitem)
  932. {
  933. this.SubMenuItems = menuitem.Parent.MenuItems;
  934. if (!this.HistoryMenus.Contains(menuitem))
  935. {
  936. if (this.HistoryMenus.Count >= 8)
  937. this.HistoryMenus.RemoveAt(7);
  938. this.HistoryMenus.Insert(0, menuitem);
  939. }
  940. else
  941. {
  942. this.HistoryMenus.Remove(menuitem);
  943. this.HistoryMenus.Insert(0, menuitem);
  944. }
  945. }
  946. public bool SwitchPage(string firstLevelMenuID, string secondLevelMenuID, object parameter)
  947. {
  948. foreach (AppMenu menuitem in BaseApp.Instance.MenuManager.MenuItems)
  949. {
  950. if (menuitem.MenuID == firstLevelMenuID)
  951. {
  952. foreach (AppMenu menu in menuitem.MenuItems)
  953. {
  954. if (menu.MenuID == secondLevelMenuID)
  955. {
  956. SwitchMenuItem(menu, parameter);
  957. return true;
  958. }
  959. }
  960. }
  961. }
  962. return false;
  963. }
  964. #endregion
  965. #region Refresh Date Time on page
  966. protected override void InvokeAfterUpdateProperty(Dictionary<string, object> data)
  967. {
  968. if (_alarmMenu != null)
  969. _alarmMenu.IsAlarm = SystemHasAlarm;
  970. }
  971. protected override bool OnTimer()
  972. {
  973. try
  974. {
  975. base.Poll();
  976. List<Role> roles = RoleAccountProvider.Instance.GetRoles();
  977. if (!string.IsNullOrEmpty(ClientApp.Instance.UserContext.RoleName))
  978. {
  979. Role role = roles.Find(x => x.RoleName == ClientApp.Instance.UserContext.RoleName);
  980. LogoutTime = role.LogoutTime;
  981. IsAutoLogout = role.IsAutoLogout;
  982. int intervaltime = GetLastInputTime();
  983. //if (System.DateTime.Now >= ClientApp.Instance.UserContext.LoginTime.AddMinutes(LogoutTime) && IsLogin && IsAutoLogout)
  984. // Console.WriteLine(intervaltime);
  985. if (intervaltime >= LogoutTime * 60 && IsLogin && IsAutoLogout)
  986. Logoff();
  987. }
  988. }
  989. catch (Exception ex)
  990. {
  991. LOG.Error(ex.Message);
  992. }
  993. return true;
  994. }
  995. private void StartTimer()
  996. {
  997. System.Windows.Threading.DispatcherTimer myDispatcherTimer =
  998. new System.Windows.Threading.DispatcherTimer();
  999. myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
  1000. myDispatcherTimer.Tick += new EventHandler(Each_Tick);
  1001. myDispatcherTimer.Start();
  1002. }
  1003. public void Each_Tick(object o, EventArgs sender)
  1004. {
  1005. this.NowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  1006. this.DisplayName = $"Furnace (Ver:{SoftwareVersion})";
  1007. this.NotifyOfPropertyChange("NowDateTime");
  1008. }
  1009. #endregion
  1010. #endregion
  1011. }
  1012. }