/// /// Copyright (c) 2013-2023 Sensus Slovensko a.s. /// using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.IO; using System.Threading; using System.Windows.Forms; using log4net; using Common; using Config.Entities; using Dirichlet.Numerics; using SchematicDrawing; using TBF.Resources; using TBF.UiBridge; using TBF.UI.Shared; using TBF.Rig.Uni.SharedDialogs.SmartMetersCommunication; namespace TBF.UI { /// /// Main program window /// public partial class MainWnd : Form { static readonly ILog log = LogManager.GetLogger(typeof(MainWnd)); /// Used when re-scaling the dialog: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi public static int Dpi; const string ProcSeparator = " "; /// string separating procedure number and procedure name public BenchControlPanel BenchControlPanel; public bool IsShutdownDisabled; public bool IsShutdownPCAfterClosingTbf; /// /// Procedure selection /// IList localProcedures; /// procedures loaded form the local DB IList remoteProcedures; /// Procedures loaded from thr remote/shared DB IList tracingDBOrders; /// Production orders loaded from the production tracing DB IList oracleOrders; /// Production orders loaded from the Oracle DB IList procedureInfos; /// Composed procedure infos /// public ProcedureInfo SelectedProcedure; public Procedure CurrentProcedure; /// /// This dialog is shown when TBF program is shutting down /// Shared.ModelessActivityForm closingTbfMessageForm; TestProgressControls testProgressControls; /// /// Set when procedures are updated while the ProceduresComboBox is disabled (i.e. during a test). /// Reset when the ProceduresComboBox list of items is successfully reloaded in ReloadProcedures(). /// This flag is tested when ProcedureComboBox is being enabled in OnButtonsEtc(), /// optionaly ReloadProcedures() is called. /// public bool ProceduresUpdated = false; /// /// MainTabPage ID-s /// The order of TabPages in this enum must be the same as the order /// of their additions into the mainTabControl in MainWnd.Designer.cs /// TODO: Find a better way /// public enum MainTabPageId { Invalid = -1, Hydraulics = 0, Process, Insert, Results, Graphs, Events, Calendar, Camera, TabPagesCount } /// /// Event handlers switching between tab pages /// private void homeTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); } private void processTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Process); } private void resultsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Results); } private void graphsToolStripMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Graphs); } private void eventsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Events); } private void calendarTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Calendar); } #if CAMERA private System.Windows.Forms.ToolStripMenuItem cameraTSMItem; private void cameraTSMItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Camera); } #endif /// DB entities of components loaded in the MainWnd constructor IList cmpntEntities; /// /// Constructor /// public MainWnd() { /// Detect display setting: 100% = 96dpi, 125% = 120dpi, 150% = 144dpi. Dpi = (int)this.CreateGraphics().DpiX; InitializeComponent(); Text = string.Format("{0} ver. {1} - {2}{3}", Strings.Test_Bench_Framework, Program.Version, TBF.DB.CurrentBench.BenchName, TBF.DB.CurrentBench.IsRealBench ? "" : Strings._offline); localProcedures = new List(); remoteProcedures = new List(); tracingDBOrders = new List(); oracleOrders = new List(); procedureInfos = new List(); SelectedProcedure = null; CurrentProcedure = null; /// /// Customize menu items /// #if CAMERA /// Add 'Camera' menu item cameraTSMItem = new System.Windows.Forms.ToolStripMenuItem(); cameraTSMItem.Name = "cameraTSMItem"; cameraTSMItem.Text = Strings.Camera; cameraTSMItem.Click += new System.EventHandler(this.cameraTSMItem_Click); mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.cameraTSMItem}); #endif UpdateMenuItemsVisibility(); optoHeadsToolStripMenuItem.Visible = true; optoHeadsToolStripMenuItem.Enabled = false; IsShutdownDisabled = true; IsShutdownPCAfterClosingTbf = false; try { /// Load the list of components from the database var session = TBF.DB.CreateSession(DBKind.Config); cmpntEntities = session.QueryOver().OrderBy(x => x.ItemNr).Asc.List(); } catch (Exception) { MessageBox.Show(Strings.Failed_to_load_components, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); cmpntEntities = new List(); } Rig.StateMachine.MachineState = TBF.DB.CurrentBench.IsRealBench ? Rig.MachineState.StartingUp : Rig.MachineState.Disabled; #if DEBUG //define always valid for printer test - BUMI Rig.StateMachine.MachineState = Rig.MachineState.StartingUp; #endif /// if (Rig.StateMachine.MachineState == Rig.MachineState.StartingUp) { try { /// Initialize the control board, etc. Rig.StateMachine.InitializeBoardEtc(cmpntEntities); /// Check remote and local configuration DB compatibility string msg; Rig.GenericDevices.IBenchInfo benchInfo = Rig.Sequences.ProcessData.BenchInfo; bool sharedDBUsed = benchInfo != null ? benchInfo.Sources.Contains(ProcedureSelection.FromSharedDB) : false; bool oracleDBUsed = benchInfo != null ? benchInfo.Sources.Contains(ProcedureSelection.OrderFromOracleDB) : false; bool tracingDBUsed = benchInfo != null ? benchInfo.Sources.Contains(ProcedureSelection.OrderFromTracingDB) : false; if (sharedDBUsed && !Rig.StateMachine.IsRemoteDBCompatible(out msg)) { log.FatalFormat("{0} {1}", Strings.Remote_db_is_not_compatible, msg); throw new Exception(string.Format("{0}{1}{2}", Strings.Remote_db_is_not_compatible, Environment.NewLine, msg)); } if (oracleDBUsed && Rig.Sequences.ProcessData.OracleDB == null) { log.FatalFormat("{0}", Strings.Missing_Oracle_DB); throw new Exception("Oracle DB required for test procedure selection is missing"); } if (tracingDBUsed && Rig.Sequences.ProcessData.TracingDB == null) { log.FatalFormat("{0}", Strings.Missing_tracing_DB); throw new Exception("Production tracing DB required for test procedure selection is missing"); } testProgressControls = new TestProgressControls(progressFlowLayoutPanel); log.Fatal("Remote database is compatible"); } catch (Exception exc) { Rig.StateMachine.MachineState = Rig.MachineState.FailedToStart; string errMsg; if (string.IsNullOrEmpty(Rig.TbfComponents.CurrentlyLoadedComponentName)) { errMsg = exc.Message; } else { errMsg = string.Format(Strings.Failed_to_initialize_component_0_1_2, Rig.TbfComponents.CurrentlyLoadedComponentName, Environment.NewLine, exc.Message); } log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } } void Localize() { /// /// Menu /// benchTSMenuItem.Text = Strings.Bench; benchComponentsTSMenuItem.Text = Strings.Components; benchPathsTSMenuItem.Text = Strings.Paths; benchTransitionsToolStripMenuItem.Text = Strings.Transitions; benchMetrologyTSMenuItem.Text = Strings.Metrology; benchUncertaintyTSMItem.Text = Strings.Uncertainty; benchTestProfilesTSMItem.Text = Strings.Test_profiles; editSchDrawingTSMItem.Text = Strings.Edit_schematic_drawing; exitToolStripMenuItem.Text = Strings.Exit; proceduresToolStripMenuItem.Text = Strings.Procedures; homeTSMenuItem.Text = Strings.Home; processToolStripMenuItem.Text = Strings.Process; resultsToolStripMenuItem.Text = Strings.Results; graphsToolStripMenuItem.Text = Strings.Graphs; eventLogsTSMenuItem.Text = Strings.Event_logs; calendarTSMenuItem.Text = Strings.Calendar; settingsTSMenuItem.Text = Strings.Settings; usersTSMenuItem.Text = Strings.Users; languageTSMItem.Text = Strings.Language; databaseSettingsTSMenuItem.Text = Strings.Database; backUpTSMItem.Text = Strings.Backup; backUpConfigTSMItem.Text = Strings.Configuration; backUpResultsTSMItem.Text = Strings.Results; passwdTSMItem.Text = Strings.Password; upgradeTSMenuItem.Text = Strings.Upgrade_DB; appDiagnosticMenuItem.Text = Strings.Application_Diagnostic; optoHeadsToolStripMenuItem.Text = Strings.Optical_heads; clearCountersToolStripMenuItem.Text = Strings.Clear_counters; helpTSMenuItem.Text = Strings.Help; aboutTSMenuItem.Text = Strings.About; procedureGroupBox.Text = Strings.Procedure; activityGroupBox.Text = Strings.Activity; progressGroupBox.Text = Strings.Progress; } /// /// Initializes this window and its controls /// private void MainWnd_Load(object sender, EventArgs e) { Localize(); TBF.LocalSettings ls = Program.LocalSettings; WindowState = (ls.MainWndMaximized ? FormWindowState.Maximized : FormWindowState.Normal); //if (WindowState != FormWindowState.Normal) //{ // RestoreBounds = new Rectangle((ls.MainWndLeft != 0) ? ls.MainWndLeft : 75, // (ls.MainWndTop != 0) ? ls.MainWndTop : 5, // (ls.MainWndWidth > 0) ? ls.MainWndWidth : 1250, // (ls.MainWndHeight > 0) ? ls.MainWndHeight : 750); //} //else { Width = (ls.MainWndWidth > 0) ? ls.MainWndWidth : 1250; Height = (ls.MainWndHeight > 0) ? ls.MainWndHeight : 750; Left = (ls.MainWndLeft != 0) ? ls.MainWndLeft : 75; Top = (ls.MainWndTop != 0) ? ls.MainWndTop : 5; } if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.StartingUp) { var form = new Shared.ModelessActivityForm() { Message = Strings.Starting_system, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.OliveDrab, /// or Color.YellowGreen StartActivityHandler = true, }; Thread formThread = new Thread(() => form.ShowDialog()); formThread.Start(); try { string message = Rig.StateMachine.InitializeDevices(); form.CloseForm(null, new EventArgs()); formThread.Join(); #if !DEBUG if (message != null) { MessageBox.Show(Strings.The_following_components_are_in_simulation_mode_ + Environment.NewLine + message, Strings.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information); } #endif Bridge.ButtonsEtcHandler += delegate(object sndr, ButtonsEtcEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnButtonsEtc), sndr, args); } else OnButtonsEtc(sndr, args); }; Bridge.ActivityHandler += delegate(object sndr, UiBridge.ActivityEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnActivity), sndr, args); } else OnActivity(sndr, args); }; Bridge.StateChangedHandler += delegate(object sndr, UiBridge.StateChangedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnStateChanged), sndr, args); } else OnStateChanged(sndr, args); }; Bridge.StateMachineTickHandler += delegate(object sndr, UiBridge.StateMachineTickEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnStateMachineTick), sndr, args); } else OnStateMachineTick(sndr, args); }; Bridge.TestProgressHandler += delegate(object sndr, UiBridge.TestProgressEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnTestProgress), sndr, args); } else OnTestProgress(sndr, args); }; Bridge.ProcedureSelectedHandler += delegate(object sndr, UiBridge.ProcedureSelectedEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnProcedureSelected), sndr, args); } else OnProcedureSelected(sndr, args); }; Bridge.SaveSettingsHandler += delegate(object sndr, UiBridge.SaveSettingsEventArgs args) { if (InvokeRequired) { Invoke(new EventHandler(OnSaveSettings), sndr, args); } else OnSaveSettings(sndr, args); }; } catch (Exception exc) { TBF.Rig.StateMachine.MachineState = TBF.Rig.MachineState.FailedToStart; form.CloseForm(null, new EventArgs()); formThread.Join(); string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2, Rig.StateMachine.CurrentlyInitializedComponentName, Environment.NewLine, exc.Message); log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } string signature = ProcedureInfo.GetSignature(ls.LastProcedureSource, (Rig.Sequences.ProcessData.BenchInfo != null) ? Rig.Sequences.ProcessData.BenchInfo.Sources : null); SelectedProcedure = new ProcedureInfo(ls.LastProcedureSource, ls.LastProcedureNr, ls.LastProcedureName, signature); procedureComboBox.Text = SelectedProcedure.ToString(); rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance; topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance; /// Initialize bench control user interface(s) BenchControlPanel = new BenchControlPanel(); BenchControlPanel.BalancesCount = TBF.Rig.StateMachine.Tank3 != null ? 3 : TBF.Rig.StateMachine.Tank2 != null ? 2 : TBF.Rig.StateMachine.Tank1 != null ? 1 : 0; new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)).ApplyResources(BenchControlPanel, "benchControlPanel"); BenchControlPanel.Name = "benchControlPanel"; rightHorizSplitContainer.Panel2.Controls.Add(BenchControlPanel); ReloadProcedureComboBoxItems(); /// Select the initial tab page mainTabControl.SelectTab((int)MainTabPageId.Process); /// This is to load the 'Process screen' mainTabControl.SelectTab((int)MainTabPageId.Calendar); /// This is to load the 'Calendar screen' UpdateUser(); mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); processTabPageCtrl.Settings2UI(); /// /// Initialize hydraulical schematic drawing /// drawingCtrl.SupressRedraws = true; string[] edgesScfg = null; string[] edgesMcfg = null; string[] edgesLcfg = null; string[] edgesXLcfg = null; /// var schDrawingCmpnts = (TBF.DB.CurrentBench.IsRealBench && Rig.StateMachine.Components != null) ? Rig.StateMachine.Components : TBF.Rig.TbfComponents.LoadComponentsFromDB(cmpntEntities); foreach (var component in schDrawingCmpnts) { TBF.Rig.Generic.IComponentCfg cmpCfg = component.Cfg; if (cmpCfg is IDrawingItem) { /// Component is an item to be drawn in the schematic drawing and added to the list box drawingCtrl.AddItem(cmpCfg as IDrawingItem); } else if (cmpCfg is TBF.Rig.Various.Drawing.Pipes.Configuration) { /// Component is Various.Drawing.Edges component var eCfg = cmpCfg as TBF.Rig.Various.Drawing.Pipes.Configuration; switch (eCfg.Sz) { case Sz.S: if (edgesScfg == null) edgesScfg = eCfg.Pipes; break; case Sz.M: if (edgesMcfg == null) edgesMcfg = eCfg.Pipes; break; case Sz.L: if (edgesLcfg == null) edgesLcfg = eCfg.Pipes; break; case Sz.XL: if (edgesXLcfg == null) edgesXLcfg = eCfg.Pipes; break; } } } /// drawingCtrl.PipesS = edgesScfg; drawingCtrl.PipesM = edgesMcfg; drawingCtrl.PipesL = edgesLcfg; drawingCtrl.PipesXL = edgesXLcfg; drawingCtrl.Route = 0; /// Invokes Dijkstra algoritm drawingCtrl.SupressRedraws = false; if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.StartingUp) { /// /// Populate calendar with calendar events from components /// IList calendarEvents = new List(); foreach (var cmpnt in TBF.Rig.StateMachine.Components) { TBF.Rig.GenericDevices.IHasCalendarEvents cmpntWithCalEvents = cmpnt as TBF.Rig.GenericDevices.IHasCalendarEvents; if (cmpntWithCalEvents != null) { foreach (var evnt in cmpntWithCalEvents.GetCalendarEvents()) calendarEvents.Add(evnt); } } calendarTabPageCtrl.StartCalendar(calendarEvents); Rig.StateMachine.Start(); log.Info("Test bench started"); } else if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.FailedToStart) { BenchControlPanel.OnButtonsEtc(null, new ButtonsEtcEventArgs(ButtonsEtc.None)); MessageBox.Show(Strings.Bench_is_not_running, Strings.Warning, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } rightHorizSplitContainer.SplitterDistance = rightHorizSplitContainer.Height / 3;// - BenchControlPanel.Height; topVerticalSplitContainer.SplitterDistance = topVerticalSplitContainer.Width / 2; } /// /// Pass any pressed keys to the Bench control panel. /// Note that MainWnd.KeyPreview must be set to true. /// private void MainWnd_KeyPress(object sender, KeyPressEventArgs e) { #if BADGER_MALA_TRAT || BADGER_STREDNA_TRAT || BADGER_VELKA_TRAT || GENESIS || CEVAK_200 || TURA_SPECIAL || TURA_IPERL || TURA_IPERL_NEW /// Do nothing = do not process keys #else if (BenchControlPanel != null && BenchControlPanel.ProcessKey(e.KeyChar)) { e.Handled = true; log.WarnFormat("'{0}' key pressed, handled by BenchControlPanel", e.KeyChar); } else { log.WarnFormat("'{0}' key pressed, not handled", e.KeyChar); } #endif } /// /// Invoked from the UiBridge to update the activity label. /// void OnActivity(object sender, UiBridge.ActivityEventArgs args) { switch (args.Cmd) { case ActivityEventArgs.Update.Activity: activityLabel.Text = args.Activity; if (string.IsNullOrEmpty(messageLabel.Text)) messageLabel.ForeColor = Color.Black; break; case ActivityEventArgs.Update.Message: messageLabel.Text = args.Message; if (args.ErrorMsg) messageLabel.ForeColor = Color.Red; else messageLabel.ForeColor = Color.Black; break; default: activityLabel.Text = args.Activity; messageLabel.Text = args.Message; if (args.ErrorMsg) messageLabel.ForeColor = Color.Red; else messageLabel.ForeColor = Color.Black; break; } } /// /// Invoked from the UiBridge to update the current state status bar item. /// void OnStateChanged(object sender, StateChangedEventArgs args) { activityStatusLabel.Text = string.Format("{0}: {1}, {2}", TBF.Resources.Strings.Batch, TBF.Rig.Sequences.ProcessData.BatchNr, args.StateChangedMsg); } /// /// This function copies route and process values to the schematic drawing control. /// Schematic drawing is then redrawn accordingly in the next OnPaint(). /// /// /// void OnStateMachineTick(object sender, StateMachineTickEventArgs args) { try { drawingCtrl.SupressRedraws = true; drawingCtrl.Route = args.Route; /// Duplicate measurement available flags if (drawingCtrl.MsrmntAvailableFlags == null || drawingCtrl.MsrmntAvailableFlags.Length != args.MsrmntAvailableFlags.Length) { drawingCtrl.MsrmntAvailableFlags = new bool[args.MsrmntAvailableFlags.Length]; } for (int i = 0; i < args.MsrmntAvailableFlags.Length; i++) drawingCtrl.MsrmntAvailableFlags[i] = args.MsrmntAvailableFlags[i]; /// Duplicate measured values if (drawingCtrl.MeasuredValues == null || drawingCtrl.MeasuredValues.Length != args.MeasuredValues.Length) { drawingCtrl.MeasuredValues = new double[args.MeasuredValues.Length]; } for (int i = 0; i < args.MeasuredValues.Length; i++) drawingCtrl.MeasuredValues[i] = args.MeasuredValues[i]; /// Duplicate alternative strings if (drawingCtrl.AltStrings == null || drawingCtrl.AltStrings.Length != args.AltStrings.Length) { drawingCtrl.AltStrings = new string[args.AltStrings.Length]; } for (int i = 0; i < args.AltStrings.Length; i++) drawingCtrl.AltStrings[i] = args.AltStrings[i]; /// Duplicate setpoints if (drawingCtrl.Setpoints == null || drawingCtrl.Setpoints.Length != args.Setpoints.Length) { drawingCtrl.Setpoints = new double[args.Setpoints.Length]; } for (int i = 0; i < args.Setpoints.Length; i++) drawingCtrl.Setpoints[i] = args.Setpoints[i]; /// Duplicate custom bitmaps if (drawingCtrl.CustomBitmaps == null || drawingCtrl.CustomBitmaps.Length != args.CustomBitmaps.Length) { drawingCtrl.CustomBitmaps = new DrawingShape[args.CustomBitmaps.Length]; } for (int i = 0; i < args.CustomBitmaps.Length; i++) drawingCtrl.CustomBitmaps[i] = args.CustomBitmaps[i]; drawingCtrl.SupressRedraws = false; } catch (Exception e) { log.ErrorFormat("MainWnd.OnStateMachineTick() failed: {0}", e.Message); if (e.InnerException != null) log.FatalFormat("InnerMessage : {0}", e.InnerException.Message); log.FatalFormat("StackTrace : {0}{1}", Environment.NewLine, e.StackTrace); } } void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args) { mainProgressBar.Value = (int)(100.499f * args.OveralProgress); } void OnProcedureSelected(object sender, UiBridge.ProcedureSelectedEventArgs args) { mainProgressBar.Value = 0; } /// /// This handler is onvoked when state of buttons changes /// /// /// void OnButtonsEtc(object sender, UiBridge.ButtonsEtcEventArgs args) { if ((args.Flags & ButtonsEtc.Shutdown) != 0) { /// /// TBF program is shutting down and the state machine was proparly stopped /// UI2Settings(); if (closingTbfMessageForm != null) closingTbfMessageForm.CloseForm(this, null); if (IsShutdownPCAfterClosingTbf) { var psi = new System.Diagnostics.ProcessStartInfo("shutdown", "/s /t 0"); psi.CreateNoWindow = true; psi.UseShellExecute = false; System.Diagnostics.Process.Start(psi); } Close(); return; } if (((args.Flags & ButtonsEtc.ShowBenchEmpty) != 0) || ((args.Flags & ButtonsEtc.ShowBenchFilled) != 0)) { return; } reloadProceduresButton.Enabled = procedureComboBox.Enabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) != 0); optoHeadsToolStripMenuItem.Enabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) != 0); if (procedureComboBox.Enabled) { if (ProceduresUpdated) ReloadProcedureComboBoxItems(); procedureGroupBox.BackColor = Color.DarkBlue; procedureGroupBox.ForeColor = Color.White; procedureComboBox.Focus(); } else { procedureGroupBox.BackColor = SystemColors.Control; procedureGroupBox.ForeColor = SystemColors.ControlText; } IsShutdownDisabled = ((args.Flags & ButtonsEtc.ProcedureCmbBoxEn) == 0); } void OnSaveSettings(object sender, SaveSettingsEventArgs args) { if (Program.LocalSettings != null) Program.LocalSettings.Save(); } public void UpdateUser() { userInfoStatusLabel.Text = string.Format("{0}: {1}{2}, ", Strings.User, CurrentUser.UserName(), (CurrentUser.AuthorizedAs == AuthorizedAs.PowerUser) ? "(S)" : (CurrentUser.AuthorizedAs == AuthorizedAs.LocalUser) ? "(L)" : "(R)"); UpdateMenuItemsVisibility(); } void UpdateMenuItemsVisibility() { usersTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) || CurrentUser.IsMemberOf(GID.HeadOfLab); databaseSettingsTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser(); upgradeTSMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser(); clearCountersToolStripMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) || CurrentUser.IsMemberOf(GID.HeadOfLab) || CurrentUser.IsMemberOf(GID.TestingSpecialists) || CurrentUser.IsMemberOf(GID.Metrologists); appDiagnosticMenuItem.Visible = CurrentUser.IsMemberOf(GID.Administrators) && CurrentUser.IsPowerUser(); } public void UpdateStatusP(string statusPStr) { statusPStatusLabel.Text = string.Format("S={0} , ", statusPStr); /// TODO: Resolve exception } public void UpdateRoute(string routeStr) { routeStatusLabel.Text = string.Format("R={0} , ", routeStr); } /// /// Stop the bench when program closes /// /// /// private void MainWnd_FormClosed(object sender, FormClosedEventArgs e) { //Rig.StateMachine.Stop(); } private void benchComponentsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Components.ComponentsManagerDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchPathsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Paths.PathsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchTransitionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Transitions.TransitionsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchMetrologyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Metrology.MetrologyDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchUncertaintyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.Uncertainties.UncertaintiesDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchTestProfilesTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Bench.TestProfiles.TestProfilesDlg().ShowDialog(); Cursor = Cursors.Default; } private void editSchDrawingTSMItem_Click(object sender, EventArgs e){ Cursor = Cursors.WaitCursor; new TBF.UI.Bench.EditSchDrawing.EditSchDrawingDlg().ShowDialog();Cursor = Cursors.Default; } private void proceduresTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TBF.UI.Procedures.ProceduresDlg().ShowDialog(); Cursor = Cursors.Default; } private void usersTSMItem_Click(object s, EventArgs e) { SharedDatabase.UsersDB.ConnectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString; SharedDatabase.UsersDB.DbType = TBF.DB.CurrentBench.ProceduresDBSettings.DbType; #if IPERL SharedDatabase.Forms.UserManagementDlg dlg = new SharedDatabase.Forms.UserManagementDlg(SharedDatabase.UsersDB.CreateSession(), true); string connStr = SharedDatabase.UsersDB.ConnectionString; int len = connStr.ToUpper().IndexOf("; UID="); if (len == -1) len = connStr.ToUpper().IndexOf("; USER="); if (len > 0) dlg.TitleExtension = connStr.Substring(0, len); #else SharedDatabase.Forms.UserManagementDlg dlg = new SharedDatabase.Forms.UserManagementDlg(SharedDatabase.UsersDB.CreateSession(), false); #endif dlg.ShowDialog(); } private void languageTSMItem_Click(object s, EventArgs e) { new TBF.UI.Settings.LanguageDlg().ShowDialog(); } private void databaseSettingsTSMItem_Click(object s, EventArgs e) { TBF.UI.Settings.BenchesDlg dlg = new TBF.UI.Settings.BenchesDlg(); dlg.ShowDialog(); if (dlg.CurrentDBChanged) { MessageBox.Show(Strings.Currently_used_database_was_restored + Environment.NewLine + Strings.Program_must_be_closed, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); if (TryShutdownTBF()) { /// Save settings and exit TBF UI2Settings(); Close(); } } } private void backUpConfigTSMItem_Click(object s, EventArgs e) { BackupConfiguration(); } private void backUpResultsTSMItem_Click(object s, EventArgs e) { BackupResults(); } private void passwdTSMItem_Click(object s, EventArgs e) { new SharedDatabase.Forms.PasswordChangeDlg(CurrentUser.UserName()).ShowDialog(); } private void aboutTSMItem_Click(object s, EventArgs e) { new TBF.UI.Help.AboutDlg().ShowDialog(); } /// /// Read the database and re-initialize procedureComboBox items. /// Try to preserve the original selection. /// public void ReloadProcedureComboBoxItems() { int separPos = procedureComboBox.Text.IndexOf(ProcSeparator); string procName = (separPos >= 0) ? procedureComboBox.Text.Substring(separPos + ProcSeparator.Length) : string.Empty; ReloadProcedureComboBoxItems(procName); } public void ReloadProcedureComboBoxItems(string procedureNameToSelect) { if (!procedureComboBox.Enabled) { /// Test cycle in progress, reload combo box items when the session is finished ProceduresUpdated = true; } else { /// /// Ensure there is at least one source = one way to select a procedure /// ICollection sources; if (Rig.Sequences.ProcessData.BenchInfo == null) { sources = new ProcedureSelection[] { ProcedureSelection.FromLocalDB }; } else { bool noneOnly = true; foreach (var s in Rig.Sequences.ProcessData.BenchInfo.Sources) if (s != ProcedureSelection.None) { noneOnly = false; break; } sources = noneOnly ? new ProcedureSelection[] { ProcedureSelection.FromLocalDB } : Rig.Sequences.ProcessData.BenchInfo.Sources; } bool procedureSet = false; procedureComboBox.Items.Clear(); procedureInfos.Clear(); foreach (var src in sources) { string signature = ProcedureInfo.GetSignature(src, sources); int itemNr = 1; if (src == ProcedureSelection.FromLocalDB) { try { using (var session = TBF.DB.CreateSession(DBKind.Config)) { localProcedures = session.QueryOver() .Where(x => (x.ProcedureState == ProcedureState.Active)) .OrderBy(x => x.ItemNr).Asc .List(); foreach (var proc in localProcedures) { procedureInfos.Add(new ProcedureInfo(src, itemNr++, proc.Name, signature, proc.Watermeters)); } } } catch (Exception ex) { log.ErrorFormat("Cannot load procedures from a local database: {0}", ex); localProcedures = new List(); } } else if (src == ProcedureSelection.FromSharedDB) { try { using (var session = TBF.DB.CreateSession(DBKind.RemoteConfig)) { remoteProcedures = session.QueryOver() .Where(x => (x.ProcedureState == ProcedureState.Active)) .OrderBy(x => x.ItemNr).Asc .List(); session.Close(); } foreach (var proc in remoteProcedures) { procedureInfos.Add(new ProcedureInfo(src, itemNr++, proc.Name, signature, proc.Watermeters)); } } catch (Exception ex) { log.ErrorFormat("Cannot load procedures from a remote database: {0}", ex); remoteProcedures = new List(); } } else if (src == ProcedureSelection.OrderFromOracleDB) { oracleOrders = Rig.Sequences.ProcessData.OracleDB.ReadOrders(); foreach (var order in oracleOrders) { procedureInfos.Add(new ProcedureInfo(src, 0, order.POName.ToString(), signature, order.VariantCode, order)); } } else if (src == ProcedureSelection.OrderFromTracingDB) { try { using (var session = Rig.Sequences.ProcessData.TracingDB.SessionFactory.OpenSession()) { tracingDBOrders = session.QueryOver() .Where(x => x.POState != (sbyte)SharedDatabase.Entities.OrderState.Finished) .List(); session.Close(); } foreach (var order in tracingDBOrders) { procedureInfos.Add(new ProcedureInfo(src, 0, order.POName, signature, order.VariantCode, order, order.Workflow, order.LaserMarking)); } } catch (Exception ex) { log.ErrorFormat("Cannot load orders from the production tracing DB: {0}", ex); tracingDBOrders = new List(); } } } ResolveOrders(procedureInfos); foreach (var procInfo in procedureInfos) { if (procInfo.IsValid) { procedureComboBox.Items.Add(procInfo); if (!procedureSet && (procedureNameToSelect == procInfo.Name)) { procedureSet = true; procedureComboBox.Text = procInfo.ToString(); SelectedProcedure = procInfo; } } } if (!procedureSet) { procedureComboBox.Text = string.Empty; SelectedProcedure = null; } ProceduresUpdated = false; if (SelectedProcedure != null) BenchControlPanel.ReloadTests(); } } /// /// To each unresolved procedure finds the first native procedure that matches teh unresolved procedure /// /// ProcedureInfo-s that contain unresolved, as well as resolved (native) procedures /// Native procedures /// ProcedureSelection sources of native procedures (the same list items count as nativeProcedures) void ResolveOrders(IList procInfos) { foreach (var pi in procInfos) { if (!pi.IsNative) { if (pi.Source == ProcedureSelection.OrderFromTracingDB) { /// pi.Name is the order name (the production order number) /// Production orders in the tracing DB contain test procedure names var order = tracingDBOrders.FirstOrDefault(x => x.POName == pi.Name); var procInfo = (order == null) ? null : procInfos.FirstOrDefault(x => x.IsNative && x.Name == order.TestProcedure); if (procInfo != null) { pi.ItemNr = procInfo.ItemNr; pi.ResolvedName = procInfo.Name; pi.ResolvedSource = procInfo.Source; } } else if (pi.Source == ProcedureSelection.OrderFromOracleDB) { /// pi.Name is the order name (the production order number) /// Production orders in Oracle DB contain varian codes var order = oracleOrders.FirstOrDefault(x => x.POName == pi.Name); var vaco = (order == null) ? null : order.VariantCode; foreach (var pi2 in procInfos) { if (pi2.IsNative && IsMatch(pi, pi2)) { pi.ItemNr = pi2.ItemNr; pi.ResolvedName = pi2.Name; pi.ResolvedSource = pi2.Source; } } } } } } bool IsMatch(ProcedureInfo procInfoToBeResolved, ProcedureInfo nativeProcedure) { string var1 = procInfoToBeResolved.Variant; string var2 = nativeProcedure.Variant; if (var2.Length == 0 || var1.Length != var2.Length) return false; for (int i = 0; i < var2.Length; i++) { if (var2[i] != 'X' && var1[i] != var2[i]) return false; } return true; } private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e) { foreach (var item in procedureComboBox.Items) { var procInfo = item as ProcedureInfo; if (procInfo != null && procInfo.IsValid && procInfo.ToString() == procedureComboBox.Text) { SelectedProcedure = procInfo; BenchControlPanel.ReloadTests(); if (CurrentProcedure != null && CurrentProcedure.Description != null) { descriptionLabel.Text = CurrentProcedure.Description; } if (CurrentProcedure != null && testProgressControls != null) { testProgressControls.ProcedureSelectedInUI(this, new UiBridge.ProcedureSelectedEventArgs(CurrentProcedure)); } if (!string.IsNullOrEmpty(procInfo.ResolvedName)) { Program.LocalSettings.LastProcedureName = procInfo.ResolvedName; Program.LocalSettings.LastProcedureSource = procInfo.ResolvedSource; Program.LocalSettings.LastProcedureNr = procInfo.ItemNr; Program.LocalSettings.Save(); } } } } private void procedureComboBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '\r' && procedureComboBox.Enabled) { /// Enter key was pressed ... procedureComboBox_SelectedIndexChanged(sender, e as EventArgs); if (SelectedProcedure != null && SelectedProcedure.IsValid) { /// and according to procedureComboBox.Text a valid procedure was selected => start a test cycle Bridge.Ui2Bench(UI2BenchCmd.StartCycle); } } } private void reloadProceduresButton_Click(object sender, EventArgs e) { if (procedureComboBox.Enabled) ReloadProcedureComboBoxItems(); } /// /// Save UI settings to Program.LocalSettings and save them to a file. /// UI settings are: /// MainWnd size and location and splitter distances. /// void UI2Settings() { processTabPageCtrl.UI2Settings(); /// Obtain MainWnd dimensions, etc. bool isMaximized = (WindowState == FormWindowState.Maximized); int left = (WindowState == FormWindowState.Normal) ? Location.X : RestoreBounds.Left; int top = (WindowState == FormWindowState.Normal) ? Location.Y : RestoreBounds.Top; int width = (WindowState == FormWindowState.Normal) ? Size.Width : RestoreBounds.Width; int height = (WindowState == FormWindowState.Normal) ? Size.Height : RestoreBounds.Height; int sd1 = rightHorizSplitContainer.SplitterDistance; int sd2 = topVerticalSplitContainer.SplitterDistance; LocalSettings ls = Program.LocalSettings; if (ls != null && (ls.MainWndMaximized != isMaximized || ls.MainWndLeft != left || ls.MainWndTop != top || ls.MainWndWidth != width || ls.MainWndHeight != height || ls.RightPaneHorizSplitterDistance != sd1 || ls.TopPaneVerticalSplitterDistance != sd2)) { /// At least one MainWnd dimension differs => Update local settings and save them ls.MainWndMaximized = isMaximized; ls.MainWndLeft = left; ls.MainWndTop = top; ls.MainWndWidth = width; ls.MainWndHeight = height; ls.RightPaneHorizSplitterDistance = sd1; ls.TopPaneVerticalSplitterDistance = sd2; ls.Save(); } } bool TryShutdownTBF() { if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Undefined || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Disabled || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.FailedToStart || TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.Off) { /// /// StateMachine is not running --> Shutdown immediately without displaying a message box /// if (closingTbfMessageForm != null) closingTbfMessageForm.CloseForm(this, null); return true; } if (TBF.Rig.StateMachine.MachineState == TBF.Rig.MachineState.ShuttingDown) { /// /// Already shutting down --> Prevent a new shutdown without displaying a message box /// return false; } if ((messageLabel.ForeColor != Color.Red) && IsShutdownDisabled) { /// /// It is not possible to shutdown (most likely a cycle is not completed) --> Display a message and prevent shutdown now /// MessageBox.Show(Strings.Finish_the_session_please, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } ClosingTbfForm closingForm = new ClosingTbfForm(); DialogResult dr = closingForm.ShowDialog(); if (dr == DialogResult.Yes) { /// /// User confirmed TBF program shutdown --> 1. Show modeless form, 2. Stop MainSeq and StateMachine, 3. Prevent TBF exit now /// IsShutdownPCAfterClosingTbf = closingForm.ShutDownPC; /// Show 'Closing_Test_Bench_Framework' modeless window in separate thread closingTbfMessageForm = new Shared.ModelessActivityForm() { Message = Strings.Closing_Test_Bench_Framework, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.PeachPuff, StartActivityHandler = true, }; Thread formThread = new Thread(() => closingTbfMessageForm.ShowDialog()); formThread.Start(); /// Stop MainSeq and StateMachine Bridge.Ui2Bench(UI2BenchCmd.Shutdown); /// Prevent TBF program exit now return false; } else { /// User aborted the shutdown return false; } } private void MainWnd_FormClosing(object sender, FormClosingEventArgs e) { if (TryShutdownTBF()) { UI2Settings(); /// Save settings and exit TBF } else { e.Cancel = true; /// Prevent TBF exit } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (TryShutdownTBF()) { /// Save settings and exit TBF UI2Settings(); Close(); } } private void upgradeTSMenuItem_Click(object sender, EventArgs e) { new TBF.UI.Settings.UpgradeSelectionDlg().ShowDialog(); } private void appDiagnosticMenuItem_Click(object sender, EventArgs e) { /*diagApi = new DiagApi(liveLogCache); //diagApi.AddLog("ahoj, toto je prvy log"); ILog loger = LogManager.GetLogger("logCache"); log.Debug("ahoj, ideme");*/ //LiveLogCache.Instance.AddLog("=== Live diagnostic entry ==="); //DiagApi liveDiagApi = new DiagApi(); /*try { // Predpoklad�me, �e ApplicationDiagnostic.exe je v rovnakom adres�ri ako hlavn� aplik�cia string exePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppDiagnostic.exe"); if (File.Exists(exePath)) { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = exePath, UseShellExecute = true // Spust� aplik�ciu ako samostatn� proces }; System.Diagnostics.Process.Start(startInfo); } else { MessageBox.Show("ApplicationDiagnostic.exe not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show($"Failed to start ApplicationDiagnostic: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }*/ } private void optoHeadsToolStripMenuItem_Click(object sender, EventArgs e) { new SmartCommunicationForm(true).ShowDialog(); } private void statusStrip1_DoubleClick(object sender, EventArgs e) { #if TURA_IPERL || TURA_IPERL_NEW || TURA_SPECIAL GID[] reqGrpMembership = new GID[] { GID.Testers, GID.TestingSpecialists, GID.Metrologists, GID.HeadOfLab }; #else GID[] reqGrpMembership = null; #endif if (new SharedDatabase.Forms.LoginDlg(reqGrpMembership, this).ShowDialog() == DialogResult.OK) { UpdateUser(); } } private void clearCountersToolStripMenuItem_Click(object sender, EventArgs e) { if ((Program.LocalSettings != null) && (Program.LocalSettings.Counters != null) && MessageBox.Show("Do you really want to clear counter(s)?", Strings.Confirmation, MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { for (int i = 0; i < Program.LocalSettings.Counters.Length; i++) { Program.LocalSettings.Counters[i] = 0; } } } /// /// Configuration database export (UI) /// void BackupConfiguration() { string connectionString = TBF.DB.CurrentBench.ProceduresDBSettings.ConnectionString; string server = Common.DatabaseSettings.GetDBServer(connectionString); if ((server != "localhost") && (server != "127.0.0.1")) { MessageBox.Show(Strings.Remote_database_cannot_be_exported, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show(Strings.Do_you_want_to_back_up_configuration_qm, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = string.Format(@"C:\TBF\DbBackups\"); dlg.FileName = string.Format(@"C:\TBF\DbBackups\{0}-{1:yyMMdd-HHmm}.sql", Common.DatabaseSettings.GetDBName(connectionString), DateTime.Now); if (dlg.ShowDialog() != DialogResult.OK) return; DBExportMessageStart(Strings.Saving_configuration); bool successful = ExportDatabase(connectionString, dlg.FileName); DBExportMessageEnd(); if (!successful) MessageBox.Show(Strings.Saving_configuration_failed); } } /// /// Results database export (UI) /// void BackupResults() { string connectionString = TBF.DB.CurrentBench.WaterMetersDBSettings.ConnectionString; string server = Common.DatabaseSettings.GetDBServer(connectionString); if ((server != "localhost") && (server != "127.0.0.1")) { MessageBox.Show(Strings.Remote_database_cannot_be_exported, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show(Strings.Do_you_want_to_back_up_results_qm, string.Empty, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { SaveFileDialog dlg = new SaveFileDialog(); dlg.InitialDirectory = string.Format(@"C:\TBF\DbBackups\"); dlg.FileName = string.Format(@"C:\TBF\DbBackups\{0}-{1:yyMMdd-HHmm}.sql", Common.DatabaseSettings.GetDBName(connectionString), DateTime.Now); if (dlg.ShowDialog() != DialogResult.OK) return; DBExportMessageStart(Strings.Saving_all_results); bool successful = ExportDatabase(connectionString, dlg.FileName); DBExportMessageEnd(); if (!successful) MessageBox.Show(Strings.Saving_results_failed); } } Shared.ModelessActivityForm form; System.Threading.Thread formThread; /// void DBExportMessageStart(string message) { form = new Shared.ModelessActivityForm() { Message = message, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.RoyalBlue, }; formThread = new System.Threading.Thread(() => form.ShowDialog()); formThread.Start(); } /// void DBExportMessageEnd() { if (form != null && formThread != null) { form.CloseForm(null, new EventArgs()); formThread.Join(); } form = null; formThread = null; } /// /// Database export (functionality) /// Invokes: mysqldump --user [userName] --default-character-set=utf8 [databaseName] -r [outputFileName] /// /// DB connection string /// Output file name bool ExportDatabase(string connectionString, string outputFileName) { string databaseName = Common.DatabaseSettings.GetDBName(connectionString); string userName = Common.DatabaseSettings.GetDBUser(connectionString); string password = Common.DatabaseSettings.GetDBPassword(connectionString); try { const string CredFileName = "tempfile"; using (TextWriter writer = new StreamWriter(CredFileName)) { writer.WriteLine("[client]"); writer.WriteLine(string.Format("password=\"{0}\"", password)); } System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = @"C:\xampp\mysql\bin\mysqldump"; proc.StartInfo.Arguments = string.Format("--defaults-file={0} --user={1} --host=localhost --protocol=tcp --port=3306 --default-character-set=utf8 --skip-triggers \"{2}\" -r {3}", CredFileName, userName, databaseName, outputFileName); proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); File.Delete(CredFileName); log.ErrorFormat("Database {0} exported into file {1}", databaseName, outputFileName); return true; } catch (Exception exc) { log.FatalFormat("Failed to export database {0} to file {1}: {2}", databaseName, outputFileName, exc.Message); return false; } } private void drawingCtrl_MouseClick(object sender, MouseEventArgs e) { //if (!drawingCtrl.BenchControlMode) return; IDrawingItem item; Pipe edge; int nodeId; Element element = drawingCtrl.FindElement(e.X, e.Y, Element.Body | Element.Setpoint, out item, out edge, out nodeId); if (element == Element.Body) { if (item is TBF.Rig.Uni.Diverter.DiverterCfg) { TBF.Rig.ControlBoard.Uni.UniCB uniCB = TBF.Rig.StateMachine.ControlBoardMain as TBF.Rig.ControlBoard.Uni.UniCB; if (uniCB != null) { var divCfg = item as TBF.Rig.Uni.Diverter.DiverterCfg; bool divState = (uniCB.Route & ((UInt128)1 << divCfg.BitNr)) != 0; uniCB.SwitchDiverter(true, divCfg.DivNr1, !divState); } return; } if (item is IRouteBasedDrawingItem) { TBF.UiBridge.Bridge.OnRouteChange(this, new TBF.UiBridge.RouteChangeArgs((item as IRouteBasedDrawingItem).BitNr)); return; } if (item is IDrawingItemWithMeasuredVal) { TBF.UiBridge.Bridge.OnMeasurementRequest(this, new TBF.UiBridge.MeasurementRequestArgs(item.Name)); return; } } if (element == Element.Setpoint && item is IDrawingItemWithSetpoint) { TBF.UiBridge.Bridge.OnSetpointChange(this, new TBF.UiBridge.SetpointChangeArgs((item as IDrawingItemWithSetpoint).Name, (e.Button == System.Windows.Forms.MouseButtons.Right))); return; } } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); } } }