/// <summary>
      /// Writes the auto pin fallback.
      /// </summary>
      /// <param name="port">The port.</param>
      /// <param name="isEnabled">The is enabled.</param>
      public static void WriteAutoPinFallback(PortData port, string isEnabled)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var isActive = GetTextAsValue(isEnabled);

         instance.proxy.WriteIsPinFallbackTimerActive(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), isActive);
      }
      /// <summary>
      /// Writes the index of the init second.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      public static void WriteInitSecondIndex(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.WriteInitSecondIndex(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));
      }
        /// <summary>
        /// RADs the page view1 selected page changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MainPageViewSelectedPageChanged(object sender, EventArgs e)
        {
            if (this.mainPageView.SelectedPage.Name.ToUpper() == "PAGEPORTS")
            {
                if (this.activePort != null)
                {
                    this.LoadPortStatus();
                }
            }

            if (this.mainPageView.SelectedPage.Name.ToUpper() == "PAGESCANMATRIXCODE")
            {
                if (this.activePort == null)
                {
                    this.activePort = this.portList.FirstOrDefault(p => p.IsActive);
                }

                this.tvMatrixCodePorts.SelectedNode = this.GetTreeNodeForPort(this.tvMatrixCodePorts, this.activePort);

                //if (this.tvMatrixCodePorts.SelectedNode == null)
                //{
                //   var selected = false;
                //   foreach (var defNode in this.tvMatrixCodePorts.Nodes)
                //   {
                //      foreach (var portNode in defNode.Nodes)
                //      {
                //         this.tvMatrixCodePorts.SelectedNode = portNode;
                //         selected = true;
                //         break;
                //      }

                //      if (selected)
                //      {
                //         break;
                //      }
                //   }
                //}

                //if (this.tvMatrixCodePorts.SelectedNode != null)
                //{
                //   this.activePort =
                //      this.PortList.FirstOrDefault(p => p.PortName == this.tvMatrixCodePorts.SelectedNode.Name);
                //   this.TvMatrixCodePortsSelectedNodeChanged(this, new RadTreeViewEventArgs(this.tvMatrixCodePorts.SelectedNode));
                //}
            }

            if (this.mainPageView.SelectedPage.Name.ToUpper() == "PAGEEXPORT")
            {
                this.InitGridExcel();

                var rowNum = 0;
                foreach (var port in portList.Where(p => p.IsActive))
                {
                    this.gvExcel.Rows.AddNew();
                    this.gvExcel.Rows[rowNum].Cells[0].Value = port.TestStationId.ToString();

                    var pubKey = port.ParameterList.Find(p => p.Id == ParameterId.PublicKey).RealValue;
                    this.gvExcel.Rows[rowNum].Cells[1].Value = pubKey != null ? pubKey.Replace("-", string.Empty) : string.Empty;

                    var manufSerialNo = port.ParameterList.Find(p => p.Id == ParameterId.ManufacturerSerialNumber).RealValue;
                    this.gvExcel.Rows[rowNum].Cells[2].Value = manufSerialNo ?? string.Empty;

                    var serverId = port.ParameterList.Find(p => p.Id == ParameterId.ServerId).RealValue;
                    this.gvExcel.Rows[rowNum].Cells[3].Value = serverId != null ? serverId.Replace("-", string.Empty) : string.Empty;

                    var eigNr = port.ParameterList.Find(p => p.Id == ParameterId.Eigentumsnummer).TargetValue ?? string.Empty;
                    this.gvExcel.Rows[rowNum].Cells[4].Value = string.Format("{0}", eigNr);

                    var typ = port.ParameterList.Find(p => p.Id == ParameterId.Typ).TargetValue;
                    this.gvExcel.Rows[rowNum].Cells[5].Value = typ ?? string.Empty;

                    var pincode = port.ParameterList.Find(p => p.Id == ParameterId.PinCode).TargetValue;
                    this.gvExcel.Rows[rowNum].Cells[6].Value = pincode ?? string.Empty;

                    rowNum++;
                }

                // modify excel#2 filename
                var eportTwoFileName = Properties.Settings.Default.ExportFilePathTwo;
                var activePorts = this.portList.Where(p => p.IsActive);

                var firstPort = activePorts.FirstOrDefault();
                if (firstPort != null)
                {
                    var serialParam = firstPort.ParameterList.FirstOrDefault(p => p.Id == ParameterId.ManufacturerSerialNumber);
                    if (serialParam != null)
                    {
                        eportTwoFileName = eportTwoFileName.Replace("{0}", serialParam.TargetValue);
                    }
                }

                var lastPort = activePorts.LastOrDefault();
                if (lastPort != null)
                {
                    var serialParam = lastPort.ParameterList.FirstOrDefault(p => p.Id == ParameterId.ManufacturerSerialNumber);
                    if (serialParam != null)
                    {
                        eportTwoFileName = eportTwoFileName.Replace("{1}", serialParam.TargetValue);
                        this.txtExportPathTwo.Text = eportTwoFileName;
                    }
                }
            }
        }
      /// <summary>
      /// Disables the manufacturer mode.
      /// </summary>
      /// <param name="port">The meter bench port.</param>
      public static void DisableManufacturerMode(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.ConfigureManufacturerMode(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), false);
      }
      /// <summary>
      /// Writes the power on LCD enabled.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="isEnabled">The is enabled.</param>
      public static void WritePowerOnLcdEnabled(PortData port, string isEnabled)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var isActive = GetTextAsValue(isEnabled);

         instance.proxy.WriteIsCurrentPowerOnDisplayAllowed(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), isActive);
      }
        /// <summary>
        /// Handler for matrix code ports selected node changed event.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.WinControls.UI.RadTreeViewEventArgs"/> instance containing the event data.</param>
        private void TvMatrixCodePortsSelectedNodeChanged(object sender, RadTreeViewEventArgs e)
        {
            // clear real value (read from scanner) textbox contents
            this.txtScanPublicKeyReal.Text = string.Empty;
            this.txtScanServerIdReal.Text = string.Empty;
            this.txtScanSerialNoReal.Text = string.Empty;
            this.txtScanEigentumsnrReal.Text = string.Empty;
            this.txtScanTypCodeReal.Text = string.Empty;

            // get the port instance

            if (e.Node == null)
            {
                return;
            }

            this.activePort = this.PortList.Find(p => p.PortName == e.Node.Name);
            if (this.activePort == null)
            {
                return;
            }

            this.lblActiveScanPort.Text = string.Format("{0}", this.activePort.TestStationId);

            // set target value textbox contents to parameterized values
            var param = this.activePort.ParameterList.Find(prt => prt.Id == ParameterId.PublicKey);
            this.txtScanPublicKeyTarget.Text = param.RealValue == null ? "???" : param.RealValue.Replace("-", string.Empty);

            param = this.activePort.ParameterList.Find(prt => prt.Id == ParameterId.ServerId);
            this.txtScanServerIdTarget.Text = param.RealValue == null ? "???" : param.RealValue.Replace("-", string.Empty);

            param = this.activePort.ParameterList.Find(prt => prt.Id == ParameterId.ManufacturerSerialNumber);
            this.txtScanSerialNoTarget.Text = param.RealValue ?? "???";

            param = this.activePort.ParameterList.Find(prt => prt.Id == ParameterId.Eigentumsnummer);
            this.txtScanEigentumsnrTarget.Text = param.TargetValue ?? "???";

            param = this.activePort.ParameterList.Find(prt => prt.Id == ParameterId.Typ);
            this.txtScanTypCodeTarget.Text = param.TargetValue ?? "???";
        }
 /// <summary>
 /// Writes the number of tariffs.
 /// </summary>
 /// <param name="port">The meter bench port.</param>
 /// <param name="numberOfTariffs">The number of tariffs.</param>
 public static void WriteNumberOfTariffs(PortData port, int numberOfTariffs)
 {
    instance.proxy.WriteNumberOfTariffs(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), (byte)numberOfTariffs);
 }
      /// <summary>
      /// Writes the info interface status.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="isEnabled">The enabled flag.</param>
      public static void WriteInfoInterfaceStatus(PortData port, string isEnabled)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var isActive = GetTextAsValue(isEnabled);

         instance.proxy.WriteIsInfoInterfaceActivated(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), isActive);
      }
      /// <summary>
      /// Writes the server id.
      /// </summary>
      /// <param name="port">The meter bench port.</param>
      /// <param name="serverId">The server id.</param>
      public static void WriteServerId(PortData port, string serverId)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var servIdBytes = Utils.ByteArray.FromHexString(serverId);
         instance.proxy.WriteServerId(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), servIdBytes);
      }
      /// <summary>
      /// Reads the number of tariffs.
      /// </summary>
      /// <param name="port">The meter bench port.</param>
      /// <returns>The number of tariffs.</returns>
      public static int ReadNumberOfTariffs(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var readNumberOfTariffs = instance.proxy.ReadNumberOfTariffs(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));

         if (readNumberOfTariffs.Data.HasValue)
         {
            return (int)readNumberOfTariffs.Data.Value;
         }

         return 0;
      }
      /// <summary>
      /// Reads the server id.
      /// </summary>
      /// <param name="port">The meter bench port.</param>
      /// <returns>The server id read.</returns>
      public static string ReadServerId(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var readServerId = instance.proxy.ReadServerId(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));
         return BitConverter.ToString(readServerId.Data);
      }
      /// <summary>
      /// Activates the pin.
      /// </summary>
      /// <param name="port">The meter bench port.</param>
      public static void ActivatePin(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.WriteIsPinProtectionActive(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), true);
      }
 /// <summary>
 /// Sets the pin.
 /// </summary>
 /// <param name="port">The meter bench port.</param>
 /// <param name="pinCode">The pin code.</param>
 public static void WritePinCode(PortData port, string pinCode)
 {
    instance.proxy.WritePin(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), pinCode);
 }
      /// <summary>
      /// Writes the terminal control reverse.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="isReversedText">The is reversed text.</param>
      public static void WriteTerminalControlReverse(PortData port, string isReversedText)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var isReversed = GetTextAsValue(isReversedText);

         instance.proxy.WriteIsTerminalControlReverse(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), isReversed);
      }
      public static string ReadMeasurementMode(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var readMeasurementMode = instance.proxy.ReadMeasurementMode(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));
         if (readMeasurementMode.Data.HasValue)
         {
            string modeCode = string.Empty;
            switch (readMeasurementMode.Data.Value)
            {
               case 0x08:
                  modeCode = "1";
                  break;
               case 0x0A:
                  modeCode = "2";
                  break;
               case 0x02:
                  modeCode = "3";
                  break;
               case 0x01:
                  modeCode = "4";
                  break;
               default:
                  modeCode = string.Format("[BCD]{0}", readMeasurementMode.Data.Value);
                  break;
            }

            return string.Format("MM{0}", modeCode);
         }

         return string.Empty;
      }
      /// <summary>
      /// Reads the info interface status.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <returns>The info interface status read.</returns>
      public static string ReadInfoInterfaceStatus(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         string boolRes = string.Empty;
         var boolParam = instance.proxy.ReadIsInfoInterfaceActivated(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));

         if (boolParam.Data.HasValue)
         {
            return GetValueAsText(boolParam.Data.Value);
         }

         return boolRes;
      }
      /// <summary>
      /// Writes the measurement mode.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="measurementMode">The measurement mode.</param>
      public static void WriteMeasurementMode(PortData port, string measurementMode)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.WriteMeasurementMode(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), measurementMode);
      }
      /// <summary>
      /// Reads the power on LCD enabled.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <returns>The text status whether power on lcd is enabled.</returns>
      public static string ReadPowerOnLcdEnabled(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         string boolRes = string.Empty;
         var boolParam = instance.proxy.ReadIsCurrentPowerOnDisplayAllowed(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));

         if (boolParam.Data.HasValue)
         {
            return GetValueAsText(boolParam.Data.Value);
         }

         return boolRes;
      }
      /// <summary>
      /// Writes the manufacturer serial number.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="serialNumber">The serial number.</param>
      public static void WriteManufacturerSerialNumber(PortData port, string serialNumber)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.WriteManufacturerSerialNumber(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), serialNumber);
      }
 /// <summary>
 /// Handler for ports selected node changed event.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="Telerik.WinControls.UI.RadTreeViewEventArgs"/> instance containing the event data.</param>
 private void TvParameterizationPortsSelectedNodeChanged(object sender, RadTreeViewEventArgs e)
 {
     this.activePort = this.PortList.Find(p => p.PortName == e.Node.Name);
     Task.Run(
         () => this.InvokeEx(f => f.LoadPortStatus()));
 }
      /// <summary>
      /// Reads the production id.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <returns>The production id read.</returns>
      public static string ReadProductionId(PortData port)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         var num = instance.proxy.ReadProductionId(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName));

         return Encoding.UTF8.GetString(num.Data);
      }
        /// <summary>
        /// Gets the tree node for port.
        /// </summary>
        /// <param name="treeView">The tree view.</param>
        /// <param name="port">The port.</param>
        /// <returns></returns>
        private RadTreeNode GetTreeNodeForPort(RadTreeView treeView, PortData port)
        {
            if (port == null)
            {
                return null;
            }

            foreach (var defNode in treeView.Nodes)
            {
                foreach (var portNode in defNode.Nodes)
                {
                    if (port.PortName.Equals(portNode.Name))
                    {
                        return portNode;
                    }
                }
            }

            return null;
        }
      /// <summary>
      /// Writes the production id.
      /// </summary>
      /// <param name="port">The meter test bench port.</param>
      /// <param name="productionId">The production id.</param>
      public static void WriteProductionId(PortData port, string productionId)
      {
         if (instance.isInitialized == false)
         {
            throw new InvalidOperationException("instance.proxy not initialized.");
         }

         instance.proxy.WriteProductionId(instance.serviceGuid, instance.servicePorts.Find(p => p.ComPortName == port.PortName), productionId);
      }
        /// <summary>
        /// Inits this instance.
        /// </summary>
        public void Init()
        {
            // Load persisted data.
            this.InitData();

            // Init portlist and sort ascending
            var ports = (from qP in SerialPort.GetPortNames()
                         orderby System.Text.RegularExpressions.Regex.Replace(qP, "~\\d", string.Empty).PadLeft(6, '0')
                         select qP).ToArray();

            // Get included ports from configuration file
            var includedPorts = Properties.Settings.Default.IncludedPorts.Split(
               new[] { ", ", "," }, StringSplitOptions.RemoveEmptyEntries);


            // load portlist with values from last run
            if (File.Exists(this.ParamValFileName))
            {
                try
                {
                    var persistedValueList = ParamUtil.LoadParameterValuesFromFile(this.ParamValFileName);
                    if (persistedValueList != null)
                    {
                        this.portList.Clear();
                        this.portList.AddRange(persistedValueList);
                        this.activePort = this.portList.FirstOrDefault();

                        return;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error("Could not read stored parameter values from file.");
                }
            }

            // If param value list is not existing or values could not be loaded create that ones from the definition.
            // Create the port's own parameters by copying all from definition
            var portCnt = 0;
            this.PortList.Clear();
            foreach (var port in ports)
            {
                if (includedPorts.Contains(port) == false)
                {
                    continue;
                }

                var newPort = new PortData()
                {
                    PortName = port,
                    ActiveParameterDefinition = this.activeDefinition,
                    ParameterList = new List<Parameter>(),
                    ComStatus = PortComStatus.Idle,
                    IsActive = true,
                    TestStationId = ++portCnt
                };

                // Copy the parameters from the definition to this port
                foreach (var defaultParam in this.activeDefinition.ParameterList)
                {
                    var portParam = (Parameter)defaultParam.Clone();
                    newPort.ParameterList.Add(portParam);
                }

                this.PortList.Add(newPort);
            }
        }
 /// <summary>
 /// Loads the port params.
 /// </summary>
 public static void LoadPortParamGrid(RadGridView gridView, PortData activePort)
 {
     gridView.InvokeEx(
             gv =>
                 {
                     gv.DataSource = null;
                     gv.DataSource = activePort.ParameterList;
                     gv.ResetBindings();
                     gv.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
                 });
 }