123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401 |
- using Aitex.Core.Account;
- using Aitex.Core.Common.DeviceData;
- using Aitex.Core.RT.Event;
- using Aitex.Core.RT.Log;
- using Aitex.Core.Util;
- using Aitex.Core.WCF;
- using Caliburn.Micro;
- using MECF.Framework.Common.Account.Extends;
- using MECF.Framework.Common.DataCenter;
- using MECF.Framework.Common.OperationCenter;
- using MECF.Framework.UI.Client.CenterViews.DataLogs.DataHistory;
- using MECF.Framework.UI.Client.CenterViews.Dialogs;
- using MECF.Framework.UI.Client.CenterViews.LogOnOff;
- using MECF.Framework.UI.Client.ClientBase;
- using MECF.Framework.UI.Core.Accounts;
- using OpenSEMI.ClientBase;
- using OpenSEMI.ClientBase.Command;
- using OpenSEMI.ClientBase.Utility;
- using SciChart.Charting.ChartModifiers;
- using SciChart.Charting.Visuals;
- using SciChart.Charting.Visuals.Annotations;
- using SciChart.Charting.Visuals.Axes;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System.Windows.Threading;
- using FurnaceUI.Config;
- using Cali = Caliburn.Micro.Core;
- using MECF.Framework.Common.Jobs;
- using static Aitex.Core.Common.DeviceData.AITConfigData;
- namespace FurnaceUI.Client
- {
- public class TimeredMainViewModel : Cali.Conductor<Cali.Screen>.Collection.OneActive
- {
- PeriodicJob _timer;
- ConcurrentBag<string> _subscribedKeys = new ConcurrentBag<string>();
- Func<object, bool> _isSubscriptionAttribute;
- Func<MemberInfo, bool> _hasSubscriptionAttribute;
- public TimeredMainViewModel()
- {
- _timer = new PeriodicJob(1000, this.OnTimer, "UIUpdaterThread - " + GetType().Name);
- _isSubscriptionAttribute = attribute => attribute is SubscriptionAttribute;
- _hasSubscriptionAttribute = mi => mi.GetCustomAttributes(false).Any(_isSubscriptionAttribute);
- SubscribeKeys(this);
- }
- [StructLayout(LayoutKind.Sequential)]
- internal struct LASTINPUTINFO
- {
- [MarshalAs(UnmanagedType.U4)]
- public int cbSize;
- [MarshalAs(UnmanagedType.U4)]
- public int dwTime;
- }
- [DllImport("user32.dll")]
- internal static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
- /// <summary>
- /// 获取鼠标键盘不活动的时间
- /// </summary>
- /// <returns>结果</returns>
- public static int GetLastInputTime()
- {
- LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
- lastInputInfo.cbSize = Marshal.SizeOf(lastInputInfo);
- lastInputInfo.dwTime = 0;
- int idleTime = 0;
- if (GetLastInputInfo(ref lastInputInfo))
- {
- idleTime = Environment.TickCount - lastInputInfo.dwTime;
- }
- return ((idleTime > 0) ? (idleTime / 1000) : 0);
- }
- protected virtual bool OnTimer()
- {
- try
- {
- Poll();
- }
- catch (Exception ex)
- {
- LOG.Error(ex.Message);
- }
- return true;
- }
- public virtual void EnableTimer(bool enable)
- {
- if (enable) _timer.Start();
- else _timer.Pause();
- }
- protected virtual void Poll()
- {
- if (_subscribedKeys.Count > 0)
- {
- Dictionary<string, object> result = QueryDataClient.Instance.Service.PollData(_subscribedKeys);
- if (result == null)
- {
- LOG.Error("获取RT数据失败");
- return;
- }
- if (result.Count != _subscribedKeys.Count)
- {
- string unknowKeys = string.Empty;
- foreach (string key in _subscribedKeys)
- {
- if (!result.ContainsKey(key))
- {
- unknowKeys += key + "\r\n";
- }
- }
- //System.Diagnostics.Debug.Assert(false, unknowKeys);
- }
- InvokeBeforeUpdateProperty(result);
- UpdateValue(result);
- Application.Current.Dispatcher.Invoke(new System.Action(() =>
- {
- InvokePropertyChanged();
- InvokeAfterUpdateProperty(result);
- }));
- }
- }
- private void InvokePropertyChanged()
- {
- Refresh();
- }
- protected virtual void InvokeBeforeUpdateProperty(Dictionary<string, object> data)
- {
- }
- protected virtual void InvokeAfterUpdateProperty(Dictionary<string, object> data)
- {
- }
- void UpdateValue(Dictionary<string, object> data)
- {
- if (data == null)
- return;
- UpdateSubscribe(data, this);
- var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<SubscriptionModuleAttribute>() != null);
- foreach (var property in properties)
- {
- var moduleAttr = property.GetCustomAttribute<SubscriptionModuleAttribute>();
- UpdateSubscribe(data, property.GetValue(this), moduleAttr.Module);
- }
- }
- protected void Subscribe(string key)
- {
- if (!string.IsNullOrEmpty(key))
- {
- _subscribedKeys.Add(key);
- }
- }
- public void SubscribeKeys(TimeredMainViewModel target)
- {
- Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
- property =>
- {
- SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
- string key = subscription.ModuleKey;
- if (!_subscribedKeys.Contains(key))
- _subscribedKeys.Add(key);
- });
- Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
- method =>
- {
- SubscriptionAttribute subscription = method.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
- string key = subscription.ModuleKey;
- if (!_subscribedKeys.Contains(key))
- _subscribedKeys.Add(key);
- });
- }
- public void UpdateSubscribe(Dictionary<string, object> data, object target, string module = null)
- {
- Parallel.ForEach(target.GetType().GetProperties().Where(_hasSubscriptionAttribute),
- property =>
- {
- PropertyInfo pi = (PropertyInfo)property;
- SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
- string key = subscription.ModuleKey;
- key = module == null ? key : string.Format("{0}.{1}", module, key);
- if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
- {
- try
- {
- var convertedValue = Convert.ChangeType(data[key], pi.PropertyType);
- var originValue = Convert.ChangeType(pi.GetValue(target, null), pi.PropertyType);
- if (originValue != convertedValue)
- {
- if (pi.Name == "PumpLimitSetPoint")
- pi.SetValue(target, convertedValue, null);
- else
- pi.SetValue(target, convertedValue, null);
- }
- }
- catch (Exception ex)
- {
- LOG.Error("由RT返回的数据更新失败" + key, ex);
- }
- }
- });
- Parallel.ForEach(target.GetType().GetFields().Where(_hasSubscriptionAttribute),
- property =>
- {
- FieldInfo pi = (FieldInfo)property;
- SubscriptionAttribute subscription = property.GetCustomAttributes(false).First(_isSubscriptionAttribute) as SubscriptionAttribute;
- string key = subscription.ModuleKey;
- if (_subscribedKeys.Contains(key) && data.ContainsKey(key))
- {
- try
- {
- var convertedValue = Convert.ChangeType(data[key], pi.FieldType);
- pi.SetValue(target, convertedValue);
- }
- catch (Exception ex)
- {
- LOG.Error("由RT返回的数据更新失败" + key, ex);
- }
- }
- });
- }
- }
- public class MainViewModel : TimeredMainViewModel
- {
- #region Menus
- public string NowDateTime { get; set; }
- private bool _IsLogin = false;
- public bool IsLogin
- {
- get { return _IsLogin; }
- set { _IsLogin = value; NotifyOfPropertyChange("IsLogin"); }
- }
- private List<Role> roles;
- public List<Role> Roles
- {
- get { return this.roles; }
- set
- {
- this.roles = value;
- ShowRoles = new List<Role>(value);
- this.RaisePropertyChangedEventImmediately("Roles");
- }
- }
- private List<Role> showRoles;
- public List<Role> ShowRoles
- {
- get { return showRoles; }
- set { showRoles = value; this.RaisePropertyChangedEventImmediately("ShowRoles"); }
- }
- private string lockString;
- public string LockString
- {
- get
- {
- return lockString;
- }
- set
- {
- lockString = value;
- NotifyOfPropertyChange("LockString");
- }
- }
- private ICommand menuItemClickCommand;
- public ICommand MenuItemClickCommand
- {
- get
- {
- if (this.menuItemClickCommand == null)
- this.menuItemClickCommand = new BaseCommand<AppMenu>((AppMenu menuViewItem) => this.SwitchMenuItem(menuViewItem));
- return this.menuItemClickCommand;
- }
- }
- private ICommand mainmenuItemClickCommand;
- public ICommand MainMenuItemClickCommand
- {
- get
- {
- if (this.mainmenuItemClickCommand == null)
- this.mainmenuItemClickCommand = new BaseCommand<AppMenu>((AppMenu menuViewItem) => this.MainSwitchMenuItem(menuViewItem));
- return this.mainmenuItemClickCommand;
- }
- }
- public List<AppMenu> MenuItems
- {
- get { return this.menuItems; }
- set { this.menuItems = value; this.NotifyOfPropertyChange("MenuItems"); }
- }
- public List<AppMenu> SubMenuItems
- {
- get { return this.subMenuItems; }
- set { this.subMenuItems = value; this.NotifyOfPropertyChange("SubMenuItems"); }
- }
- public ObservableCollection<AppMenu> HistoryMenus
- {
- get { return this.historyItems; }
- set { this.historyItems = value; this.NotifyOfPropertyChange("HistoryMenus"); }
- }
- public string Context
- {
- get { return this.context; }
- set { this.context = value; this.NotifyOfPropertyChange("Context"); }
- }
- public BaseModel CurrentViewModel { get; private set; }
- public UserContext User { get { return BaseApp.Instance.UserContext; } }
- private AppMenu _currentMenuItem;
- private List<AppMenu> menuItems;
- private List<AppMenu> subMenuItems;
- private ObservableCollection<AppMenu> historyItems;
- private string context;
- private MainView _view;
- private Dictionary<Type, BaseModel> _models;
- #endregion
- public bool IsPermission { get; set; }
- public bool IsAutoLogout { get; set; }
- public int LogoutTime { get; set; }
- [Subscription("System.LiveAlarmEvent")]
- public List<EventItem> AlarmLogList { get; set; }
- public ObservableCollection<EventItem> WarnEventLogList { get; set; }
- public ObservableCollection<EventItem> EventLogList { get; set; }
- public Visibility AllEventsVisibility { get; set; }
- public Visibility WarnEventsVisibility { get; set; }
- [Subscription("LP1.Status")]
- public string LP1Status { get; set; }
- [Subscription("LP2.Status")]
- public string LP2Status { get; set; }
- public string LP1StatusBackground
- {
- get { return ModuleStatusBackground.GetStatusBackground(LP1Status); }
- }
- public string LP2StatusBackground
- {
- get { return ModuleStatusBackground.GetStatusBackground(LP2Status); }
- }
- [Subscription("Rt.Status")]
- public string RtStatus { get; set; }
- [Subscription("System.TransferJobStatus")]
- public string TransferJobStatus { get; set; }
- [Subscription("System.ProcessJobStatus")]
- public string ProcessJobStatus { get; set; }
- public string SystemStatus
- {
- get
- {
- switch (RtStatus)
- {
- case "ChargeProcessDischarging":
- return ProcessJobStatus;
- case "LoadProcessStockering":
- case "LoadProcessUnloading":
- return ProcessJobStatus == "Idle" ? TransferJobStatus : ProcessJobStatus;
- }
- return RtStatus;
- }
- set
- {
- }
- }
- public string RtStatusBackground
- {
- get { return ModuleStatusBackground.GetStatusBackground(SystemStatus); }
- }
- private bool _isLock = false;
- public bool IsLock
- {
- get
- {
- return _isLock;
- }
- set
- {
- _isLock = value;
- AppSettingsHelper.SetConfigValue("IsLock", value.ToString());
- LockString = _isLock ? "Lock" : "Unlock";
- NotifyOfPropertyChange("IsLock");
- }
- }
- #region FA
- [Subscription("System.ControlStatus")]
- public string SystemControlStatus
- {
- get;
- set;
- }
- public string ControlStatus
- {
- get
- {
- return SystemControlStatus;
- }
- set
- {
- }
- }
- public string ControlStatusBackground
- {
- get
- {
- switch (SystemControlStatus)
- {
- case "Unknown":
- return "Yellow";
- case "EquipmentOffline":
- case "AttemptOnline":
- case "HostOffline":
- return "Transparent";
- case "OnlineLocal":
- case "OnlineRemote":
- return "LawnGreen";
- default:
- return "Yellow";
- }
- }
- }
- /// Disabled = 0,
- /// Enabled = 1,
- /// EnabledNotCommunicating = 2,
- /// EnabledCommunicating = 3,
- /// WaitCRA = 4,
- /// WaitDelay = 5,
- /// WaitCRFromHost = 6,
- public string HostCommunicationStatusBackground
- {
- get
- {
- switch (HostCommunicationStatus)
- {
- case "Unknown":
- return "Yellow";
- case "EquipmentOffline":
- case "AttemptOnline":
- case "HostOffline":
- return "Transparent";
- case "OnlineLocal":
- case "EnabledCommunicating":
- return "LawnGreen";
- default:
- return "Yellow";
- }
- }
- }
- [Subscription("System.CommunicationStatus")]
- public string HostCommunicationStatus
- {
- get;
- set;
- }
- public bool IsEnableFAEnable
- {
- get
- {
- return HostCommunicationStatus == "Disabled";
- }
- }
- public bool IsDisableFAEnable
- {
- get
- {
- return HostCommunicationStatus != "Disabled";
- }
- }
- public string FAButtonContent => HostCommunicationStatus == "Disabled" ? "FA Enable" : "FA Disable";
- #endregion
- public string PM1Status
- {
- get { return $"{PM1EntityStatus}"; }
- set { }
- }
- [Subscription("PM1.Status")]
- public string PM1EntityStatus { get; set; }
- private string _newPM1EntityStatus;
- public string NewPM1EntityStatus
- {
- get { return _newPM1EntityStatus; }
- set { _newPM1EntityStatus = value; NotifyOfPropertyChange("NewPM1EntityStatus"); }
- }
- public string PM1StatusBackground
- {
- get { return ModuleStatusBackground.GetStatusBackground(NewPM1EntityStatus); }
- }
- [Subscription("System.SignalTower.DeviceData")]
- public AITSignalTowerData SignalTowerData { get; set; }
- public string SoftwareVersion
- {
- get;
- set;
- }
- public string RunTime
- {
- get
- {
- return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- public string LogoTooltip
- {
- get
- {
- return $"Software Version: {SoftwareVersion}";
- }
- }
- [Subscription("Scheduler.ControlJobList")]
- public List<ControlJobInfo> ControlJobs
- {
- get;
- set;
- }
- [Subscription("Scheduler.SecondPj")]
- public List<ProcessJobInfo> SecondPjList
- {
- get;
- set;
- }
- [Subscription("PM1.IsOnline")]
- public bool IsOnlinePM1 { get; set; }
- [Subscription("System.HasActiveAlarm")]
- public bool SystemHasAlarm { get; set; }
- private AppMenu _alarmMenu;
- public MainViewModel()
- {
- BaseApp.Instance.Initialize();
- ((FurnaceUI.Client.ClientApp)BaseApp.Instance).ViewModelSwitcher = this;
- this._models = new Dictionary<Type, BaseModel>();
- //for login part
- Roles = RoleAccountProvider.Instance.GetRoles();
- EventLogList = new ObservableCollection<EventItem>();
- WarnEventLogList = new ObservableCollection<EventItem>();
- SoftwareVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
- EventClient.Instance.OnEvent += Instance_OnEvent;
- EventClient.Instance.LockAndUnlockEvent += Instance_LockAndUnlockEvent;
- EventClient.Instance.OnDisconnectedWithRT += Instance_OnDisconnectedWithRT;
- EventClient.Instance.Start();
- //if (Debugger.IsAttached)
- {
- Login("admin", new PasswordBox() { Password = "admin" }, Roles.Find(it => it.RoleName == "Manager"));
- }
- //Reset();
- //var exeFilePath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
- //var tempPath = exeFilePath.Substring(0, exeFilePath.LastIndexOf("\\"));
- //exeFilePath = tempPath.Substring(0, tempPath.LastIndexOf("\\")) + "\\FurnaceGasPanelUI\\" + "FurnaceGasPanelUI.exe";
- //if (File.Exists(exeFilePath))
- //{
- // System.Diagnostics.Process.Start(exeFilePath);
- //}
- }
- //设置LockAndUnLock
- private void Instance_LockAndUnlockEvent(bool obj)
- {
- // throw new NotImplementedException();
- IsLock = obj;
- }
- private void Instance_OnDisconnectedWithRT()
- {
- MessageBox.Show("Disconnected with RT, UI will exit", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
- Environment.Exit(0);
- }
- public void ShowAlarmEvents()
- {
- AllEventsVisibility = Visibility.Hidden;
- WarnEventsVisibility = Visibility.Visible;
- this.NotifyOfPropertyChange("AllEventsVisibility");
- this.NotifyOfPropertyChange("WarnEventsVisibility");
- }
- public void ShowAllEvents()
- {
- AllEventsVisibility = Visibility.Visible;
- WarnEventsVisibility = Visibility.Hidden;
- this.NotifyOfPropertyChange("AllEventsVisibility");
- this.NotifyOfPropertyChange("WarnEventsVisibility");
- }
- private void Instance_OnEvent(EventItem obj)
- {
- switch (obj.Type)
- {
- case EventType.EventUI_Notify:
- LogEvent(obj);
- break;
- case EventType.Dialog_Nofity:
- //PopDialog(obj);
- break;
- case EventType.KickOut_Notify:
- if (obj.Description == "ShutDown")
- {
- AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
- ShutdownThread = ShutdownExecute;
- ShutdownThread.BeginInvoke(ShutdownCallBack, ShutdownThread);
- }
- break;
- case EventType.Sound_Notify:
- break;
- case EventType.UIMessage_Notify:
- //PopUIMessage(obj);
- break;
- }
- }
- void LogEvent(EventItem obj)
- {
- if (obj.Type != EventType.EventUI_Notify)
- return;
- Application.Current.Dispatcher.Invoke(() =>
- {
- while (EventLogList.Count > 100)
- {
- EventLogList.RemoveAt(0);
- }
- EventLogList.Add(obj);
- if (obj.Level == EventLevel.Alarm || obj.Level == EventLevel.Warning)
- {
- this.WarnEventLogList.Add(obj);
- }
- });
- }
- public void FAEnable()
- {
- InvokeClient.Instance.Service.DoOperation($"FACommand", "FAEnable");
- }
- public void FADisable(object para)
- {
- if (para.ToString() == "FA Disable")
- {
- InvokeClient.Instance.Service.DoOperation($"FACommand", "FADisable");
- }
- else
- {
- InvokeClient.Instance.Service.DoOperation($"FACommand", "FAEnable");
- }
- }
- #region login part
- public void Enter(KeyEventArgs args, string loginName, PasswordBox password, Role role)
- {
- if (args.Key == Key.Enter)
- this.Login(loginName, password, role);
- }
- public void Login(string loginName, PasswordBox password, Role role)
- {
- try
- {
- LoginResult result = AccountClient.Instance.Service.LoginEx(loginName, password.Password, role.RoleID);
- if (result.ActSucc)
- {
- ClientApp.Instance.UserContext.LoginId = result.SessionId;
- ClientApp.Instance.UserMode = UserMode.Normal;
- ClientApp.Instance.UserContext.LoginName = loginName;
- ClientApp.Instance.UserContext.Role = role;
- ClientApp.Instance.UserContext.RoleID = role.RoleID;
- ClientApp.Instance.UserContext.RoleName = role.RoleName;
- ClientApp.Instance.UserContext.LoginTime = DateTime.Now;
- //ClientApp.Instance.UserContext.Token = token;
- ClientApp.Instance.UserContext.LastAccessTime = DateTime.Now;
- ClientApp.Instance.UserContext.IsLogin = true;
- //Load menu by role
- //filer menu if necessary...
- ClientApp.Instance.MenuManager.LoadMenu(RoleAccountProvider.Instance.GetMenusByRole(role.RoleID, ClientApp.Instance.MenuLoader.MenuList));
- IsAutoLogout = role.IsAutoLogout;
- LogoutTime = role.LogoutTime;
- IsPermission = RoleAccountProvider.Instance.GetMenuPermission(role.RoleID, "Header") == 3;
- InitMenu(); //bind menu to main view
- IsLogin = true; //control the display logic of main view
- if (GetView() != null)
- {
- ((Window)GetView()).Dispatcher.BeginInvoke(new System.Action(() =>
- {
- foreach (var item in Application.Current.Windows)
- {
- if (item is Window && item != Application.Current.MainWindow)
- {
- ((Window)item).Visibility = Visibility.Visible
- ;
- }
- }
- }));
- }
- LOG.Info(string.Format("{0} login as {1}", loginName, role.RoleName));
- }
- else
- {
- Enum.TryParse(result.Description, out AuthorizeResult errCode);
- switch (errCode)
- {
- case AuthorizeResult.None:
- DialogBox.ShowError("Not connected with RT.");
- break;
- case AuthorizeResult.WrongPwd:
- DialogBox.ShowError("Invalid password.");
- break;
- case AuthorizeResult.HasLogin:
- DialogBox.ShowError("{0} has already logged in.", loginName);
- break;
- case AuthorizeResult.NoMatchRole:
- DialogBox.ShowError("{0} does not match {1} role.", loginName, role.RoleName);
- break;
- case AuthorizeResult.NoMatchUser:
- DialogBox.ShowError("{0} does not exists.", loginName);
- break;
- case AuthorizeResult.NoSession:
- DialogBox.ShowError("The current session is invalid.");
- break;
- }
- }
- password.Clear();
- }
- catch (Exception ex)
- {
- LOG.Error(ex.Message, ex);
- }
- }
- public void TxtLoginNameLostFocus(object sender, RoutedEventArgs e)
- {
- var userName = ((TextBox)sender).Text;
- if (!string.IsNullOrEmpty(userName))
- {
- var accounts = AccountClient.Instance.Service.GetAccounts();
- var user = accounts.Where(x => x.LoginName == userName).FirstOrDefault();
- if (user != null)
- {
- ShowRoles = RoleAccountProvider.Instance.GetRoles().Where(it => user.RoleIDs.Contains(it.RoleID)).ToList();
- if (_view != null)
- {
- if (_view.cbRole.Items.Count > 0)
- {
- _view.cbRole.SelectedIndex = 0;
- }
- }
- }
- }
- }
- #endregion
- public void PutModuleOnline(string module)
- {
- InvokeClient.Instance.Service.DoOperation($"{module}.PutOnline");
- }
- public void PutModuleOffline(string module)
- {
- InvokeClient.Instance.Service.DoOperation($"{module}.PutOffline");
- }
- public void Logout()
- {
- this.OnLogoutCommand();
- }
- public void LockClick()
- {
- string cmd = "Lock";
- if (IsLock == true)
- { cmd = "Unlock"; }
- else
- { cmd = "Lock"; }
- //EventClient.Instance.Service.Register
- InvokeClient.Instance.Service.DoOperation("System.SetLockAndUnlock", new object[] { cmd, EventClient.Instance.ClientGuid });
- }
- public void OnLogoutCommand()
- {
- WindowManager windowmanager = new WindowManager();
- var logoffViewmodel = new LogoffViewModel();
- windowmanager.ShowDialog(logoffViewmodel);
- BaseApp.Instance.UserMode = logoffViewmodel.DialogResult;
- switch (logoffViewmodel.DialogResult)
- {
- case UserMode.Logoff:
- Logoff();
- break;
- case UserMode.Exit:
- AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
- BaseApp.Instance.UserMode = UserMode.Exit;
- LOG.Info(string.Format("{0} exit a" +
- "s {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
- this.TryClose();
- break;
- case UserMode.Lock:
- Login("logoff", new PasswordBox() { Password = "admin" }, Roles.Find(it => it.RoleName == "Logoff"));
- break;
- case UserMode.Shutdown:
- Roles = RoleAccountProvider.Instance.GetRoles();
- InvokeClient.Instance.Service.DoOperation("System.ShutDown");
- break;
- }
- }
- public void Logoff()
- {
- BaseApp.Instance.UserMode = UserMode.Logoff;
- if (BaseApp.Instance.UserContext.IsLogin)
- {
- try
- {
- AccountClient.Instance.Service.LogoutEx(BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.LoginId);
- BaseApp.Instance.UserContext.IsLogin = false;
- LOG.Info(string.Format("{0} logoff as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
- }
- catch (Exception exp)
- {
- LOG.Write(exp);
- }
- }
- IsLogin = false; //no independent login page
- Roles = RoleAccountProvider.Instance.GetRoles();
- ((Window)GetView()).Dispatcher.BeginInvoke(new System.Action(() =>
- {
- foreach (var item in Application.Current.Windows)
- {
- if (item is Window && item != Application.Current.MainWindow)
- {
- ((Window)item).Visibility = Visibility.Hidden;
- }
- }
- }));
- }
- public void Reset()
- {
- InvokeClient.Instance.Service.DoOperation("System.Reset");
- }
- public void BuzzerOff()
- {
- InvokeClient.Instance.Service.DoOperation($"System.SignalTower.{AITSignalTowerOperation.SwitchOffBuzzer}");
- }
- #region override functions
- public override void CanClose(Action<bool> callback)
- {
- if (BaseApp.Instance.UserMode == UserMode.Normal)
- {
- callback(false);
- Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)delegate
- {
- this.OnLogoutCommand();
- });
- }
- else
- callback(true);
- }
- protected override void OnInitialize()
- {
- //display system version or other info...
- this.DisplayName = $"Furnace (V{SoftwareVersion})";
- base.OnInitialize();
- this.StartTimer();
- DrawSciChart();
- // Login("admin", new PasswordBox() { Password = "admin" }, new Role("0", "Manager", false, 1000, ""));
- }
- protected override void OnActivate()
- {
- base.OnActivate();
- this.ShowAllEvents();
- EnableTimer(true);
- }
- void DrawSciChart()
- {
- // Create the chart surface
- var sciChartSurface = new SciChartSurface();
- // Create the X and Y Axis
- var xAxis = new NumericAxis() { AxisTitle = "Number of Samples (per series)" };
- var yAxis = new NumericAxis() { AxisTitle = "Value" };
- sciChartSurface.XAxis = xAxis;
- sciChartSurface.YAxis = yAxis;
- // Specify Interactivity Modifiers
- sciChartSurface.ChartModifier = new ModifierGroup(new RubberBandXyZoomModifier(), new ZoomExtentsModifier());
- // Add annotation hints to the user
- var textAnnotation = new TextAnnotation()
- {
- Text = "Hello World!",
- X1 = 5.0,
- Y1 = 5.0
- };
- sciChartSurface.Annotations.Add(textAnnotation);
- }
- protected override void OnViewLoaded(object view)
- {
- base.OnViewLoaded(view);
- this._view = view as MainView;
- this._view.tbLoginName.Focus();
- IsLock = bool.Parse(AppSettingsHelper.GetConfigValue("IsLock"));
- }
- protected override void OnDeactivate(bool close)
- {
- base.OnDeactivate(close);
- EnableTimer(false);
- }
- #endregion
- #region
- #region Sync ShutDown Thread
- public delegate void ShutDownSysncThread();
- ShutDownSysncThread ShutdownThread = null;
- ShutdownViewModel ShutdownWindow = null;
- private void ShutdownExecute()
- {
- BaseApp.Instance.UserMode = UserMode.Shutdown;
- BaseApp.Instance.UserContext.IsLogin = false;
- LOG.Info(string.Format("{0} shutdown as {1}", BaseApp.Instance.UserContext.LoginName, BaseApp.Instance.UserContext.RoleName));
- this.TryClose();
- }
- private void ShutdownCallBack(IAsyncResult result)
- {
- if (ShutdownWindow != null)
- {
- ShutdownWindow.TryClose();
- }
- ShutdownThread.EndInvoke(result);
- }
- #endregion
- #region Menu Control and page switch
- private void InitMenu()
- {
- this.MenuItems = BaseApp.Instance.MenuManager.MenuItems;
- this.SubMenuItems = new List<AppMenu>();
- this.HistoryMenus = new ObservableCollection<AppMenu>();
- if (this.MenuItems.Count > 0)
- {
- AppMenu _default = null;
- foreach (AppMenu menuitem in this.MenuItems)
- {
- if (menuitem.MenuItems.Count > 0)
- {
- if (menuitem.AlarmModule == "System")
- {
- _alarmMenu = menuitem;
- continue;
- }
- #region PM Filter
- List<AppMenu> filtered = new List<AppMenu>();
- string toolType = (string)QueryDataClient.Instance.Service.GetConfig("System.SetUp.ToolType");
- string runningMode = (string)QueryDataClient.Instance.Service.GetConfig("System.RunningMode");
- if (string.IsNullOrEmpty(toolType)) continue;
- foreach (var menuItemMenuItem in menuitem.MenuItems)
- {
- if (menuItemMenuItem.IsHide && runningMode == ConfigEnum.Release.ToString())
- {
- filtered.Add(menuItemMenuItem);
- }
- if (string.IsNullOrEmpty(menuItemMenuItem.Type))
- {
- continue;
- }
- else
- {
- if (!menuItemMenuItem.Type.Contains(toolType))
- filtered.Add(menuItemMenuItem);
- }
- }
- foreach (var appMenu in filtered)
- {
- menuitem.MenuItems.Remove(appMenu);
- }
- }
- #endregion
- if (menuitem.MenuItems.Count > 0 && _default == null)
- _default = menuitem.MenuItems[0];
- }
- this.SwitchMenuItem(_default);
- }
- }
- public void MainSwitchMenuItem(AppMenu menuViewItem)
- {
- if (menuViewItem.MenuItems.Count > 0)
- {
- if (menuViewItem.LastSelectedSubMenu != null)
- SwitchMenuItem(menuViewItem.LastSelectedSubMenu);
- else
- SwitchMenuItem(menuViewItem.MenuItems[0]);
- }
- }
- private Dictionary<string, object> _menus = new Dictionary<string, object>();
- public void SwitchMenuItem(AppMenu menuViewItem, object parameter = null)
- {
- if (menuViewItem != null && menuViewItem.ViewModel != null && menuViewItem.ViewModel != string.Empty)
- {
- //if (menuViewItem.MenuID.ToLower() == "layoutrecipe")
- //{
- // if (parameter == null)
- // parameter = "Layout.List";
- // if (!_menus.ContainsKey(parameter.ToString()))
- // {
- // if (parameter.ToString() == "Layout.List")
- // {
- // menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType("FurnaceUI.Views.Recipes.RecipeLayoutViewModel, FurnaceUI"));
- // _menus["Layout.List"] = menuViewItem.Model;
- // }
- // if (parameter.ToString() == "Layout.Editor")
- // {
- // menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType("FurnaceUI.Views.Recipes.LayoutRecipes.LayoutRecipeEditorViewModel, FurnaceUI"));
- // _menus["Layout.Editor"] = menuViewItem.Model;
- // }
- // }
- // else
- // {
- // menuViewItem.Model = _menus[parameter.ToString()];
- // }
- //}
- if (menuViewItem.Model == null)
- {
- menuViewItem.Model = (BaseModel)AssemblyUtil.CreateInstance(AssemblyUtil.GetType(menuViewItem.ViewModel));
- ((BaseModel)menuViewItem.Model).Permission = menuViewItem.Permission;
- ((BaseModel)menuViewItem.Model).Token = BaseApp.Instance.UserContext.Token;
- if (menuViewItem.Model is ISupportMultipleSystem)
- (menuViewItem.Model as ISupportMultipleSystem).SystemName = menuViewItem.System;
- }
- switch (menuViewItem.MenuID.ToLower())
- {
- case "jobrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "Job";
- break;
- case "processrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "Process";
- break;
- case "subrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "sub";
- break;
- case "alarmrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "alarm";
- break;
- case "abortrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "abort";
- break;
- case "resetrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "reset";
- break;
- case "idlerecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "idle";
- break;
- case "layoutrecipe":
- ((BaseModel)menuViewItem.Model).CurrentMenuID = "Layout";
- break;
- }
- this.ActivateItem(((BaseModel)menuViewItem.Model));
- CurrentViewModel = ((BaseModel)menuViewItem.Model);
- //if (((BaseModel)menuViewItem.Model).Page != PageID.MAX_PAGE)
- // BaseApp.Instance.SetCurrentPage(((BaseModel)menuViewItem.Model).Page);
- this.HandleSubAndHistoryMenu(menuViewItem);
- if (this._currentMenuItem != null)
- {
- this._currentMenuItem.Selected = false;
- this._currentMenuItem.Parent.Selected = false;
- }
- menuViewItem.Selected = true;
- menuViewItem.Parent.Selected = true;
- menuViewItem.Parent.LastSelectedSubMenu = menuViewItem;
- this._currentMenuItem = menuViewItem;
- if (menuViewItem.Model is DataViewModel && parameter != null)
- {
- Task.Delay(200).ContinueWith((x) =>
- {
- var viewModel = (menuViewItem.Model as DataViewModel);
- viewModel.Query(parameter);
- });
- }
- }
- }
- private void HandleSubAndHistoryMenu(AppMenu menuitem)
- {
- this.SubMenuItems = menuitem.Parent.MenuItems;
- if (!this.HistoryMenus.Contains(menuitem))
- {
- if (this.HistoryMenus.Count >= 8)
- this.HistoryMenus.RemoveAt(7);
- this.HistoryMenus.Insert(0, menuitem);
- }
- else
- {
- this.HistoryMenus.Remove(menuitem);
- this.HistoryMenus.Insert(0, menuitem);
- }
- }
- public bool SwitchPage(string firstLevelMenuID, string secondLevelMenuID, object parameter)
- {
- foreach (AppMenu menuitem in BaseApp.Instance.MenuManager.MenuItems)
- {
- if (menuitem.MenuID == firstLevelMenuID)
- {
- foreach (AppMenu menu in menuitem.MenuItems)
- {
- if (menu.MenuID == secondLevelMenuID)
- {
- SwitchMenuItem(menu, parameter);
- return true;
- }
- }
- }
- }
- return false;
- }
- #endregion
- #region Refresh Date Time on page
- protected override void InvokeAfterUpdateProperty(Dictionary<string, object> data)
- {
- if (_alarmMenu != null)
- _alarmMenu.IsAlarm = SystemHasAlarm;
- SetTubeStatus();
- }
- private void SetTubeStatus()
- {
- if (SecondPjList != null && SecondPjList.Count > 0 && SecondPjList.FirstOrDefault() != null && ControlJobs != null && ControlJobs.Count > 0)
- {
- var secondPj = SecondPjList.FirstOrDefault();
- var actualPjName = ControlJobs.FirstOrDefault().ProcessJobNameList.FirstOrDefault();
- if (secondPj.Name.Equals(actualPjName) && (int)secondPj.ProcessingState <= (int)EnumProcessingState.Processing)
- {
- NewPM1EntityStatus = "Process";
- }
- else
- {
- NewPM1EntityStatus = PM1EntityStatus;
- }
- }
- else
- {
- NewPM1EntityStatus = PM1EntityStatus;
- }
- }
- protected override bool OnTimer()
- {
- try
- {
- base.Poll();
- //List<Role> roles = RoleAccountProvider.Instance.GetRoles();
- if (!string.IsNullOrEmpty(ClientApp.Instance.UserContext.RoleName))
- {
- Role role = roles.Find(x => x.RoleName == ClientApp.Instance.UserContext.RoleName);
- if (role == null) return true;
- LogoutTime = role.LogoutTime;
- IsAutoLogout = role.IsAutoLogout;
- int intervaltime = GetLastInputTime();
- //if (System.DateTime.Now >= ClientApp.Instance.UserContext.LoginTime.AddMinutes(LogoutTime) && IsLogin && IsAutoLogout)
- // Console.WriteLine(intervaltime);
- //if (intervaltime >= LogoutTime * 60 && IsLogin && IsAutoLogout)
- // Logoff();
- }
- }
- catch (Exception ex)
- {
- LOG.Error(ex.Message);
- }
- return true;
- }
- private void StartTimer()
- {
- System.Windows.Threading.DispatcherTimer myDispatcherTimer =
- new System.Windows.Threading.DispatcherTimer();
- myDispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000);
- myDispatcherTimer.Tick += new EventHandler(Each_Tick);
- myDispatcherTimer.Start();
- }
- public void Each_Tick(object o, EventArgs sender)
- {
- this.NowDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- this.DisplayName = $"Furnace (Ver:{SoftwareVersion})";
- this.NotifyOfPropertyChange("NowDateTime");
- }
- #endregion
- #endregion
- public void PasswordMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
- {
- if (sender is PasswordBox)
- {
- string strRet = ShowKeyboard(sender, ((PasswordBox)sender).Password);
- ((PasswordBox)sender).Password = strRet;
- }
- }
- private string ShowKeyboard(object sender, string strDefaultValue)
- {
- bool EnablePopupKeyboard = false;
- Control control = sender as Control;
- string strRet = string.Empty;
- if (QueryDataClient.Instance.Service.GetConfig($"System.EnablePopupKeyboard") != null)
- EnablePopupKeyboard = (bool)QueryDataClient.Instance.Service.GetConfig($"System.EnablePopupKeyboard");
- if (!EnablePopupKeyboard) { return string.Empty; }
- FullKeyboard fullKeyboard = new FullKeyboard("", strDefaultValue);
- var point = control.PointFromScreen(new Point(0, 0));
- double x = SystemParameters.WorkArea.Width;
- double y = SystemParameters.WorkArea.Height;
- if (-point.Y + control.ActualHeight + 5 + fullKeyboard.Height < y)
- {
- fullKeyboard.Top = -point.Y + control.ActualHeight + 5;
- }
- else
- {
- fullKeyboard.Top = -point.Y - fullKeyboard.Height - 5;
- }
- if (-point.X + fullKeyboard.Width < x)
- {
- fullKeyboard.Left = -point.X;
- }
- else
- {
- fullKeyboard.Left = -point.X - (fullKeyboard.Width - control.ActualWidth);
- }
- if ((bool)fullKeyboard.ShowDialog()) strRet = fullKeyboard.ValueString;
- return strRet;
- }
- }
- }
|