Exemplo n.º 1
0
        private static GXDLMSSeasonProfile[] LoadSeasonProfile(GXXmlReader reader, string name)
        {
            List <GXDLMSSeasonProfile> list = new List <GXDLMSSeasonProfile>();

            if (reader.IsStartElement(name, true))
            {
                while (reader.IsStartElement("Item", true))
                {
                    GXDLMSSeasonProfile it = new GXDLMSSeasonProfile();
                    it.Name     = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("Name"));
                    it.Start    = new GXDateTime(reader.ReadElementContentAsString("Start"), CultureInfo.InvariantCulture);
                    it.WeekName = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("WeekName"));
                    list.Add(it);
                }
                reader.ReadEndElement(name);
            }
            return(list.ToArray());
        }
Exemplo n.º 2
0
        private void UpdateValue(TextBox value, bool ascii)
        {
            string str = GetAsHex(value.Text, !ascii, true);

            if (ascii)
            {
                if (!IsAscii(GXDLMSTranslator.HexToBytes(str)))
                {
                    value.Select();
                    throw new ArgumentOutOfRangeException("There are non ASCII chars.");
                }
                value.Text = ASCIIEncoding.ASCII.GetString(GXDLMSTranslator.HexToBytes(str));
            }
            else
            {
                value.Text = str;
            }
        }
        void IGXDLMSBase.Load(GXXmlReader reader)
        {
            SecurityPolicy = (SecurityPolicy)reader.ReadElementContentAsInt("SecurityPolicy");
            //This is old functionality.It can be removed in some point.
            reader.ReadElementContentAsInt("SecurityPolicy0");
            SecuritySuite = (SecuritySuite)reader.ReadElementContentAsInt("SecuritySuite");
            string str = reader.ReadElementContentAsString("ClientSystemTitle");

            if (str == null)
            {
                ClientSystemTitle = null;
            }
            else
            {
                ClientSystemTitle = GXDLMSTranslator.HexToBytes(str);
            }
            str = reader.ReadElementContentAsString("ServerSystemTitle");
            if (str == null)
            {
                ServerSystemTitle = null;
            }
            else
            {
                ServerSystemTitle = GXDLMSTranslator.HexToBytes(str);
            }
            Certificates.Clear();
            if (reader.IsStartElement("Certificates", true))
            {
                while (reader.IsStartElement("Item", true))
                {
                    GXDLMSCertificateInfo it = new GXDLMSCertificateInfo();
                    Certificates.Add(it);
                    it.Entity         = (CertificateEntity)reader.ReadElementContentAsInt("Entity");
                    it.Type           = (CertificateType)reader.ReadElementContentAsInt("Type");
                    it.SerialNumber   = BigInteger.Parse(reader.ReadElementContentAsString("SerialNumber"));
                    it.Issuer         = reader.ReadElementContentAsString("Issuer");
                    it.Subject        = reader.ReadElementContentAsString("Subject");
                    it.SubjectAltName = reader.ReadElementContentAsString("SubjectAltName");
                }
                reader.ReadEndElement("Certificates");
            }
        }
