/// /// Copyright (c) 2013-2017 Sensus Metering Systems /// using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using log4net; using Config.Entities; using TBF.UiBridge; using TBF.Resources; using System.Threading; namespace TBF { public partial class MainWnd : Form { static readonly ILog log = LogManager.GetLogger(typeof(MainWnd)); public UiControls.BenchControlPanel BenchControlPanel; public string ProcedureName; public Procedure CurrentProcedure; /// /// This dialog is shown when emergency stop is activated /// TBF.Forms.EmergencyStopForm emergencyStopModelessDlg; bool benchInitializationFailed; 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, Logs, Pictures, 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 logsTSMenuItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Logs); } #if CAMERA private void picturesTSMItem_Click(object sender, EventArgs e) { mainTabControl.SelectTab((int)MainTabPageId.Pictures); } #endif #if CAMERA private System.Windows.Forms.ToolStripMenuItem picturesTSMItem; #endif /// /// Constructor /// public MainWnd() { InitializeComponent(); #if CAMERA /// Add 'Pictures' menu item picturesTSMItem = new System.Windows.Forms.ToolStripMenuItem(); picturesTSMItem.Name = "picturesTSMItem"; picturesTSMItem.Text = "Pictures"; picturesTSMItem.Click += new System.EventHandler(this.picturesTSMItem_Click); mainMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {this.picturesTSMItem}); #endif Text = string.Format("Test Bench Framework ver. {0} - {1}{2}", Program.Version, Config.Data.CurrentBench.BenchName, Config.Data.CurrentBench.IsRealBench ? "" : Strings._offline); usersTSMenuItem.Visible = Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.Administrators) || Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.HeadOfLab); upgradeTSMenuItem.Visible = Users.GlobalData.CurrentUser.IsMemberOf(Users.Grp.GID.Administrators) && Users.GlobalData.CurrentUser.UserName == "milan"; benchInitializationFailed = false; /// if (Config.Data.CurrentBench.IsRealBench) { try { BenchControl.StateMachine.InitializeBoardEtc(ctrlBrdComponent); testProgressControls = new TestProgressControls(progressFlowLayoutPanel); } catch (Exception exc) { benchInitializationFailed = true; string errMsg = string.Format(Strings.Failed_to_initialize_component_0_1_2, BenchControl.TbfComponents.CurrentlyLoadedComponentName, Environment.NewLine, exc.Message); log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } } void Localize() { 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.ManiWndMaximized ? 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 (Config.Data.CurrentBench.IsRealBench && !benchInitializationFailed) { var form = new TBF.Forms.ModelessActivityForm() { Message = Strings.Starting_system, FontFamily = "Arial", FontSize = 24, FontStyle = FontStyle.Regular, BackgroundColor = Color.OliveDrab /// or Color.YellowGreen }; Thread formThread = new Thread(() => form.ShowDialog()); formThread.Start(); try { string message = BenchControl.StateMachine.InitializeDevices(); form.CloseForm(null, new EventArgs()); formThread.Join(); #if !MUNICH if (message != null) { MessageBox.Show(Strings.The_following_components_are_in_simulation_mode_ + Environment.NewLine + message, Strings.Warning, MessageBoxButtons.OK, MessageBoxIcon.Information); } #endif //emergencyStopModelessDlg = new TBF.Forms.EmergencyStopForm(); //emergencyStopModelessDlg.Show(); 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.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); }; } catch (Exception exc) { benchInitializationFailed = true; form.CloseForm(null, new EventArgs()); formThread.Join(); string errMsg = string.Format(Strings.Failed_to_initialize_device_0_1_2, BenchControl.StateMachine.CurrentlyInitializedDeviceName, Environment.NewLine, exc.Message); log.Fatal(errMsg); MessageBox.Show(errMsg, Strings.Error, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } procedureComboBox.Text = Program.LocalSettings.LastProcedureName; ProcedureName = Program.LocalSettings.LastProcedureName; rightHorizSplitContainer.SplitterDistance = Program.LocalSettings.RightPaneHorizSplitterDistance; topVerticalSplitContainer.SplitterDistance = Program.LocalSettings.TopPaneVerticalSplitterDistance; /// Text boxes for data input, with border and white background CustomStyle.Set(0, DockStyle.Fill, Color.White, BorderStyle.FixedSingle, false, new System.Drawing.Font("Verdana", 10.5F, FontStyle.Regular, GraphicsUnit.Point, (byte)(238))); // Read only text boxes (labels), its background matches the window background /// Measurement CustomStyle.Set(1, DockStyle.Fill, Color.FromArgb(150, 180, 200), BorderStyle.None, true, new System.Drawing.Font("Verdana", 10.5F, FontStyle.Regular, GraphicsUnit.Point, (byte)(238))); /// Not used CustomStyle.Set(2, DockStyle.Fill, Color.OliveDrab, BorderStyle.None, true, new System.Drawing.Font("Verdana", 10.5F, FontStyle.Regular, GraphicsUnit.Point, (byte)(238))); /// Procedure CustomStyle.Set(3, DockStyle.Fill, Color.FromArgb(200, 200, 150), BorderStyle.None, true, new System.Drawing.Font("Verdana", 10.5F, FontStyle.Regular, GraphicsUnit.Point, (byte)(238))); /// Initialize bench control user interface(s) BenchControlPanel = new TBF.UiControls.BenchControlPanel(); BenchControlPanel.BalancesCount = TBF.BenchControl.MettlerToledo.Standard.BalanceDev.BalancesCount + TBF.BenchControl.MettlerToledo.Multi.BalanceDev.BalancesCount; new System.ComponentModel.ComponentResourceManager(typeof(MainWnd)).ApplyResources(BenchControlPanel, "benchControlPanel"); BenchControlPanel.Name = "benchControlPanel"; rightHorizSplitContainer.Panel2.Controls.Add(BenchControlPanel); ReloadProcedures(); /// Select the initial tab page mainTabControl.SelectTab((int)MainTabPageId.Process); /// This is to load the 'Process screen' UpdateUser(); mainTabControl.SelectTab((int)MainTabPageId.Hydraulics); if (Config.Data.CurrentBench.IsRealBench) { if (!benchInitializationFailed) { BenchControl.StateMachine.Start(); log.Info("Test bench started"); } else { BenchControlPanel.OnButtonsEtc(null, new ButtonsEtcEventArgs(TBF.UiBridge.ButtonsEtc.None)); MessageBox.Show(Strings.Bench_is_not_running, Strings.Warning, System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Exclamation); } } } /// /// 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 (BenchControlPanel != null && BenchControlPanel.ProcessKey(e.KeyChar)) { e.Handled = true; } } /// /// 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; 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 = args.StateChangedMsg; } void OnTestProgress(object sender, UiBridge.TestProgressEventArgs args) { mainProgressBar.Value = (int)(100.499f * args.OveralProgress); } void OnProcedureSelected(object sender, UiBridge.ProcedureSelectedEventArgs args) { mainProgressBar.Value = 0; } void OnButtonsEtc(object sender, UiBridge.ButtonsEtcEventArgs args) { if (((args.Flags & ButtonsEtc.ShowBenchEmpty) != 0) || ((args.Flags & ButtonsEtc.ShowBenchFilled) != 0)) { return; } procedureComboBox.Enabled = ((args.Flags & UiBridge.ButtonsEtc.ProcedureCmbBoxEn) != 0); if (procedureComboBox.Enabled && ProceduresUpdated) { ReloadProcedures(); } } public void UpdateUser() { userInfoStatusLabel.Text = string.Format("{0}: {1}{2}, ", Strings.User, Users.GlobalData.CurrentUser.UserName, (Users.GlobalData.AuthorizedAs == Users.Entities.AuthorizedAs.PowerUser) ? "(S)" : ((Users.GlobalData.AuthorizedAs == Users.Entities.AuthorizedAs.LocalUser) ? "(L)" : "(R)")); } 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) { //BenchControl.StateMachine.Stop(); } private void benchComponentsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new ComponentsManagerDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchPathsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new PathsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchTransitionsTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new TransitionsDlg().ShowDialog(); Cursor = Cursors.Default; } private void benchMetrologyTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new MetrologyDlg().ShowDialog(); Cursor = Cursors.Default; } private void proceduresTSMItem_Click(object s, EventArgs e) { Cursor = Cursors.WaitCursor; new ProceduresDlg().ShowDialog(); Cursor = Cursors.Default; } private void localSettingsTSMItem_Click(object s, EventArgs e) { new PreferencesDlg().ShowDialog(); } private void databaseSettingsTSMItem_Click(object s, EventArgs e) { new BenchesDlg().ShowDialog(); } private void usersTSMItem_Click(object s, EventArgs e) { Users.DB.ConnectionString = Config.Data.CurrentBench.ProceduresDBSettings.ConnectionString; Users.DB.DbType = Config.Data.CurrentBench.ProceduresDBSettings.DbType; #if TURA_IPERL || TURA_SPECIAL Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(true); string connStr = Users.DB.ConnectionString; int len = connStr.ToUpper().IndexOf("; UID="); if (len > 0) dlg.TitleExtension = connStr.Substring(0, len); #else Users.Forms.UserManagementDlg dlg = new Users.Forms.UserManagementDlg(false); #endif dlg.ShowDialog(); } private void aboutTSMItem_Click(object s, EventArgs e) { new Forms.AboutDlg().ShowDialog(); } /// /// Read the database and re-initialize procedureComboBox items. /// Try to preserve the original selection. /// public void ReloadProcedures() { if (procedureComboBox.Enabled) { string oriProcName = procedureComboBox.Text; IList procedures = Config.FluentCommon.CreateSession(Users.Entities.DBKind.Config) .QueryOver() .Where(x => (x.ProcedureState == ProcedureState.Active)) .OrderBy(x => x.ItemNr).Asc .List(); procedureComboBox.Items.Clear(); foreach (var proc in procedures) procedureComboBox.Items.Add(proc.Name); if (procedureComboBox.Items.Contains(oriProcName)) { procedureComboBox.Text = oriProcName; ProcedureName = oriProcName; } else if (procedures.Count > 0) { procedureComboBox.Text = procedures[0].Name; ProcedureName = procedures[0].Name; } else { procedureComboBox.Text = string.Empty; ProcedureName = null; } ProceduresUpdated = false; BenchControlPanel.ReloadTests(); } else { ProceduresUpdated = true; } } private void procedureComboBox_SelectedIndexChanged(object sender, EventArgs e) { UpdateProcedure(procedureComboBox.Text); } public void UpdateProcedure(string procedureName) { procedureComboBox.Text = procedureName; ProcedureName = procedureName; 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(ProcedureName)) { Program.LocalSettings.LastProcedureName = ProcedureName; Program.LocalSettings.Save(); } } private void MainWnd_FormClosing(object sender, FormClosingEventArgs e) { Program.LocalSettings.RightPaneHorizSplitterDistance = rightHorizSplitContainer.SplitterDistance; Program.LocalSettings.TopPaneVerticalSplitterDistance = topVerticalSplitContainer.SplitterDistance; Program.LocalSettings.ManiWndMaximized = (WindowState == FormWindowState.Maximized); if (WindowState == FormWindowState.Normal) { Program.LocalSettings.MainWndLeft = Location.X; Program.LocalSettings.MainWndTop = Location.Y; Program.LocalSettings.MainWndWidth = Size.Width; Program.LocalSettings.MainWndHeight = Size.Height; } else { /// Maximized or minimized (when restarted, minimized window is restored as normal) Program.LocalSettings.MainWndLeft = RestoreBounds.Left; Program.LocalSettings.MainWndTop = RestoreBounds.Top; Program.LocalSettings.MainWndWidth = RestoreBounds.Width; Program.LocalSettings.MainWndHeight = RestoreBounds.Height; } Program.LocalSettings.Save(); if (DialogResult == DialogResult.None) { exitToolStripMenuItem_Click(sender, e); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { bool oriEmgStopState = false; if (emergencyStopModelessDlg != null) { oriEmgStopState = emergencyStopModelessDlg.Visible; emergencyStopModelessDlg.Visible = false; } if (DialogResult.Yes == MessageBox.Show(Strings.Do_you_want_to_exit_TBF, Strings.Closing_the_program, MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { BenchControl.StateMachine.Stop(); BenchControl.StateMachine.StopDevices(); UiBridge.Bridge.OnEmergencyStopChanged(this, UiBridge.EmergencyStopEventArgs.State.CloseForm); new Forms.ClosingProgram().ShowDialog(); DialogResult = DialogResult.OK; Close(); return; } else if (e is FormClosingEventArgs) { (e as FormClosingEventArgs).Cancel = true; } if (emergencyStopModelessDlg != null) emergencyStopModelessDlg.Visible = oriEmgStopState; } private void printToolStripMenuItem_Click(object sender, EventArgs e) { //TBF.Forms.PrintOrderForm dlg = new TBF.Forms.PrintOrderForm(); //if (dlg.ShowDialog() == DialogResult.OK) //{ // string purchaseOrder = dlg.PurchaseOrder; // string tester = dlg.Tester; // NHibernate.ISession session = Config.FluentCommon.CreateSession(Users.Entities.DBKind.Config); // IList testResults = session.QueryOver() // .Where(x => (x.PurchaseOrder == purchaseOrder)) // .List(); // if (testResults.Count == 0) // { // MessageBox.Show(Strings.No_results_to_print, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // return; // } // if (dlg.OnlyGoodResults) // { // /// Proceed from the end of the list so that items can be removed by index // for (int i = testResults.Count - 1; i >= 0; i--) // { // // TODO: Complete // } // } // if (dlg.OnlyLastResult) // { // /// Remove test results if there exist a later test results for the same sn // /// Proceed from the end of the list so that items can be removed by index // for (int i = testResults.Count - 1; i >= 0; i--) // { // string name = testResults[i].Name; // int batchNr = testResults[i].BatchNr; // foreach (var tr in testResults) // { // if (tr.Name == name && tr.BatchNr > batchNr) // { // bool allWMsAreTheSame = true; // int cnt = Math.Min(testResults[i].Meters.Count, tr.Meters.Count); // for (int j = 0; j < cnt; j++) // { // if (testResults[i].Meters[j].SerialNr != tr.Meters[j].SerialNr) // { // allWMsAreTheSame = false; // break; // } // } // if (allWMsAreTheSame) // { // /// Remove as there exists a more recent measurement with the same meters // testResults.RemoveAt(i); // break; // } // } // } // } // } // IList procedure = session.QueryOver() // .Where(x => (x.ProcedureState == ProcedureState.Active)) // .And(x => (x.Name == testResults[0].ProcedureName)) // .List(); // if (procedure.Count != 1) // { // MessageBox.Show(Strings.No_results_to_print, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // return; // } // if ((testResults != null) && (testResults.Count != 0) && (testResults[0].MetersKind == MetersKind.Single)) // { // PrintOrderDocument doc = new PrintOrderDocument(procedure[0], testResults, tester); // doc.DefaultPageSettings.Landscape = true; // doc.Print(); // } // else if((testResults != null) && (testResults.Count != 0) && (testResults[0].MetersKind == MetersKind.Combined)) // { // /// Do nothing right now // } // else // { // MessageBox.Show(Strings.No_results_to_print, Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // return; // } //} } private void upgradeTSMenuItem_Click(object sender, EventArgs e) { new Forms.UpgradeSelectionDlg().Show(); } } }