//----------------------------------------------------------------------- // // Copyright © 2012 Nils Hammar. All rights reserved. // //----------------------------------------------------------------------- /* * Software to access vehicle information via the OBD-II connector. * * Copyright © 2012 Nils Hammar * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * Alternative licensing is possible, see the licensing document. * * The above text may not be removed or modified. */ namespace UserInterface.GUI { using System; using System.Collections.Generic; using System.IO.Ports; using System.Management; using System.Threading; using System.Windows.Forms; using global::DataSource; using global::DataSource.FileAccess; using global::DeviceApi.J2534; using global::DeviceApi.Serial; using global::Protocol; using global::SharedObjects; using global::SharedObjects.Api; using global::SharedObjects.DataMgmt; using global::SharedObjects.GUI; using global::SharedObjects.GUI.Popup; using global::SharedObjects.Misc; using global::SharedObjects.Protocol; using global::UserInterface.GUI.Objects; /// /// Panel for interface data. /// public partial class InterfacePanel : UserControl, ISerialPortMonitorCallback, IInterfacePanel { /// /// Gets current PassThru instance. /// public IPassThru iPassThru { get; private set; } /// /// Gets a value indicating whether the protocols panel is activated. /// public bool protocolsEnabled { get; private set; } /// /// Current logging instance. /// private ILogging iLogging; /// /// Current preferences instance. /// private IPreferences iPreferences; /// /// Current device instance. /// private IPassThruDevice passThruDevice; /// /// Current data source instance. /// private IDataSource iDataSource; /// /// Wrapper class for serial port parameters. /// private ISerialPortParameters serialPortParameters = new SerialPortParameters(); /// /// Current serial port handler, 'null' until serial port Opened. /// private SerialPortHandler serialPortHandler = null; /// /// Selected vehicle. /// private XmlClass.vehicle vehicle; /// /// General OBD code file access. /// private ObdCodeFileAccess generalObd; /// /// Vehicle specific OBD code file access. /// private ObdCodeFileAccess specificObd; /// /// Composite OBD code file access, this is an union of the general and vehicle specific codes. /// private ObdCodeFileAccess compositeObd; /// /// Node in panel tree that this instance maps to. /// private TreeNode panelTreeNode; /// /// Misc functions interface instance. /// private IMiscFunc iMiscFunc; /// /// Application tree instance. /// private IApplicationTree applicationTree; /// /// Hint engine instance. /// private IHintActivator hintActivator; /// /// Data file directory path. /// private string dataFileDir; /// /// Initializes a new instance of the class. /// /// Misc functions interface instance. /// Current data source instance. /// Current logging instance. /// Current PassThru interface instance. /// Current preferences instance. /// Current Application Tree instance. /// Hint activator instance. /// Data file directory path. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "CanApp.CustomToolTip", Justification = "Reviewed, intentional.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Reviewed, intentional.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "3", Justification = "Reviewed.")] public InterfacePanel( IMiscFunc iMiscFunc, IDataSource iDataSource, ILogging iLogging, IPassThru iPassThru, IPreferences iPreferences, ApplicationTree applicationTree, IHintActivator hintActivator, string dataFileDir) { this.iMiscFunc = iMiscFunc; this.iDataSource = iDataSource; this.iLogging = iLogging; this.iPassThru = iPassThru; this.iPreferences = iPreferences; this.applicationTree = applicationTree; this.hintActivator = hintActivator; this.dataFileDir = dataFileDir; this.protocolsEnabled = false; this.InitializeComponent(); this.interfaceDescription.Text = iPassThru.name; this.refreshSerialPortInfo(null); this.init(); this.loadObdCodes(); this.reloadVehicles(); this.setPreferredVehicle(); this.toolTip1.SetToolTip(this.quickOpenBT, "Connect to the vehicle using the default values."); this.toolTip1.SetToolTip(this.openBT, "Connect to the vehicle step by step allowing for manual control of the process."); this.toolTip1.SetToolTip(this.closeBT, "Disconnect all protocols and close the connection."); this.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); } /// /// Reload the vehicles drop-down with fresh data. /// public void reloadVehicles() { string selectedText = this.vehicleCB.Text; selectedText = selectedText != null ? selectedText.Trim() : null; this.vehicleCB.Items.Clear(); for (int i = 0; i < this.iDataSource.vehicles.Count; i++) { if (this.iDataSource.vehicles[i].name != null) { this.vehicleCB.Items.Add(this.iDataSource.vehicles[i].name); } } if (selectedText != null && selectedText.Length > 0 && this.vehicleCB.Items.Contains(selectedText)) { this.vehicleCB.Text = selectedText; } else { if (this.vehicleCB.Items.Count > 0) { this.vehicleCB.SelectedIndex = 0; } } } /// /// Close device (and all other opened/allocated items) /// public void closeDevice() { this.protocolSelectPanel1.enableFields(false); this.close(); this.readVersionBT.Enabled = false; this.lastErrorBT.Enabled = false; this.openBT.Enabled = true; this.quickOpenBT.Enabled = true; this.closeBT.Enabled = false; this.serialPortNameComboBox.Enabled = true; this.serialPortSpeedComboBox.Enabled = true; this.serialPortDatabitsComboBox.Enabled = true; this.serialPortParityComboBox.Enabled = true; this.serialPortStopBitsComboBox.Enabled = true; this.defaultValuesButton.Enabled = true; this.vehicleCB.Enabled = true; } /// /// Set the mapping of tree node to this instance. /// /// Tree node instance to map to this interface. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "panelTreeNode", Justification = "Reviewed, intentional.")] public void setPanelTreeNode(TreeNode panelTreeNode) { this.panelTreeNode = panelTreeNode; this.protocolSelectPanel1.setPanelTreeNode(this.applicationTree, (PanelTreeNode)panelTreeNode); } /// /// Update and populate the combo boxes for serial port data. /// /// Name of port that triggered the change, 'null' value permitted. public void refreshSerialPortInfo(string newPort) { if (this.serialPortNameComboBox.InvokeRequired) { try { this.serialPortNameComboBox.Invoke(new refreshSerialPortInfoFunc(this.refreshSerialPortInfo), new object[] { newPort }); } catch (ThreadAbortException) { throw; } catch (System.Reflection.TargetParameterCountException ex) { MessageBox.Show( "Exception: " + ex.Message + "\r\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (System.ObjectDisposedException) { // Ignore. } } else { try { this.refreshSerialPortInfoInt(newPort); } catch (Exception ex) { // Most likely because there is no serial port available. this.iLogging.appendText("refreshSerialPortInfoInt: " + ex.Message + "\r\n"); } } } /// /// Get the currently selected port name. /// /// Combo box presenting port name. /// Name of port. private static string getPortName(ComboBox cb) { string portName = null; if (cb.SelectedItem != null) { string value = (string)cb.SelectedItem.ToString(); //// this.iPreferences.setPreference(iPassThru.code + "_" + CanMain.SERIAL_PORT, value); string[] portNames = SerialPort.GetPortNames(); foreach (string name in portNames) { if (value.Contains("(" + name + ")") || (value.Trim().Length > 0 && value.Trim().Equals(name.Trim()))) { portName = name; break; } } } return portName; } /// /// Update and populate the combo boxes for serial port data. /// /// Name of port that triggered the change, 'null' value permitted. private delegate void refreshSerialPortInfoFunc(string newPort); /// /// Update and populate the combo boxes for serial port data. /// /// Name of port that triggered the change, 'null' value permitted. private void refreshSerialPortInfoInt(string newPort) { string[] portNames = SerialPort.GetPortNames(); List portInfo = new List(); using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity WHERE ClassGuid = '{4d36e978-e325-11ce-bfc1-08002be10318}'")) { foreach (ManagementObject queryObj in searcher.Get()) { portInfo.Add(queryObj["Caption"].ToString()); } } string defaultSerialPortName; this.iLogging.appendText("newPort='" + newPort + "', this.serialPortNameComboBox.Visible=" + this.serialPortNameComboBox.Visible + "\r\n"); if (newPort != null && this.serialPortNameComboBox.Visible) { defaultSerialPortName = newPort; this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_PORT, newPort); } else { defaultSerialPortName = this.iPreferences.getPreference(this.iPassThru.code + "_" + Utils.SERIAL_PORT); } this.serialPortParameters.serialPortName = defaultSerialPortName; int ix = 0; Array.Sort(portNames, new Utils.ComPortComparer()); int selIx = -1; this.serialPortNameComboBox.Items.Clear(); foreach (string portName in portNames) { string dispName = portName; foreach (string caption in portInfo) { if (caption.Contains("(" + portName + ")")) { dispName = caption; break; } } this.serialPortNameComboBox.Items.Add(dispName); if (defaultSerialPortName != null && defaultSerialPortName.Trim().Length > 0 && dispName.Contains("(" + defaultSerialPortName + ")")) { this.iLogging.appendText("dispName='" + dispName + "', defaultSerialPortName='" + defaultSerialPortName + "'\r\n"); selIx = ix; } ix++; } if (selIx >= 0) { this.serialPortNameComboBox.SelectedIndex = selIx; } else { if (this.serialPortNameComboBox.Items.Count > 0) { this.serialPortNameComboBox.SelectedIndex = 0; } } bool serialPortSelected = this.iPassThru.isSerial(); this.textBox1.Visible = serialPortSelected; this.serialPortLabel.Visible = serialPortSelected; this.serialPortSpeedLabel.Visible = serialPortSelected; this.serialPortDatabitsLabel.Visible = serialPortSelected; this.serialPortParityLabel.Visible = serialPortSelected; this.serialPortStopbitsLabel.Visible = serialPortSelected; this.serialPortNameComboBox.Visible = serialPortSelected; this.serialPortSpeedComboBox.Visible = serialPortSelected; this.serialPortDatabitsComboBox.Visible = serialPortSelected; this.serialPortParityComboBox.Visible = serialPortSelected; this.serialPortStopBitsComboBox.Visible = serialPortSelected; } /// /// Set the vehicle from preferences. /// private void setPreferredVehicle() { int preferredVehicle = this.iPreferences.getIntPreference(this.iPassThru.code + "_" + PreferencesFileAccess.VEHICLE); if (this.vehicleCB.Items.Count > 0) { if (preferredVehicle < this.vehicleCB.Items.Count) { this.vehicleCB.SelectedIndex = preferredVehicle; } else { this.vehicleCB.SelectedIndex = 0; } } } /// /// Store changed preference. /// /// Sending object. /// Event data. private void serialPortNameComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; if (cb.Focused) { string portName = getPortName(cb); if (portName != null) { this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_PORT, portName); this.serialPortParameters.serialPortName = portName; } } } /// /// Store changed preference. /// /// Sending object. /// Event data. private void serialPortSpeedComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; if (cb.Focused) { string value = (string)cb.SelectedItem.ToString(); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_SPEED, value); this.serialPortParameters.serialPortSpeed = Convert.ToInt32(value); } } /// /// Store changed preference. /// /// Sending object. /// Event data. private void serialPortDatabitsComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; if (cb.Focused) { string value = (string)cb.SelectedItem.ToString(); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_DATABITS, value); this.serialPortParameters.serialPortDatabits = Convert.ToInt32(value); } } /// /// Store changed preference. /// /// Sending object. /// Event data. private void serialPortParityComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; if (cb.Focused) { string value = (string)cb.SelectedItem.ToString(); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_PARITY, value); this.serialPortParameters.serialPortParity = (Parity)Enum.Parse(typeof(Parity), value); } } /// /// Store changed preference. /// /// Sending object. /// Event data. private void serialPortStopBitsComboBox_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cb = (ComboBox)sender; if (cb.Focused) { string value = (string)cb.SelectedItem.ToString(); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_STOPBITS, value); this.serialPortParameters.serialPortStopbits = (StopBits)Enum.Parse(typeof(StopBits), value); } } /// /// Handle click on Open button. /// /// Sending object. /// Event data. private void openBT_Click(object sender, EventArgs e) { this.openInterface(); } /// /// Quick-open interface. /// /// This will perform multiple steps using default /// values to ease the use of the application. /// /// /// Sending object. /// Event data. private void quickOpenBT_Click(object sender, EventArgs e) { Thread quickConnectThread = new Thread(new ThreadStart(this.quickConnectThreadImpl)); quickConnectThread.Name = "Quick Connect"; quickConnectThread.Start(); } /// /// Thread for quick connection. /// private void quickConnectThreadImpl() { if (this.openInterface()) { if (this.protocolSelectPanel1.detectProtocol()) { // Thread.Sleep(1000); ConnectionPanel connectionPanel = this.protocolSelectPanel1.prepareConnection(); if (connectionPanel != null) { // Thread.Sleep(1000); if (connectionPanel.performConnect()) { // Thread.Sleep(1000); if (connectionPanel.waitForInit()) { // Thread.Sleep(1000); connectionPanel.startObdUi(); } } } } } } /// /// Perform opening of interface. /// /// 'true' if successful. private delegate bool openInterfaceFunc(); /// /// Perform opening of interface. /// /// 'true' if successful. private bool openInterface() { bool success = false; if (this.InvokeRequired) { try { success = (bool)this.Invoke(new openInterfaceFunc(this.openInterface), new object[] { }); } catch (ThreadAbortException) { throw; } catch (System.Reflection.TargetParameterCountException ex) { MessageBox.Show( "Exception: " + ex.Message + "\r\n", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } catch (System.ObjectDisposedException) { // Ignore. } } else { this.vehicleCB.Enabled = false; try { if (this.serialPortParameters.serialPortName == null) { this.serialPortParameters.serialPortName = getPortName(this.serialPortNameComboBox); } if (this.iPassThru.isSerial()) { this.serialPortHandler = new SerialPortHandler(this.serialPortParameters); } else { this.serialPortHandler = null; } this.passThruDevice = new PassThruDevice(this.iLogging, this.iPassThru); this.iLogging.appendText("Selected API '" + this.passThruDevice.name + "'.\r\n", LogLevel.LOG_INFO); if (this.openDevice()) { int ix = this.vehicleCB.SelectedIndex; this.vehicle = this.iDataSource.vehicles[ix]; this.protocolSelectPanel1.init( this.iMiscFunc, this.iLogging, this.iPreferences, this.iDataSource, this.passThruDevice, this.iPassThru, this.vehicle, this.serialPortHandler, this.compositeObd, this.hintActivator, this.dataFileDir); this.protocolSelectPanel1.enableFields(true); this.protocolsEnabled = true; this.hintActivator.showHints(this); this.protocolSelectPanel1.Focus(); if (this.panelTreeNode != null) { this.panelTreeNode.ImageKey = "connect_green.png"; this.panelTreeNode.SelectedImageKey = "connect_green.png"; } success = true; } } catch (Exception ex) { MessageBox.Show( "Open Failed!\r\n" + ex.Message + "\r\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } return success; } /// /// Close the device. /// private void close() { if (this.protocolSelectPanel1 != null) { this.protocolSelectPanel1.disconnect(); } if (this.passThruDevice != null) { this.iLogging.appendText("Close API with PassThruClose().\r\n", LogLevel.LOG_DEBUG); PassThruConstants.resultCode status = this.passThruDevice.Gl_PassThruClose(); string errtext; if (!this.iLogging.errTestDevice(this.passThruDevice, status, out errtext)) { this.iLogging.appendText("Close res=" + status + ", errtxt=" + errtext + "\r\n"); MessageBox.Show( "Close Failed!\r\n" + errtext, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } else { this.iLogging.appendText("Close OK!\r\n"); this.passThruDevice = null; } } if (this.serialPortHandler != null) { this.serialPortHandler.close(); } if (this.panelTreeNode != null) { this.panelTreeNode.ImageKey = "disconnect_yellow.png"; this.panelTreeNode.SelectedImageKey = "disconnect_yellow.png"; } } /// /// Actual opening of device. /// /// 'true' on success. private bool openDevice() { bool success = false; if (this.passThruDevice != null) { this.iLogging.appendText("Open API with PassThruOpen().\r\n", LogLevel.LOG_DEBUG); PassThruConstants.resultCode status = this.passThruDevice.Gl_PassThruOpen(); string errtext; if (status != PassThruConstants.resultCode.ERR_SUCCESS && !this.iLogging.errTestDevice(this.passThruDevice, status, out errtext)) { this.iLogging.appendText("Open res=" + status + ", errtxt=" + errtext + "\r\n"); MessageBox.Show( "Open Failed!\r\n" + errtext, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } else { this.iLogging.appendText("Open OK!\r\n"); success = true; this.readVersion(); } } if (success) { this.readVersionBT.Enabled = !this.passThruDevice.passThruInterface.isSerial(); this.lastErrorBT.Enabled = !this.passThruDevice.passThruInterface.isSerial(); this.openBT.Enabled = false; this.quickOpenBT.Enabled = false; this.closeBT.Enabled = true; this.serialPortNameComboBox.Enabled = false; this.serialPortSpeedComboBox.Enabled = false; this.serialPortDatabitsComboBox.Enabled = false; this.serialPortParityComboBox.Enabled = false; this.serialPortStopBitsComboBox.Enabled = false; this.defaultValuesButton.Enabled = false; } return success; } /// /// Actual API version information. /// private void readVersion() { if (this.passThruDevice != null) { string ApiVersion; string DllVersion; string FirmwareVersion; this.iLogging.appendText("Read versions with PassThruReadVersion().\r\n", LogLevel.LOG_DEBUG); PassThruConstants.resultCode status = this.passThruDevice.Gl_PassThruReadVersion(out ApiVersion, out DllVersion, out FirmwareVersion); string errtext; if (!this.iLogging.errTestDevice(this.passThruDevice, status, out errtext)) { this.iLogging.appendText("ReadVersion res=" + status + ", errtxt=" + errtext + "\r\n"); MessageBox.Show( "ReadVersion Failed!\r\n" + errtext, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop); } else { this.iLogging.appendText("Read Version Api: " + ApiVersion + "\r\n"); this.iLogging.appendText("Read Version Dll: " + DllVersion + "\r\n"); this.iLogging.appendText("Read Version Firmware: " + FirmwareVersion + "\r\n"); } } } /// /// Request reading of API version information. /// /// Sending object. /// Event data. private void readVersionBT_Click(object sender, EventArgs e) { this.readVersion(); } /// /// Fetch last encountered Device error. /// /// Sending object. /// Event data. private void lastErrorBT_Click(object sender, EventArgs e) { if (this.passThruDevice != null) { this.iLogging.appendText("Last Device Error: " + this.passThruDevice.lastError + "\r\n"); } } /// /// Vehicle changed. /// /// Sending object. /// Event data. private void vehicleCB_SelectedIndexChanged(object sender, EventArgs e) { ComboBox item = (ComboBox)sender; if (item.Visible && item.Focused) { int ix = item.SelectedIndex; this.iPreferences.setPreference(this.iPassThru.code + "_" + PreferencesFileAccess.VEHICLE, ix.ToString()); this.vehicle = this.iDataSource.vehicles[ix]; if (this.vehicle.protocol != null) { this.protocolSelectPanel1.setProtocol(this.vehicle.protocol); } this.loadObdCodes(); if (this.compositeObd.obdcodes.Count == 0) { MessageBox.Show( "No OBD code explanations are loaded.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { this.iLogging.appendText(this.compositeObd.obdcodes.Count.ToString() + " OBD Codes loaded\r\n"); } } } /// /// Load OBD codes. /// private void loadObdCodes() { // Load OBD codes specific for the vehicle selected. this.compositeObd = new ObdCodeFileAccess(this.iLogging, true, this.dataFileDir); if (this.vehicleCB.SelectedIndex >= 0 && this.iDataSource.vehicles[this.vehicleCB.SelectedIndex].obdcodefile != null && this.iDataSource.vehicles[this.vehicleCB.SelectedIndex].obdcodefile.Trim().Length > 0) { this.specificObd = new ObdCodeFileAccess(this.iLogging, false, this.dataFileDir); this.specificObd.loadObdCodes(this.iDataSource.vehicles[this.vehicleCB.SelectedIndex].obdcodefile, false); this.compositeObd.addCodes(this.specificObd.obdcodes); } // Load the generic OBD codes that are specified to be valid for all vehicles. this.generalObd = new ObdCodeFileAccess(this.iLogging, false, this.dataFileDir); this.generalObd.loadObdCodes(DataSourceImplementation.OBDCODES_FILE, false); this.compositeObd.addCodes(this.generalObd.obdcodes); if (this.compositeObd.obdcodes.Count == 0) { MessageBox.Show( "No OBD code explanations are loaded.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } /// /// Initialize the panel with data and enable view of the appropriate items. /// private void init() { bool serialPortSelected = this.iPassThru.isSerial(); if (serialPortSelected) { SerialAtPassThru serialPassThru = (SerialAtPassThru)this.iPassThru; this.serialPortParameters = serialPassThru.serialPortParameters; this.getSavedParameterData(); string portName = getPortName(this.serialPortNameComboBox); if (portName != null) { this.serialPortParameters.serialPortName = portName; } this.updateSerialPortDataFields(); } this.serialPortLabel.Visible = serialPortSelected; this.serialPortSpeedLabel.Visible = serialPortSelected; this.serialPortDatabitsLabel.Visible = serialPortSelected; this.serialPortParityLabel.Visible = serialPortSelected; this.serialPortStopbitsLabel.Visible = serialPortSelected; this.serialPortNameComboBox.Visible = serialPortSelected; this.serialPortSpeedComboBox.Visible = serialPortSelected; this.serialPortDatabitsComboBox.Visible = serialPortSelected; this.serialPortParityComboBox.Visible = serialPortSelected; this.serialPortStopBitsComboBox.Visible = serialPortSelected; this.defaultValuesButton.Visible = serialPortSelected; this.openBT.Enabled = true; this.quickOpenBT.Enabled = true; } /// /// Update the data fields for a serial port. /// private void updateSerialPortDataFields() { this.serialPortSpeedComboBox.SelectedIndex = 3; int ix = 0; foreach (string str in this.serialPortSpeedComboBox.Items) { if (Convert.ToInt32(str) == this.serialPortParameters.serialPortSpeed) { this.serialPortSpeedComboBox.SelectedIndex = ix; break; } ix++; } this.serialPortDatabitsComboBox.SelectedIndex = 1; ix = 0; foreach (string str in this.serialPortDatabitsComboBox.Items) { if (Convert.ToInt32(str) == this.serialPortParameters.serialPortDatabits) { this.serialPortDatabitsComboBox.SelectedIndex = ix; break; } ix++; } ix = 0; int selIx = -1; foreach (Parity parity in Enum.GetValues(typeof(Parity))) { this.serialPortParityComboBox.Items.Add(parity); if (parity == this.serialPortParameters.serialPortParity) { selIx = ix; } ix++; } if (selIx >= 0) { this.serialPortParityComboBox.SelectedIndex = selIx; } else { if (this.serialPortParityComboBox.Items.Count > 0) { this.serialPortParityComboBox.SelectedIndex = 0; } } ix = 0; foreach (StopBits stopBits in Enum.GetValues(typeof(StopBits))) { this.serialPortStopBitsComboBox.Items.Add(stopBits); if (stopBits == this.serialPortParameters.serialPortStopbits) { selIx = ix; } ix++; } if (selIx >= 0) { this.serialPortStopBitsComboBox.SelectedIndex = selIx; } else { if (this.serialPortStopBitsComboBox.Items.Count > 0) { this.serialPortStopBitsComboBox.SelectedIndex = 0; } } } /// /// Fetch the saved serial port parameters for the interface. /// /// Notice that each interface has it's own set of parameters. /// /// private void getSavedParameterData() { int speed = this.iPreferences.getIntPreference(this.iPassThru.code + "_" + Utils.SERIAL_SPEED); if (speed > 0) { this.serialPortParameters.serialPortSpeed = speed; } int datbits = this.iPreferences.getIntPreference(this.iPassThru.code + "_" + Utils.SERIAL_DATABITS); if (datbits > 0) { this.serialPortParameters.serialPortDatabits = datbits; } string parityStr = this.iPreferences.getPreference(this.iPassThru.code + "_" + Utils.SERIAL_PARITY); if (parityStr != null) { this.serialPortParameters.serialPortParity = (Parity)Enum.Parse(typeof(Parity), parityStr); } string stopbitsStr = this.iPreferences.getPreference(this.iPassThru.code + "_" + Utils.SERIAL_STOPBITS); if (stopbitsStr != null) { this.serialPortParameters.serialPortStopbits = (StopBits)Enum.Parse(typeof(StopBits), stopbitsStr); } } /// /// Close device (and all other opened/allocated items) /// /// Sending object. /// Event data. private void closeBT_Click(object sender, EventArgs e) { this.closeDevice(); this.protocolSelectPanel1.enableFields(false); this.protocolsEnabled = false; this.hintActivator.showHints(this); } /// /// Set the default values for the interface. /// /// Sending object. /// Event data. private void defaultValuesButton_Click(object sender, EventArgs e) { bool serialPortSelected = this.iPassThru.isSerial(); if (serialPortSelected) { SerialAtPassThru serialPassThru = (SerialAtPassThru)this.iPassThru; this.serialPortParameters = serialPassThru.serialPortParameters; this.updateSerialPortDataFields(); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_SPEED, this.serialPortParameters.serialPortSpeed.ToString()); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_DATABITS, this.serialPortParameters.serialPortDatabits.ToString()); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_PARITY, this.serialPortParameters.serialPortParity.ToString()); this.iPreferences.setPreference(this.iPassThru.code + "_" + Utils.SERIAL_STOPBITS, this.serialPortParameters.serialPortStopbits.ToString()); } } } }