Exemplo n.º 4
0
 private void OkBtn_Click(object sender, EventArgs e)
 {
     try
     {
         if (NameTb.Text.Length == 0)
         {
             throw new Exception("Invalid name.");
         }
         if (AsciiBtn.Checked)
         {
             Target.Name = ASCIIEncoding.ASCII.GetBytes(NameTb.Text);
         }
         else
         {
             Target.Name = GXDLMSTranslator.HexToBytes(NameTb.Text);
         }
         if (Target.Name.Length == 0)
         {
             throw new Exception("Invalid name.");
         }
         try
         {
             Target.Monday    = ((GXDLMSDayProfile)MondayCb.SelectedItem).DayId;
             Target.Tuesday   = ((GXDLMSDayProfile)TuesdayCb.SelectedItem).DayId;
             Target.Wednesday = ((GXDLMSDayProfile)WednesdayCb.SelectedItem).DayId;
             Target.Thursday  = ((GXDLMSDayProfile)ThursdayCb.SelectedItem).DayId;
             Target.Friday    = ((GXDLMSDayProfile)FridayCb.SelectedItem).DayId;
             Target.Saturday  = ((GXDLMSDayProfile)SaturdayCb.SelectedItem).DayId;
             Target.Sunday    = ((GXDLMSDayProfile)SundayCb.SelectedItem).DayId;
         }
         catch (System.NullReferenceException)
         {
             throw new Exception("Invalid day profile.");
         }
     }
     catch (Exception ex)
     {
         DialogResult = DialogResult.None;
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// Convert message to XML.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TranslateBtn_Click(object sender, EventArgs e)
        {
            MessageXmlTB.Text = "";
            StringBuilder sb = new StringBuilder();
            GXByteBuffer  bb = new GXByteBuffer();
            //TODO: This can remove later.
            Security s = translator.Security;

            try
            {
                translator.Clear();
                UpdateSecurity();
                translator.Security = Security.Authentication;

                translator.PduOnly = PduOnlyCB.Checked;
                GXByteBuffer pdu = new GXByteBuffer();
                bb.Set(GXDLMSTranslator.HexToBytes(RemoveComments(MessagePduTB.Text)));
                InterfaceType type = GXDLMSTranslator.GetDlmsFraming(bb);
                int           cnt  = 1;
                while (translator.FindNextFrame(bb, pdu, type))
                {
                    int    start = bb.Position;
                    string tmp   = translator.MessageToXml(bb);
                    sb.AppendLine(cnt + ": " + bb.ToHex(true, start, bb.Position - start));
                    ++cnt;
                    sb.Append(tmp);
                    pdu.Clear();
                }
                MessageXmlTB.Text   = sb.ToString();
                translator.Security = s;
            }
            catch (Exception ex)
            {
                translator.Security = s;
                MessageXmlTB.AppendText(sb.ToString());
                MessageXmlTB.AppendText(Environment.NewLine);
                MessageXmlTB.AppendText(bb.RemainingHexString(true));

                MessageBox.Show(this, ex.Message);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Try to get identification from xml file.
 /// </summary>
 /// <param name="nodes">XML nodes.</param>
 /// <returns>Found dentification.</returns>
 public static void GetImage(XmlNodeList nodes, ref byte[] image)
 {
     foreach (XmlNode it in nodes)
     {
         if (it.NodeType == XmlNodeType.Element && it.ChildNodes.Count == 1 && it.ChildNodes[0].NodeType == XmlNodeType.Text)
         {
             byte[] tmp = GXDLMSTranslator.HexToBytes(it.InnerText);
             if (image == null || tmp.Length > image.Length)
             {
                 image = tmp;
             }
         }
         else
         {
             if (it.ChildNodes.Count != 0 && it.FirstChild.NodeType != XmlNodeType.Text)
             {
                 GetImage(it.ChildNodes, ref image);
             }
         }
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Generate private key and certificate for the client.
 /// </summary>
 private void PrivatekeyBtn_Click(object sender, EventArgs e)
 {
     try
     {
         GXEcdsaKeysDlg dlg = new GXEcdsaKeysDlg(_address, _keysPath,
                                                 _certificatesPath,
                                                 _title,
                                                 SecuritySuite,
                                                 GXDLMSTranslator.HexToBytes(SystemTitle));
         if (dlg.ShowDialog(Parent) == DialogResult.OK)
         {
             _privateKeys.Import(_keysPath);
             _certifications.Import(_certificatesPath);
             ShowKeys();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(Parent, ex.Message);
     }
 }
 private void TemplateDescriptionTb_Leave(object sender, EventArgs e)
 {
     try
     {
         DataType          v;
         GXByteBuffer      bb     = new GXByteBuffer();
         GXDLMSCompactData target = Target as GXDLMSCompactData;
         bb.SetUInt8(2);
         bb.SetUInt8(0);
         foreach (string it in TemplateDescriptionTb.Text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
         {
             if (!Enum.TryParse <DataType>(it, out v))
             {
                 bb.Clear();
                 break;
             }
             bb.SetUInt8((byte)v);
         }
         byte[] tmp;
         if (bb.Size != 0)
         {
             bb.SetUInt8(1, (byte)(bb.Size - 2));
             tmp = bb.Array();
         }
         else
         {
             tmp = GXDLMSTranslator.HexToBytes(TemplateDescriptionTb.Text);
         }
         if (GXDLMSTranslator.ToHex(tmp) != GXDLMSTranslator.ToHex(target.TemplateDescription))
         {
             target.TemplateDescription = tmp;
             Target.UpdateDirty(5, target.TemplateDescription);
             errorProvider1.SetError(TemplateDescriptionTb, Properties.Resources.ValueChangedTxt);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Register selected meters.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void RegisterMnu_Click(object sender, EventArgs e)
 {
     try
     {
         if (MetersView.SelectedItems.Count == 1)
         {
             ListViewItem       li  = MetersView.SelectedItems[0];
             GXDLMSPlcMeterInfo mi  = (GXDLMSPlcMeterInfo)li.Tag;
             GXPlcRegisterDlg   dlg = new GXPlcRegisterDlg(GXDLMSTranslator.HexToBytes(Settings.Default.PlcSerialSettingsActiveInitiator), mi.SystemTitle);
             if (dlg.ShowDialog(this) == DialogResult.OK)
             {
                 GXDLMSDevice dev = new GXDLMSDevice(media);
                 dev.Comm.client.InterfaceType = (InterfaceType)Settings.Default.PlcInterface;
                 media.Open();
                 GXReplyData reply = new GXReplyData();
                 dev.Comm.client.Plc.MacSourceAddress = dlg.MacAddress;
                 Settings.Default.PlcSerialSettingsActiveInitiator = GXDLMSTranslator.ToHex(dlg.ActiveInitiatorSystemTitle);
                 byte[] data = dev.Comm.client.Plc.RegisterRequest(dlg.ActiveInitiatorSystemTitle, dlg.NewSystemTitle);
                 dev.Comm.ReadDLMSPacket(data, reply);
                 data = dev.Comm.client.Plc.DiscoverRequest();
                 dev.Comm.ReadDLMSPacket(data, reply);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     finally
     {
         try
         {
             media.Close();
         }
         catch (Exception ex)
         {
             MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
 }
Exemplo n.º 10
0
 private void FindBtn_Click(object sender, EventArgs e)
 {
     try
     {
         if (LogicalNameRb.Checked)
         {
             //If OBIS code is given as hex.
             if (FindTb.Text.IndexOf('.') == -1)
             {
                 byte[] tmp = GXDLMSTranslator.HexToBytes(FindTb.Text);
                 if (tmp.Length != 6)
                 {
                     throw new Exception("Invalid OBIS code.");
                 }
                 parameters.ObisCode = tmp[5].ToString() + '.' + tmp[4] + '.' + tmp[3] + '.' + tmp[2] + '.' + tmp[1] + '.' + tmp[0] + '.';
             }
             else if (FindTb.Text.Split(new char[] { '.' }).Length != 6)
             {
                 throw new Exception("Invalid OBIS code.");
             }
             parameters.ObisCode = FindTb.Text.Trim();
             parameters.Text     = null;
         }
         else
         {
             parameters.ObisCode = null;
             parameters.Text     = FindTb.Text.Trim();
             if (string.IsNullOrEmpty(parameters.Text))
             {
                 throw new Exception("Invalid text to search for.");
             }
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(this, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         DialogResult = DialogResult.None;
     }
 }
        /// <summary>
        /// Accept changes.
        /// </summary>
        private void OKBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (KekAsciiCb.Checked)
                {
                    Kek = ASCIIEncoding.ASCII.GetBytes(KekTb.Text);
                }
                else
                {
                    Kek = GXDLMSTranslator.HexToBytes(KekTb.Text);
                }
                if (Kek.Length != 16)
                {
                    throw new Exception("Key Encryption Key is invalid.");
                }
                if (KeyAsciiCb.Checked)
                {
                    Key = ASCIIEncoding.ASCII.GetBytes(KeyTb.Text);
                }
                else
                {
                    Key = GXDLMSTranslator.HexToBytes(KeyTb.Text);
                }
                if (Key.Length != 16)
                {
                    throw new Exception("Key is invalid.");
                }

                Type = (GlobalKeyType)SecurityPolicyTB.SelectedItem;
                Properties.Settings.Default.SecurityKey = GXDLMSTranslator.ToHex(Key, false);
                Properties.Settings.Default.SecurityKek = GXDLMSTranslator.ToHex(Kek, false);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(this, Ex.Message);
                DialogResult = DialogResult.None;
            }
        }
Exemplo n.º 12
0
 private void OkBtn_Click(object sender, EventArgs e)
 {
     try
     {
         if (DataTypeCb.SelectedItem == null)
         {
             throw new Exception("Data type is not selected.");
         }
         if (DataTb.Text == "")
         {
             throw new Exception("Invalid data.");
         }
         Data.ValueInformation = GXDLMSTranslator.HexToBytes(ValueInformationTb.Text);
         Data.DataInformation  = GXDLMSTranslator.HexToBytes(DataInformationTb.Text);
         Data.Data             = Convert.ChangeType(Data, GXDLMSConverter.GetDataType((DataType)DataTypeCb.SelectedItem));
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         DialogResult = DialogResult.None;
     }
 }
Exemplo n.º 13
0
 private void OkBtn_Click(object sender, EventArgs e)
 {
     try
     {
         ActiveInitiatorSystemTitle = GXDLMSTranslator.HexToBytes(ActiveInitiatorTb.Text);
         if (ActiveInitiatorSystemTitle.Length != 8 && ActiveInitiatorSystemTitle.Length != 6)
         {
             throw new Exception("Invalid active initiator system title.");
         }
         NewSystemTitle = GXDLMSTranslator.HexToBytes(SystemTitleTb.Text);
         if (NewSystemTitle.Length != 8 && NewSystemTitle.Length != 6)
         {
             throw new Exception("Invalid new system title.");
         }
         MacAddress = UInt16.Parse(MACAddressTb.Text);
     }
     catch (Exception ex)
     {
         DialogResult = DialogResult.None;
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// Update server system title if Italy standard is used.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void ServerSystemTitle_TextChanged(object sender, EventArgs e)
 {
     try
     {
         int len = ServerSystemTitleTb.Text.Replace(" ", "").Length;
         if (len != 0 && len != 16)
         {
             throw new Exception("Invalid system title.");
         }
         toolTip1.SetToolTip(ServerSystemTitleTb, null);
         if (len == 16)
         {
             byte[] tmp = GXDLMSTranslator.HexToBytes(ServerSystemTitleTb.Text);
             toolTip1.SetToolTip(ServerSystemTitleTb, GXDLMSConverter.SystemTitleToString(_standard, tmp, true));
         }
     }
     catch (Exception ex)
     {
         ServerSystemTitleTb.Select();
         MessageBox.Show(Parent, ex.Message);
     }
 }
        void IGXDLMSBase.Load(GXXmlReader reader)
        {
            string str = reader.ReadElementContentAsString("Secret");

            if (str == null)
            {
                Secret = null;
            }
            else
            {
                Secret = GXDLMSTranslator.HexToBytes(str);
            }
            str = reader.ReadElementContentAsString("HlsSecret");
            if (str == null)
            {
                HlsSecret = null;
            }
            else
            {
                HlsSecret = GXDLMSTranslator.HexToBytes(str);
            }
            SecuritySetupReference = reader.ReadElementContentAsString("SecuritySetupReference");
        }
Exemplo n.º 16
0
 /// <summary>
 /// Try to get identification from xml file.
 /// </summary>
 /// <param name="nodes">XML nodes.</param>
 /// <returns>Found dentification.</returns>
 public static byte[] GetIdentification(XmlNodeList nodes)
 {
     foreach (XmlNode it in nodes)
     {
         if (it.NodeType == XmlNodeType.Element && it.ChildNodes.Count == 1 && it.ChildNodes[0].NodeType == XmlNodeType.Text &&
             it.Name.Contains("Identification"))
         {
             return(GXDLMSTranslator.HexToBytes(it.InnerText));
         }
         else
         {
             if (it.ChildNodes.Count != 0 && it.FirstChild.NodeType != XmlNodeType.Text)
             {
                 byte[] ret = GetIdentification(it.ChildNodes);
                 if (ret != null)
                 {
                     return(ret);
                 }
             }
         }
     }
     return(null);
 }
        private static GXDLMSWeekProfile[] LoadWeekProfileTable(GXXmlReader reader, string name)
        {
            List <GXDLMSWeekProfile> list = new List <GXDLMSWeekProfile>();

            if (reader.IsStartElement(name, true))
            {
                while (reader.IsStartElement("Item", true))
                {
                    GXDLMSWeekProfile it = new GXDLMSWeekProfile();
                    it.Name      = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("Name"));
                    it.Monday    = reader.ReadElementContentAsInt("Monday");
                    it.Tuesday   = reader.ReadElementContentAsInt("Tuesday");
                    it.Wednesday = reader.ReadElementContentAsInt("Wednesday");
                    it.Thursday  = reader.ReadElementContentAsInt("Thursday");
                    it.Friday    = reader.ReadElementContentAsInt("Friday");
                    it.Saturday  = reader.ReadElementContentAsInt("Saturday");
                    it.Sunday    = reader.ReadElementContentAsInt("Sunday");
                    list.Add(it);
                }
                reader.ReadEndElement(name);
            }
            return(list.ToArray());
        }
Exemplo n.º 18
0
 public void WriteElementObject(string name, object value, DataType type, DataType uiType)
 {
     if (type != DataType.None && value is string)
     {
         if (type == DataType.OctetString)
         {
             if (uiType == DataType.String)
             {
                 value = ASCIIEncoding.ASCII.GetBytes((string)value);
             }
             else if (uiType == DataType.OctetString)
             {
                 value = GXDLMSTranslator.HexToBytes((string)value);
             }
         }
         else if (!(value is GXDateTime))
         {
             Type newType = GXDLMSConverter.GetDataType(type);
             value = Convert.ChangeType(value, newType);
         }
     }
     WriteElementObject(name, value, true);
 }
Exemplo n.º 19
0
        void IGXDLMSBase.Load(GXXmlReader reader)
        {
            DataLinkLayerReference = reader.ReadElementContentAsString("DataLinkLayerReference");
            IPAddress = reader.ReadElementContentAsString("IPAddress");
            List <UInt32> list = new List <UInt32>();

            if (reader.IsStartElement("MulticastIPAddress", true))
            {
                while (reader.IsStartElement("Value", false))
                {
                    list.Add((UInt32)reader.ReadElementContentAsInt("Value"));
                }
                reader.ReadEndElement("MulticastIPAddress");
            }
            MulticastIPAddress = list.ToArray();

            List <GXDLMSIp4SetupIpOption> ipOptions = new List <GXDLMSIp4SetupIpOption>();

            if (reader.IsStartElement("IPOptions", true))
            {
                while (reader.IsStartElement("IPOptions", true))
                {
                    GXDLMSIp4SetupIpOption it = new GXDLMSIp4SetupIpOption();
                    it.Type   = (Ip4SetupIpOptionType)reader.ReadElementContentAsInt("Type");
                    it.Length = (byte)reader.ReadElementContentAsInt("Length");
                    it.Data   = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("Data"));
                    ipOptions.Add(it);
                }
                reader.ReadEndElement("IPOptions");
            }
            IPOptions           = ipOptions.ToArray();
            SubnetMask          = reader.ReadElementContentAsULong("SubnetMask");
            GatewayIPAddress    = reader.ReadElementContentAsULong("GatewayIPAddress");
            UseDHCP             = reader.ReadElementContentAsInt("UseDHCP") != 0;
            PrimaryDNSAddress   = reader.ReadElementContentAsULong("PrimaryDNSAddress");
            SecondaryDNSAddress = reader.ReadElementContentAsULong("SecondaryDNSAddress");
        }
Exemplo n.º 20
0
 private void VerifyBtn_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect = false;
         if (SigningKeyTb.Text == "" || Path.GetFileName(SigningKeyTb.Text) == "")
         {
             dlg.InitialDirectory = Directory.GetCurrentDirectory();
             dlg.Filter           = Properties.Resources.PemFilterTxt;
             dlg.DefaultExt       = ".pem";
             dlg.ValidateNames    = true;
             if (dlg.ShowDialog(this) == DialogResult.OK)
             {
                 SigningKeyTb.Text = dlg.FileName;
             }
             else
             {
                 return;
             }
         }
         GXPkcs8 key   = GXPkcs8.Load(SigningKeyTb.Text);
         GXEcdsa ecdsa = new GXEcdsa(key.PublicKey);
         if (ecdsa.Verify(GXDLMSTranslator.HexToBytes(SignatureTb.Text), File.ReadAllBytes(FileNameTb.Text)))
         {
             MessageBox.Show(this, "Verification succeeded.", "Signature verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             MessageBox.Show(this, "Verification failed.", "Signature verification", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 21
0
        void IGXDLMSBase.Load(GXXmlReader reader)
        {
            PHYReference = reader.ReadElementContentAsString("PHYReference");
            List <GXDLMSPppSetupLcpOption> options = new List <GXDLMSPppSetupLcpOption>();

            if (reader.IsStartElement("LCPOptions", true))
            {
                while (reader.IsStartElement("Item", true))
                {
                    GXDLMSPppSetupLcpOption it = new GXDLMSPppSetupLcpOption();
                    it.Type   = (PppSetupLcpOptionType)reader.ReadElementContentAsInt("Type");
                    it.Length = (byte)reader.ReadElementContentAsInt("Length");
                    it.Data   = reader.ReadElementContentAsObject("Data", null);
                }
                reader.ReadEndElement("LCPOptions");
            }
            LCPOptions = options.ToArray();

            List <GXDLMSPppSetupIPCPOption> list = new List <GXDLMSPppSetupIPCPOption>();

            if (reader.IsStartElement("IPCPOptions", true))
            {
                while (reader.IsStartElement("Item", true))
                {
                    GXDLMSPppSetupIPCPOption it = new GXDLMSPppSetupIPCPOption();
                    it.Type   = (PppSetupIPCPOptionType)reader.ReadElementContentAsInt("Type");
                    it.Length = (byte)reader.ReadElementContentAsInt("Length");
                    it.Data   = reader.ReadElementContentAsObject("Data", null);
                }
                reader.ReadEndElement("IPCPOptions");
            }
            IPCPOptions = list.ToArray();

            UserName = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("UserName"));
            Password = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("Password"));
        }
Exemplo n.º 22
0
 private void OkBtn_Click(object sender, EventArgs e)
 {
     try
     {
         SystemTitle = GXDLMSTranslator.HexToBytes(SystemTitleTb.Text);
         if (SystemTitle.Length != 8)
         {
             throw new ArgumentOutOfRangeException("Invalid system title.");
         }
         if (DigitalSignatureCb.Checked)
         {
             CertificateType = CertificateType.DigitalSignature;
         }
         else if (KeyAgreementCb.Checked)
         {
             CertificateType = CertificateType.KeyAgreement;
         }
         else
         {
             if (ServerTlsCb.Checked)
             {
                 ExtendedKeyUsage = ExtendedKeyUsage.ServerAuth;
             }
             else
             {
                 ExtendedKeyUsage = ExtendedKeyUsage.ClientAuth;
             }
             CertificateType = CertificateType.TLS;
         }
     }
     catch (Exception ex)
     {
         DialogResult = DialogResult.None;
         MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Exemplo n.º 23
0
 void OnShowDialog(GXActionArgs arg)
 {
     if (InvokeRequired)
     {
         BeginInvoke(new ShowDialogEventHandler(OnShowDialog), arg).AsyncWaitHandle.WaitOne();
     }
     else
     {
         GXTextDlg dlg = new GXTextDlg("Transfer token", "Token", "", typeof(byte[]));
         if (dlg.ShowDialog(this) == DialogResult.OK)
         {
             GXByteBuffer bb = new GXByteBuffer();
             bb.SetUInt8((byte)DataType.OctetString);
             byte[] str = GXDLMSTranslator.HexToBytes(dlg.GetValue());
             bb.SetUInt8((byte)str.Length);
             bb.Set(str);
             arg.Value = bb.Array();
         }
         else
         {
             arg.Handled = true;
         }
     }
 }
Exemplo n.º 24
0
        static public object ChangeType(object value, DataType type, CultureInfo cultureInfo)
        {
            object ret;

            if (type == DataType.OctetString)
            {
                if (value is byte[])
                {
                    ret = value;
                }
                else
                {
                    ret = GXDLMSTranslator.HexToBytes((string)value);
                }
            }
            else if (type == DataType.DateTime)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXDateTime((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Date)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXDate((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Time)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXTime((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Enum)
            {
                if (value is GXEnum)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXEnum((byte)Convert.ChangeType(value, typeof(byte)));
                }
            }
            else if (type == DataType.Structure || type == DataType.Array)
            {
                ret = GXDLMSTranslator.XmlToValue((string)value);
            }
            else if (type == DataType.BitString)
            {
                ret = new GXBitString((string)value);
            }
            else if (type == DataType.None && value is string && string.IsNullOrEmpty((string)value))
            {
                ret = null;
            }
            else
            {
                ret = Convert.ChangeType(value, GXDLMSConverter.GetDataType(type), cultureInfo);
            }
            return(ret);
        }
 public void PreAction(GXActionArgs arg)
 {
     //Add object to association view.
     if (arg.Index == 3)
     {
         GXDLMSObject it = new GXDLMSData();
         OnShowDialog(it, arg);
     }
     else if (arg.Index == 4)
     {
         // Remove object from association view.
         OnShowDialog(null, arg);
     }
     //Add user to user list.
     else if (arg.Index == 5)
     {
         OnShowDialog(true, arg);
     }
     else if (arg.Index == 6)
     {
         // Remove user from user list.
         OnShowDialog(false, arg);
     }
     if (arg.Action == ActionType.Write && arg.Index == 7)
     {
         DialogResult ret;
         //Update pw.
         ret = GXHelpers.ShowMessageBox(this, Properties.Resources.SetPasswordWarning, "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
         if (ret == DialogResult.Yes)
         {
             byte[] value;
             if (SecretAsciiCb.Checked)
             {
                 value = ASCIIEncoding.ASCII.GetBytes(SecretTB.Text);
             }
             else
             {
                 value = GXDLMSTranslator.HexToBytes(SecretTB.Text);
             }
             GXDLMSAssociationLogicalName target = Target as GXDLMSAssociationLogicalName;
             if (target.AuthenticationMechanismName.MechanismId == Authentication.Low)
             {
                 arg.Index  = 7;
                 arg.Action = ActionType.Write;
             }
             else
             {
                 arg.Action = ActionType.Action;
                 arg.Index  = 2;
             }
             if (arg.Action == ActionType.Write)
             {
                 target.Secret = value;
             }
             else
             {
                 GXByteBuffer bb = new GXByteBuffer();
                 bb.SetUInt8((byte)DataType.OctetString);
                 bb.SetUInt8((byte)value.Length);
                 bb.Set(value);
                 arg.Value = bb.Array();
             }
         }
         arg.Handled = ret != DialogResult.Yes;
     }
     else if (arg.Action == ActionType.Write && arg.Index == 2)
     {
         //Skip write invoke.
         arg.Handled = true;
     }
 }
Exemplo n.º 26
0
        static public object ChangeType(object value, DataType type, CultureInfo cultureInfo)
        {
            object ret;

            if (type == DataType.OctetString)
            {
                if (value is byte[])
                {
                    ret = value;
                }
                else
                {
                    ret = GXDLMSTranslator.HexToBytes((string)value);
                }
            }
            else if (type == DataType.DateTime)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXDateTime((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Date)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXDate((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Time)
            {
                if (value is GXDateTime)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXTime((string)value, CultureInfo.InvariantCulture);
                }
            }
            else if (type == DataType.Enum)
            {
                if (value is GXEnum)
                {
                    ret = value;
                }
                else
                {
                    ret = new GXEnum((byte)Convert.ChangeType(value, typeof(byte)));
                }
            }
            else
            {
                ret = Convert.ChangeType(value, GXDLMSConverter.GetDataType(type));
            }
            return(ret);
        }
Exemplo n.º 27
0
 void IGXDLMSBase.Load(GXXmlReader reader)
 {
     SystemTitle  = GXDLMSTranslator.HexToBytes(reader.ReadElementContentAsString("SystemTitle"));
     MacAddress   = (UInt16)reader.ReadElementContentAsInt("MacAddress");
     LSapSelector = (byte)reader.ReadElementContentAsInt("LSapSelector");
 }
        /// <summary>
        /// Convert message to XML.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TranslateBtn_Click(object sender, EventArgs e)
        {
            MessageXmlTB.Text = "";
            StringBuilder sb = new StringBuilder();
            GXByteBuffer  bb = new GXByteBuffer();
            //TODO: This can remove later.
            byte s = translator.Security;

            try
            {
                translator.Clear();
                UpdateSecurity();
                translator.Security = (byte)Security.Authentication;

                translator.PduOnly = PduOnlyCB.Checked;
                GXByteBuffer pdu = new GXByteBuffer();
                bb.Set(GXDLMSTranslator.HexToBytes(RemoveComments(MessagePduTB.Text)));
                InterfaceType type = GXDLMSTranslator.GetDlmsFraming(bb);
                int           cnt  = 1;
                string        last = "";
                while (translator.FindNextFrame(bb, pdu, type))
                {
                    int start = bb.Position;
                    GXDLMSTranslatorMessage msg = new GXDLMSTranslatorMessage();
                    msg.Message = bb;
                    translator.MessageToXml(msg);
                    //Remove duplicate messages.
                    if (RemoveDuplicatesCb.Checked)
                    {
                        if (last == msg.Xml)
                        {
                            continue;
                        }
                    }
                    last = msg.Xml;
                    if (msg.Command == Command.Aarq)
                    {
                        if (msg.SystemTitle != null)
                        {
                            string st = UpdateSystemTitle(this, "Current System title \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                          msg.SystemTitle, SystemTitleTB.Text, SystemTitleAsciiCb.Checked);
                            if (st != null)
                            {
                                SystemTitleTB.Text         = "";
                                SystemTitleAsciiCb.Checked = false;
                                SystemTitleTB.Text         = st;
                            }
                        }
                        if (msg.DedicatedKey != null)
                        {
                            string key = UpdateSystemTitle(this, "Current dedicated key \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                           msg.DedicatedKey, DedicatedKeyTb.Text, DedicatedKeyAsciiCb.Checked);
                            if (key != null)
                            {
                                DedicatedKeyTb.Text         = "";
                                DedicatedKeyAsciiCb.Checked = false;
                                DedicatedKeyTb.Text         = key;
                            }
                        }
                    }
                    if (msg.Command == Command.Aare && msg.SystemTitle != null)
                    {
                        string st = UpdateSystemTitle(this, "Current Server System title \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                      msg.SystemTitle, ServerSystemTitleTB.Text, ServerSystemTitleAsciiCb.Checked);
                        if (st != null)
                        {
                            ServerSystemTitleTB.Text   = "";
                            SystemTitleAsciiCb.Checked = false;
                            ServerSystemTitleTB.Text   = st;
                        }
                    }
                    if (!AllRb.Checked)
                    {
                        switch (msg.Command)
                        {
                        case Command.None:
                            break;

                        case Command.InitiateRequest:
                        case Command.ReadRequest:
                        case Command.WriteRequest:
                        case Command.GetRequest:
                        case Command.SetRequest:
                        case Command.MethodRequest:
                        case Command.Snrm:
                        case Command.Aarq:
                        case Command.ReleaseRequest:
                        case Command.DisconnectRequest:
                        case Command.AccessRequest:
                        case Command.GloGetRequest:
                        case Command.GloSetRequest:
                        case Command.GloMethodRequest:
                        case Command.GloInitiateRequest:
                        case Command.GloReadRequest:
                        case Command.GloWriteRequest:
                        case Command.DedInitiateRequest:
                        case Command.DedReadRequest:
                        case Command.DedWriteRequest:
                        case Command.DedGetRequest:
                        case Command.DedSetRequest:
                        case Command.DedMethodRequest:
                        case Command.GatewayRequest:
                            if (ReceivedRb.Checked)
                            {
                                continue;
                            }
                            break;

                        case Command.InitiateResponse:
                        case Command.ReadResponse:
                        case Command.WriteResponse:
                        case Command.GetResponse:
                        case Command.SetResponse:
                        case Command.MethodResponse:
                        case Command.Ua:
                        case Command.Aare:
                        case Command.ReleaseResponse:
                        case Command.AccessResponse:
                        case Command.GloGetResponse:
                        case Command.GloSetResponse:
                        case Command.GloMethodResponse:
                        case Command.GloInitiateResponse:
                        case Command.GloReadResponse:
                        case Command.GloWriteResponse:
                        case Command.DedInitiateResponse:
                        case Command.DedReadResponse:
                        case Command.DedWriteResponse:
                        case Command.DedGetResponse:
                        case Command.DedSetResponse:
                        case Command.DedMethodResponse:
                        case Command.GatewayResponse:
                            if (SentRb.Checked)
                            {
                                continue;
                            }
                            break;

                        case Command.DisconnectMode:
                        case Command.UnacceptableFrame:
                        case Command.ConfirmedServiceError:
                        case Command.ExceptionResponse:
                        case Command.GeneralBlockTransfer:
                        case Command.DataNotification:
                        case Command.GloEventNotification:
                        case Command.GloConfirmedServiceError:
                        case Command.GeneralGloCiphering:
                        case Command.GeneralDedCiphering:
                        case Command.GeneralCiphering:
                        case Command.InformationReport:
                        case Command.EventNotification:
                        case Command.DedConfirmedServiceError:
                        case Command.DedUnconfirmedWriteRequest:
                        case Command.DedInformationReport:
                        case Command.DedEventNotification:
                            break;
                        }
                    }
                    sb.AppendLine(cnt + ": " + bb.ToHex(true, start, bb.Position - start));
                    ++cnt;
                    sb.Append(msg.Xml);
                    pdu.Clear();
                }
                MessageXmlTB.Text   = sb.ToString();
                translator.Security = s;
            }
            catch (Exception ex)
            {
                translator.Security = s;
                MessageXmlTB.AppendText(sb.ToString());
                MessageXmlTB.AppendText(Environment.NewLine);
                MessageXmlTB.AppendText(bb.RemainingHexString(true));

                MessageBox.Show(this, ex.Message);
            }
        }
 public DLMSTranslatorForm()
 {
     InitializeComponent();
     translator.Comments = true;
     DataPdu.Text        = Properties.Settings.Default.Data;
     tabControl1_SelectedIndexChanged(null, null);
     if (!string.IsNullOrEmpty(Properties.Settings.Default.Pdu))
     {
         PduTB.Text = Properties.Settings.Default.Pdu;
     }
     if (!string.IsNullOrEmpty(Properties.Settings.Default.Message))
     {
         MessagePduTB.Text = Properties.Settings.Default.Message;
     }
     try
     {
         string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "GXDLMSDirector");
         if (!Directory.Exists(path))
         {
             Directory.CreateDirectory(path);
         }
         string certificates = Path.Combine(path, "Certificates");
         if (!Directory.Exists(certificates))
         {
             Directory.CreateDirectory(certificates);
         }
         string keys = Path.Combine(path, "Keys");
         if (!Directory.Exists(keys))
         {
             Directory.CreateDirectory(keys);
         }
         try
         {
             translator.SecuritySuite     = (SecuritySuite)Properties.Settings.Default.SecuritySuite;
             translator.Security          = (Security)Enum.Parse(typeof(Security), Properties.Settings.Default.Security);
             translator.SystemTitle       = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.NotifySystemTitle);
             translator.ServerSystemTitle = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.ServerSystemTitle);
             translator.BlockCipherKey    = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.NotifyBlockCipherKey);
             translator.AuthenticationKey = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.AuthenticationKey);
             translator.InvocationCounter = (UInt32)Properties.Settings.Default.InvocationCounter;
             translator.DedicatedKey      = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.DedicatedKey);
         }
         catch (Exception)
         {
             //Set default settings if settings are corrupted.
             translator.Security          = Security.None;
             translator.SystemTitle       = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.NotifySystemTitle);
             translator.ServerSystemTitle = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.ServerSystemTitle);
             translator.BlockCipherKey    = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.NotifyBlockCipherKey);
             translator.AuthenticationKey = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.AuthenticationKey);
             translator.InvocationCounter = 0;
             translator.DedicatedKey      = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.DedicatedKey);
         }
         Ciphering = new GXCipheringSettings(translator, keys, certificates,
                                             Properties.Settings.Default.ClientAgreementKey,
                                             Properties.Settings.Default.ClientSigningKey,
                                             Properties.Settings.Default.ServerAgreementKey,
                                             Properties.Settings.Default.ServerSigningKey);
         Ciphering.Challenge = GXDLMSTranslator.HexToBytes(Properties.Settings.Default.Challenge);
         tabControl1.TabPages.Add(Ciphering.GetCiphetingTab());
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Exemplo n.º 30
0
        public static int GetParameters(string[] args, Settings settings)
        {
            string[] tmp;
            List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:i:It:a:P:g:S:C:n:v:o:T:A:B:D:d:l:F:K:k:m:");
            GXNet net = null;

            foreach (GXCmdParameter it in parameters)
            {
                switch (it.Tag)
                {
                case 'r':
                    if (string.Compare(it.Value, "sn", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = false;
                    }
                    else if (string.Compare(it.Value, "ln", true) == 0)
                    {
                        settings.client.UseLogicalNameReferencing = true;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid reference option.");
                    }
                    break;

                case 'h':
                    //Host address.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net          = settings.media as GXNet;
                    net.HostName = it.Value;
                    break;

                case 't':
                    //Trace.
                    try
                    {
                        settings.trace = (TraceLevel)Enum.Parse(typeof(TraceLevel), it.Value);
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid trace level option. (Error, Warning, Info, Verbose, Off)");
                    }
                    break;

                case 'p':
                    //Port.
                    if (settings.media == null)
                    {
                        settings.media = new GXNet();
                    }
                    net      = settings.media as GXNet;
                    net.Port = int.Parse(it.Value);
                    break;

                case 'P':    //Password
                    settings.client.Password = ASCIIEncoding.ASCII.GetBytes(it.Value);
                    break;

                case 'i':
                    try
                    {
                        settings.client.InterfaceType = (InterfaceType)Enum.Parse(typeof(InterfaceType), it.Value);
                        settings.client.Plc.Reset();
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid interface type option. (HDLC, WRAPPER, HdlcWithModeE, Plc, PlcHdlc)");
                    }
                    break;

                case 'I':
                    //AutoIncreaseInvokeID.
                    settings.client.AutoIncreaseInvokeID = true;
                    break;

                case 'v':
                    settings.invocationCounter = it.Value.Trim();
                    Objects.GXDLMSObject.ValidateLogicalName(settings.invocationCounter);
                    break;

                case 'g':
                    //Get (read) selected objects.
                    foreach (string o in it.Value.Split(new char[] { ';', ',' }))
                    {
                        tmp = o.Split(new char[] { ':' });
                        if (tmp.Length != 2)
                        {
                            throw new ArgumentOutOfRangeException("Invalid Logical name or attribute index.");
                        }
                        settings.readObjects.Add(new KeyValuePair <string, int>(tmp[0].Trim(), int.Parse(tmp[1].Trim())));
                    }
                    break;

                case 'S':    //Serial Port
                    settings.media = new GXSerial();
                    GXSerial serial = settings.media as GXSerial;
                    tmp             = it.Value.Split(':');
                    serial.PortName = tmp[0];
                    if (tmp.Length > 1)
                    {
                        serial.BaudRate = int.Parse(tmp[1]);
                        serial.DataBits = int.Parse(tmp[2].Substring(0, 1));
                        serial.Parity   = (Parity)Enum.Parse(typeof(Parity), tmp[2].Substring(1, tmp[2].Length - 2));
                        serial.StopBits = (StopBits)int.Parse(tmp[2].Substring(tmp[2].Length - 1, 1));
                    }
                    else
                    {
                        if (settings.client.InterfaceType == InterfaceType.HdlcWithModeE)
                        {
                            serial.BaudRate = 300;
                            serial.DataBits = 7;
                            serial.Parity   = Parity.Even;
                            serial.StopBits = StopBits.One;
                        }
                        else
                        {
                            serial.BaudRate = 9600;
                            serial.DataBits = 8;
                            serial.Parity   = Parity.None;
                            serial.StopBits = StopBits.One;
                        }
                    }
                    break;

                case 'a':
                    try
                    {
                        if (string.Compare("None", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.None;
                        }
                        else if (string.Compare("Low", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.Low;
                        }
                        else if (string.Compare("High", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.High;
                        }
                        else if (string.Compare("HighMd5", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighMD5;
                        }
                        else if (string.Compare("HighSha1", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA1;
                        }
                        else if (string.Compare("HighSha256", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighSHA256;
                        }
                        else if (string.Compare("HighGMac", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighGMAC;
                        }
                        else if (string.Compare("HighECDSA", it.Value, true) == 0)
                        {
                            settings.client.Authentication = Authentication.HighECDSA;
                        }
                        else
                        {
                            throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Authentication option: '" + it.Value + "'. (None, Low, High, HighMd5, HighSha1, HighGMac, HighSha256)");
                    }
                    break;

                case 'C':
                    try
                    {
                        settings.client.Ciphering.Security = Convert.ToByte(Enum.Parse(typeof(Security), it.Value));
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid Ciphering option '" + it.Value + "'. (None, Authentication, Encryption, AuthenticationEncryption)");
                    }
                    break;

                case 'T':
                    settings.client.Ciphering.SystemTitle = GXCommon.HexToBytes(it.Value);
                    break;

                case 'A':
                    settings.client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'B':
                    settings.client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'D':
                    settings.client.Ciphering.DedicatedKey = GXCommon.HexToBytes(it.Value);
                    break;

                case 'F':
                    settings.client.Ciphering.InvocationCounter = UInt32.Parse(it.Value.Trim());
                    break;

                case 'K':
                    GXPkcs8 cert1 = GXPkcs8.Load(it.Value);
                    settings.client.Ciphering.SigningKeyPair = new KeyValuePair <GXPrivateKey, GXPublicKey>(cert1.PrivateKey, cert1.PublicKey);
                    Console.WriteLine("Client Private key: " + GXDLMSTranslator.ToHex(cert1.PrivateKey.RawValue));
                    Console.WriteLine("Client Public key: " + GXDLMSTranslator.ToHex(cert1.PublicKey.RawValue));
                    break;

                case 'k':
                    GXx509Certificate cert = GXx509Certificate.Load(it.Value);
                    if ((cert.KeyUsage & ASN.Enums.KeyUsage.DigitalSignature) == 0)
                    {
                        throw new Exception("This certificate is not used for digital signature.");
                    }
                    settings.client.Ciphering.PublicKeys.Add(new KeyValuePair <CertificateType, GXx509Certificate>(CertificateType.DigitalSignature, cert));
                    string[] sn = cert.Subject.Split('=');
                    if (sn.Length != 2)
                    {
                        throw new ArgumentOutOfRangeException("Invalid public key subject.");
                    }
                    settings.client.Ciphering.SystemTitle = GXDLMSTranslator.HexToBytes(sn[1]);
                    Console.WriteLine("Server Public key: " + GXDLMSTranslator.ToHex(cert.PublicKey.RawValue));
                    break;

                case 'o':
                    settings.outputFile = it.Value;
                    break;

                case 'd':
                    try
                    {
                        settings.client.Standard = (Standard)Enum.Parse(typeof(Standard), it.Value);
                        if (settings.client.Standard == Standard.Italy || settings.client.Standard == Standard.India || settings.client.Standard == Standard.SaudiArabia)
                        {
                            settings.client.UseUtc2NormalTime = true;
                        }
                    }
                    catch (Exception)
                    {
                        throw new ArgumentException("Invalid DLMS standard option '" + it.Value + "'. (DLMS, India, Italy, SaudiArabia, IDIS)");
                    }
                    break;

                case 'c':
                    settings.client.ClientAddress = int.Parse(it.Value);
                    break;

                case 's':
                    if (settings.client.ServerAddress != 1)
                    {
                        settings.client.ServerAddress = GXDLMSClient.GetServerAddress(settings.client.ServerAddress, int.Parse(it.Value));
                    }
                    else
                    {
                        settings.client.ServerAddress = int.Parse(it.Value);
                    }
                    break;

                case 'l':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value), settings.client.ServerAddress);
                    break;

                case 'n':
                    settings.client.ServerAddress = GXDLMSClient.GetServerAddress(int.Parse(it.Value));
                    break;

                case 'm':
                    settings.client.Plc.MacDestinationAddress = UInt16.Parse(it.Value);
                    break;

                case '?':
                    switch (it.Tag)
                    {
                    case 'c':
                        throw new ArgumentException("Missing mandatory client option.");

                    case 's':
                        throw new ArgumentException("Missing mandatory server option.");

                    case 'h':
                        throw new ArgumentException("Missing mandatory host name option.");

                    case 'p':
                        throw new ArgumentException("Missing mandatory port option.");

                    case 'r':
                        throw new ArgumentException("Missing mandatory reference option.");

                    case 'a':
                        throw new ArgumentException("Missing mandatory authentication option.");

                    case 'S':
                        throw new ArgumentException("Missing mandatory Serial port option.");

                    case 't':
                        throw new ArgumentException("Missing mandatory trace option.");

                    case 'g':
                        throw new ArgumentException("Missing mandatory OBIS code option.");

                    case 'C':
                        throw new ArgumentException("Missing mandatory Ciphering option.");

                    case 'v':
                        throw new ArgumentException("Missing mandatory invocation counter logical name option.");

                    case 'T':
                        throw new ArgumentException("Missing mandatory system title option.");

                    case 'A':
                        throw new ArgumentException("Missing mandatory authentication key option.");

                    case 'B':
                        throw new ArgumentException("Missing mandatory block cipher key option.");

                    case 'D':
                        throw new ArgumentException("Missing mandatory dedicated key option.");

                    case 'F':
                        throw new ArgumentException("Missing mandatory frame counter option.");

                    case 'd':
                        throw new ArgumentException("Missing mandatory DLMS standard option.");

                    case 'K':
                        throw new ArgumentException("Missing mandatory private key file option.");

                    case 'k':
                        throw new ArgumentException("Missing mandatory public key file option.");

                    case 'l':
                        throw new ArgumentException("Missing mandatory logical server address option.");

                    case 'm':
                        throw new ArgumentException("Missing mandatory MAC destination address option.");

                    default:
                        ShowHelp();
                        return(1);
                    }

                default:
                    ShowHelp();
                    return(1);
                }
            }
            if (settings.media == null)
            {
                ShowHelp();
                return(1);
            }
            return(0);
        }