private void TerminalAdvancedBtn_Click(object sender, EventArgs e)
 {
     try
     {
         Gurux.Terminal.GXTerminal terminal = SelectedMedia as Gurux.Terminal.GXTerminal;
         terminal.PortName    = this.TerminalPortCB.Text;
         terminal.PhoneNumber = this.TerminalPhoneNumberTB.Text;
         if (SelectedMedia.Properties(this))
         {
             this.TerminalPortCB.Text        = terminal.PortName;
             this.TerminalPhoneNumberTB.Text = terminal.PhoneNumber;
         }
     }
     catch (Exception Ex)
     {
         GXDLMS.Common.Error.ShowError(this, Ex);
     }
 }
        public DevicePropertiesForm(GXManufacturerCollection manufacturers, GXDLMSDevice dev)
        {
            try
            {
                InitializeComponent();
                NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp });
                this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged);
                NetworkSettingsGB.Width = this.Width - NetworkSettingsGB.Left;
                SerialSettingsGB.Bounds = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds;
                ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed;
                Manufacturers = manufacturers;
                //OK button is not enabled if there are no manufacturers.
                if (Manufacturers.Count == 0)
                {
                    OKBtn.Enabled = false;
                }
                //Show supported services tab only when they are read.
                if (dev == null || dev.Comm.client.SNSettings == null && dev.Comm.client.LNSettings == null)
                {
                    DeviceTab.TabPages.Remove(SupportedServicesTab);
                }
                else
                {
                    object settings = null;
                    if (dev.Comm.client.UseLogicalNameReferencing)
                    {
                        settings = dev.Comm.client.LNSettings;
                    }
                    else
                    {
                        settings = dev.Comm.client.SNSettings;
                    }
                    if (settings != null)
                    {
                        SupportedServicesGrid.SelectedObject = settings;
                        foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(settings))
                        {
                            ReadOnlyAttribute att = (ReadOnlyAttribute)it.Attributes[typeof(ReadOnlyAttribute)];
                            if (att != null)
                            {
                                FieldInfo[] f = att.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
                                f[0].SetValue(att, true);
                            }
                        }
                    }
                }
                Device = dev;
                StartProtocolCB.Items.Add(StartProtocolType.IEC);
                StartProtocolCB.Items.Add(StartProtocolType.DLMS);
                int pos = 0;
                foreach (GXManufacturer it in Manufacturers)
                {
                    int index = this.ManufacturerCB.Items.Add(it);
                    if (it.Name == GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer)
                    {
                        pos = index;
                    }
                }
                if (Device == null)
                {
                    Device = new GXDLMSDevice(null);
                    //Select first manufacturer.
                    if (Manufacturers.Count != 0)
                    {
                        ManufacturerCB.SelectedIndex = pos;
                    }
                }
                else
                {
                    foreach (GXManufacturer it in this.ManufacturerCB.Items)
                    {
                        if (string.Compare(it.Identification, Device.Manufacturer, true) == 0)
                        {
                            this.ManufacturerCB.SelectedItem = it;
                            break;
                        }
                    }
                    this.VerboseModeCB.Checked = dev.Verbose;
                    this.NameTB.Text = dev.Name;
                    SelectedMedia = dev.Media;
                    UseRemoteSerialCB.Checked = Device.UseRemoteSerial;
                    StartProtocolCB.SelectedItem = Device.StartProtocol;
                    PhysicalServerAddressTB.Value = Convert.ToDecimal(Device.PhysicalAddress);
                    LogicalServerAddressTB.Value = Convert.ToDecimal(Device.LogicalAddress);
                    this.ClientAddTB.Value = Convert.ToDecimal(Convert.ToUInt32(Device.ClientAddress));
                    WaitTimeTB.Value = Device.WaitTime;
                }

                ManufacturerCB.DrawMode = MediasCB.DrawMode = DrawMode.OwnerDrawFixed;
                Gurux.Net.GXNet net = new Gurux.Net.GXNet();
                //Initialize network settings.
                if (SelectedMedia is GXNet)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    net.Protocol = Gurux.Net.NetworkType.Tcp;
                    this.HostNameTB.Text = ((GXNet)SelectedMedia).HostName;
                    this.PortTB.Text = ((GXNet)SelectedMedia).Port.ToString();
                    NetProtocolCB.SelectedItem = ((GXNet)SelectedMedia).Protocol;
                }
                else
                {
                    NetProtocolCB.SelectedItem = net.Protocol = Gurux.Net.NetworkType.Tcp;
                    this.MediasCB.Items.Add(net);
                }

                //Set maximum baud rate.
                GXSerial serial = new GXSerial();
                foreach (int it in serial.GetAvailableBaudRates(""))
                {
                    if (it != 0)
                    {
                        MaximumBaudRateCB.Items.Add(it);
                    }
                }
                if (Device.MaximumBaudRate == 0)
                {
                    UseMaximumBaudRateCB.Checked = false;
                    UseMaximumBaudRateCB_CheckedChanged(null, null);
                }
                else
                {
                    UseMaximumBaudRateCB.Checked = true;
                    this.MaximumBaudRateCB.SelectedItem = Device.MaximumBaudRate;
                }

                if (SelectedMedia is GXSerial)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    string[] ports = GXSerial.GetPortNames();
                    this.SerialPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        this.SerialPortCB.SelectedItem = ((GXSerial)SelectedMedia).PortName;
                    }
                }
                else
                {
                    //Initialize serial settings.
                    string[] ports = GXSerial.GetPortNames();
                    this.SerialPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        serial.PortName = ports[0];
                    }
                    if (((GXManufacturer)ManufacturerCB.SelectedItem).StartProtocol == StartProtocolType.DLMS)
                    {
                        serial.BaudRate = 9600;
                        serial.DataBits = 8;
                        serial.Parity = Parity.None;
                        serial.StopBits = StopBits.One;
                    }
                    else
                    {
                        serial.BaudRate = 300;
                        serial.DataBits = 7;
                        serial.Parity = Parity.Even;
                        serial.StopBits = StopBits.One;
                    }
                    this.MediasCB.Items.Add(serial);
                }
                if (SelectedMedia is Gurux.Terminal.GXTerminal)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    string[] ports = GXTerminal.GetPortNames();
                    this.TerminalPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        this.TerminalPortCB.SelectedItem = ((Gurux.Terminal.GXTerminal)SelectedMedia).PortName;
                    }
                    this.TerminalPhoneNumberTB.Text = ((Gurux.Terminal.GXTerminal)SelectedMedia).PhoneNumber;
                }
                else
                {
                    //Initialize terminal settings.
                    Gurux.Terminal.GXTerminal termial = new Gurux.Terminal.GXTerminal();
                    string[] ports = GXTerminal.GetPortNames();
                    this.TerminalPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        termial.PortName = ports[0];
                    }
                    termial.BaudRate = 9600;
                    termial.DataBits = 8;
                    termial.Parity = Parity.None;
                    termial.StopBits = StopBits.One;
                    this.TerminalPhoneNumberTB.Text = termial.PhoneNumber;
                    //termial.InitializeCommands = "AT+CBST=71,0,1\r\n";
                    this.MediasCB.Items.Add(termial);
                }
                //Select first media if medis is not selected.
                if (SelectedMedia == null)
                {
                    SelectedMedia = (Gurux.Common.IGXMedia)this.MediasCB.Items[0];
                }
                this.MediasCB.SelectedItem = SelectedMedia;
                if (!string.IsNullOrEmpty(Device.Password))
                {
                    this.PasswordTB.Text = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Device.Password, Password.Key));
                }
                if (dev != null)
                {
                    this.UseLNCB.Checked = dev.UseLogicalNameReferencing;
                }
                this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged);
                bool bConnected = Device.Media != null && Device.Media.IsOpen;
                SerialPortCB.Enabled = AdvancedBtn.Enabled = ManufacturerCB.Enabled = MediasCB.Enabled =
                    AuthenticationCB.Enabled = UseRemoteSerialCB.Enabled = OKBtn.Enabled = !bConnected;
                HostNameTB.ReadOnly = PortTB.ReadOnly = PasswordTB.ReadOnly = WaitTimeTB.ReadOnly = PhysicalServerAddressTB.ReadOnly = NameTB.ReadOnly = bConnected;
            }
            catch (Exception Ex)
            {
                GXDLMS.Common.Error.ShowError(this, Ex);
            }
        }
        public DevicePropertiesForm(GXManufacturerCollection manufacturers, GXDLMSDevice dev)
        {
            try
            {
                InitializeComponent();
                SecurityCB.Items.AddRange(new object[] { Security.None, Security.Authentication,
                                                         Security.Encryption, Security.AuthenticationEncryption });
                NetProtocolCB.Items.AddRange(new object[] { NetworkType.Tcp, NetworkType.Udp });
                this.ServerAddressTypeCB.SelectedIndexChanged += new System.EventHandler(this.ServerAddressTypeCB_SelectedIndexChanged);
                NetworkSettingsGB.Width      = this.Width - NetworkSettingsGB.Left;
                SerialSettingsGB.Bounds      = TerminalSettingsGB.Bounds = NetworkSettingsGB.Bounds;
                ServerAddressTypeCB.DrawMode = AuthenticationCB.DrawMode = DrawMode.OwnerDrawFixed;
                Manufacturers = manufacturers;
                //OK button is not enabled if there are no manufacturers.
                if (Manufacturers.Count == 0)
                {
                    OKBtn.Enabled = false;
                }
                //Show supported services tab only when they are read.
                if (dev == null || dev.Comm.client.SNSettings == null && dev.Comm.client.LNSettings == null)
                {
                    DeviceTab.TabPages.Remove(SupportedServicesTab);
                }
                else
                {
                    object settings = null;
                    if (dev.Comm.client.UseLogicalNameReferencing)
                    {
                        settings = dev.Comm.client.LNSettings;
                    }
                    else
                    {
                        settings = dev.Comm.client.SNSettings;
                    }
                    if (settings != null)
                    {
                        SupportedServicesGrid.SelectedObject = settings;
                        foreach (PropertyDescriptor it in TypeDescriptor.GetProperties(settings))
                        {
                            ReadOnlyAttribute att = (ReadOnlyAttribute)it.Attributes[typeof(ReadOnlyAttribute)];
                            if (att != null)
                            {
                                FieldInfo[] f = att.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
                                f[0].SetValue(att, true);
                            }
                        }
                    }
                }
                Device = dev;
                StartProtocolCB.Items.Add(StartProtocolType.IEC);
                StartProtocolCB.Items.Add(StartProtocolType.DLMS);
                int pos = 0;
                foreach (GXManufacturer it in Manufacturers)
                {
                    int index = this.ManufacturerCB.Items.Add(it);
                    if (it.Name == GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer)
                    {
                        pos = index;
                    }
                }
                if (Device == null)
                {
                    Device = new GXDLMSDevice(null);
                    //Select first manufacturer.
                    if (Manufacturers.Count != 0)
                    {
                        ManufacturerCB.SelectedIndex = pos;
                    }
                }
                else
                {
                    foreach (GXManufacturer it in this.ManufacturerCB.Items)
                    {
                        if (string.Compare(it.Identification, Device.Manufacturer, true) == 0)
                        {
                            this.ManufacturerCB.SelectedItem = it;
                            break;
                        }
                    }
                    this.VerboseModeCB.Checked = dev.Verbose;
                    this.NameTB.Text           = dev.Name;
                    SelectedMedia                 = dev.Media;
                    UseRemoteSerialCB.Checked     = Device.UseRemoteSerial;
                    StartProtocolCB.SelectedItem  = Device.StartProtocol;
                    PhysicalServerAddressTB.Value = Convert.ToDecimal(Device.PhysicalAddress);
                    LogicalServerAddressTB.Value  = Convert.ToDecimal(Device.LogicalAddress);
                    this.ClientAddTB.Value        = Convert.ToDecimal(Convert.ToUInt32(Device.ClientAddress));
                    WaitTimeTB.Value              = Device.WaitTime;
                    SecurityCB.SelectedItem       = dev.Security;
                    SystemTitleTB.Text            = dev.SystemTitle;
                    BlockCipherKeyTB.Text         = dev.BlockCipherKey;
                    AuthenticationKeyTB.Text      = dev.AuthenticationKey;
                    UseUtcTimeZone.Checked        = Device.UtcTimeZone;
                }

                ManufacturerCB.DrawMode = MediasCB.DrawMode = DrawMode.OwnerDrawFixed;
                Gurux.Net.GXNet net = new Gurux.Net.GXNet();
                //Initialize network settings.
                if (SelectedMedia is GXNet)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    net.Protocol               = Gurux.Net.NetworkType.Tcp;
                    this.HostNameTB.Text       = ((GXNet)SelectedMedia).HostName;
                    this.PortTB.Text           = ((GXNet)SelectedMedia).Port.ToString();
                    NetProtocolCB.SelectedItem = ((GXNet)SelectedMedia).Protocol;
                }
                else
                {
                    NetProtocolCB.SelectedItem = net.Protocol = Gurux.Net.NetworkType.Tcp;
                    this.MediasCB.Items.Add(net);
                }

                //Set maximum baud rate.
                GXSerial serial = new GXSerial();
                foreach (int it in serial.GetAvailableBaudRates(""))
                {
                    if (it != 0)
                    {
                        MaximumBaudRateCB.Items.Add(it);
                    }
                }
                if (Device.MaximumBaudRate == 0)
                {
                    UseMaximumBaudRateCB.Checked = false;
                    UseMaximumBaudRateCB_CheckedChanged(null, null);
                }
                else
                {
                    UseMaximumBaudRateCB.Checked        = true;
                    this.MaximumBaudRateCB.SelectedItem = Device.MaximumBaudRate;
                }

                if (SelectedMedia is GXSerial)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    string[] ports = GXSerial.GetPortNames();
                    this.SerialPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        this.SerialPortCB.SelectedItem = ((GXSerial)SelectedMedia).PortName;
                    }
                }
                else
                {
                    //Initialize serial settings.
                    string[] ports = GXSerial.GetPortNames();
                    this.SerialPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        serial.PortName = ports[0];
                    }
                    if (((GXManufacturer)ManufacturerCB.SelectedItem).StartProtocol == StartProtocolType.DLMS)
                    {
                        serial.BaudRate = 9600;
                        serial.DataBits = 8;
                        serial.Parity   = Parity.None;
                        serial.StopBits = StopBits.One;
                    }
                    else
                    {
                        serial.BaudRate = 300;
                        serial.DataBits = 7;
                        serial.Parity   = Parity.Even;
                        serial.StopBits = StopBits.One;
                    }
                    this.MediasCB.Items.Add(serial);
                }
                if (SelectedMedia is Gurux.Terminal.GXTerminal)
                {
                    this.MediasCB.Items.Add(SelectedMedia);
                    string[] ports = GXTerminal.GetPortNames();
                    this.TerminalPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        this.TerminalPortCB.SelectedItem = ((Gurux.Terminal.GXTerminal)SelectedMedia).PortName;
                    }
                    this.TerminalPhoneNumberTB.Text = ((Gurux.Terminal.GXTerminal)SelectedMedia).PhoneNumber;
                }
                else
                {
                    //Initialize terminal settings.
                    Gurux.Terminal.GXTerminal termial = new Gurux.Terminal.GXTerminal();
                    string[] ports = GXTerminal.GetPortNames();
                    this.TerminalPortCB.Items.AddRange(ports);
                    if (ports.Length != 0)
                    {
                        termial.PortName = ports[0];
                    }
                    termial.BaudRate = 9600;
                    termial.DataBits = 8;
                    termial.Parity   = Parity.None;
                    termial.StopBits = StopBits.One;
                    this.TerminalPhoneNumberTB.Text = termial.PhoneNumber;
                    //termial.InitializeCommands = "AT+CBST=71,0,1\r\n";
                    this.MediasCB.Items.Add(termial);
                }
                //Select first media if medis is not selected.
                if (SelectedMedia == null)
                {
                    SelectedMedia = (Gurux.Common.IGXMedia) this.MediasCB.Items[0];
                }
                this.MediasCB.SelectedItem = SelectedMedia;
                if (!string.IsNullOrEmpty(Device.Password))
                {
                    this.PasswordTB.Text = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(Device.Password, Password.Key));
                }
                if (dev != null)
                {
                    this.UseLNCB.Checked = dev.UseLogicalNameReferencing;
                }
                this.AuthenticationCB.SelectedIndexChanged += new System.EventHandler(this.AuthenticationCB_SelectedIndexChanged);
                bool bConnected = Device.Media != null && Device.Media.IsOpen;
                SerialPortCB.Enabled         = AdvancedBtn.Enabled = ManufacturerCB.Enabled = MediasCB.Enabled =
                    AuthenticationCB.Enabled = UseRemoteSerialCB.Enabled = OKBtn.Enabled = !bConnected;
                HostNameTB.ReadOnly          = PortTB.ReadOnly = PasswordTB.ReadOnly = WaitTimeTB.ReadOnly = PhysicalServerAddressTB.ReadOnly = NameTB.ReadOnly = bConnected;
            }
            catch (Exception Ex)
            {
                GXDLMS.Common.Error.ShowError(this, Ex);
            }
        }
        /// <summary>
        /// Apply new settings from property pages.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OKBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string name = NameTB.Text.Trim();
                if (name.Length == 0)
                {
                    throw new Exception("Invalid name.");
                }
                GXServerAddress server = (GXServerAddress)ServerAddressTypeCB.SelectedItem;
                if (server.HDLCAddress == HDLCAddressType.SerialNumber && PhysicalServerAddressTB.Value == 0)
                {
                    throw new Exception("Invalid Serial Number.");
                }
                GXManufacturer man = (GXManufacturer)ManufacturerCB.SelectedItem;
                Device.Authentication = ((GXAuthentication)this.AuthenticationCB.SelectedItem).Type;
                if (Device.Authentication != Authentication.None)
                {
                    Device.Password = CryptHelper.Encrypt(this.PasswordTB.Text, Password.Key);
                }
                else
                {
                    Device.Password = "";
                }
                Device.Name            = name;
                Device.Media           = SelectedMedia;
                Device.Manufacturer    = man.Identification;
                Device.WaitTime        = Convert.ToInt32(WaitTimeTB.Value);
                Device.Verbose         = VerboseModeCB.Checked;
                Device.MaximumBaudRate = 0;
                Device.UtcTimeZone     = UseUtcTimeZone.Checked;

                if (SelectedMedia is GXSerial)
                {
                    Device.UseRemoteSerial = false;

                    if (this.SerialPortCB.Text.Length == 0)
                    {
                        throw new Exception("Invalid serial port.");
                    }
                    ((GXSerial)SelectedMedia).PortName = this.SerialPortCB.Text;
                    if (UseMaximumBaudRateCB.Checked)
                    {
                        Device.MaximumBaudRate = (int)MaximumBaudRateCB.SelectedItem;
                    }
                }
                else if (SelectedMedia is GXNet)
                {
                    if (this.HostNameTB.Text.Length == 0)
                    {
                        throw new Exception("Invalid host name.");
                    }
                    ((GXNet)SelectedMedia).HostName = this.HostNameTB.Text;
                    int port;
                    if (!Int32.TryParse(this.PortTB.Text, out port))
                    {
                        throw new Exception("Invalid port number.");
                    }
                    ((GXNet)SelectedMedia).Port     = port;
                    Device.UseRemoteSerial          = UseRemoteSerialCB.Checked;
                    ((GXNet)SelectedMedia).Protocol = (NetworkType)NetProtocolCB.SelectedItem;
                }
                else if (SelectedMedia is Gurux.Terminal.GXTerminal)
                {
                    if (this.TerminalPortCB.Text.Length == 0)
                    {
                        throw new Exception("Invalid serial port.");
                    }
                    if (this.TerminalPhoneNumberTB.Text.Length == 0)
                    {
                        throw new Exception("Invalid phone number.");
                    }
                    Gurux.Terminal.GXTerminal terminal = SelectedMedia as Gurux.Terminal.GXTerminal;
                    terminal.ConfigurableSettings = Gurux.Terminal.AvailableMediaSettings.All & ~Gurux.Terminal.AvailableMediaSettings.Server;
                    Device.UseRemoteSerial        = false;
                    terminal.PortName             = this.TerminalPortCB.Text;
                    terminal.PhoneNumber          = this.TerminalPhoneNumberTB.Text;
                }
                GXAuthentication authentication = (GXAuthentication)AuthenticationCB.SelectedItem;
                Device.HDLCAddressing = ((GXServerAddress)ServerAddressTypeCB.SelectedItem).HDLCAddress;
                Device.ClientAddress  = Convert.ToInt32(ClientAddTB.Value);
                if (Device.HDLCAddressing == HDLCAddressType.SerialNumber)
                {
                    Device.PhysicalAddress = PhysicalServerAddressTB.Value;
                }
                else
                {
                    Device.PhysicalAddress = Convert.ChangeType(PhysicalServerAddressTB.Value, server.PhysicalAddress.GetType());
                }
                Device.UseLogicalNameReferencing = this.UseLNCB.Checked;
                Device.LogicalAddress            = Convert.ToInt32(LogicalServerAddressTB.Value);
                Device.StartProtocol             = (StartProtocolType)this.StartProtocolCB.SelectedItem;
                GXDLMSDirector.Properties.Settings.Default.SelectedManufacturer = man.Name;

                Device.Security          = (Security)SecurityCB.SelectedItem;
                Device.SystemTitle       = SystemTitleTB.Text;
                Device.BlockCipherKey    = BlockCipherKeyTB.Text;
                Device.AuthenticationKey = AuthenticationKeyTB.Text;
            }
            catch (Exception Ex)
            {
                this.DialogResult = DialogResult.None;
                GXDLMS.Common.Error.ShowError(this, Ex);
            }
        }