예제 #1
0
        public GXKeyForm(IGXUpdater updater, string address, string keyFolder, string certificateFolder, string title, SecuritySuite securitySuite, byte[] systemTitle)
        {
            InitializeComponent();
            _updater           = updater;
            _address           = address;
            _certificateFolder = certificateFolder;
            _systemTitle       = systemTitle;
            privateKeys        = new GXPkcs8Collection();
            KeyFolder          = keyFolder;
            Title = title;

            foreach (string p in Directory.GetFiles(keyFolder))
            {
                string ext = Path.GetExtension(p);
                if (string.Compare(ext, ".pem", true) == 0 || string.Compare(ext, ".cer", true) == 0)
                {
                    try
                    {
                        GXPkcs8 cert = GXPkcs8.Load(p);
                        AddKey(cert, p);
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("Failed to open " + p);
                    }
                }
            }
            if (_systemTitle != null)
            {
                string path = Path.Combine(KeyFolder, "D" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem";
                //Generate private key for digital signature.
                GXPkcs8 digitalSignature = new GXPkcs8(GXEcdsa.GenerateKeyPair(securitySuite == SecuritySuite.Suite1 ? Ecc.P256 : Ecc.P384));
                digitalSignature.Save(path);
                AddKey(digitalSignature, path);
                path = Path.Combine(KeyFolder, "A" + GXDLMSTranslator.ToHex(_systemTitle, false)) + ".pem";
                //Generate private key for Key agreement.
                GXPkcs8 keyAgreement = new GXPkcs8(GXEcdsa.GenerateKeyPair(Ecc.P256));
                keyAgreement.Save(path);
                AddKey(keyAgreement, path);

                //Get CRS.
                KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(digitalSignature.PublicKey, digitalSignature.PrivateKey);
                //Generate certificate request and ask new x509Certificate.
                //Note! There is a limit how many request you can do in a day.
                List <GXCertificateRequest> certifications = new List <GXCertificateRequest>();
                GXCertificateRequest        it             = new GXCertificateRequest();
                it.Certificate     = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle));
                it.CertificateType = CertificateType.DigitalSignature;
                certifications.Add(it);
                it                 = new GXCertificateRequest();
                it.Certificate     = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(_systemTitle));
                it.CertificateType = CertificateType.KeyAgreement;
                certifications.Add(it);
                GXx509Certificate[] certificates = GXPkcs10.GetCertificate(address, certifications);
                foreach (GXx509Certificate cert in certificates)
                {
                    if (cert.KeyUsage == KeyUsage.DigitalSignature)
                    {
                        path = "D" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                    {
                        path = "A" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                    {
                        path = "T" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    else
                    {
                        path = "O" + GXDLMSTranslator.ToHex(_systemTitle, false);
                    }
                    path = Path.Combine(_certificateFolder, path) + ".pem";
                    cert.Save(path);
                }
            }
        }
예제 #2
0
 public void OnValueChanged(GXDLMSViewArguments arg)
 {
     GXDLMSRegisterActivation target = (GXDLMSRegisterActivation)Target;
     if (arg.Index == 2)
     {
         // register_assignment
         Assigments.Items.Clear();
         if (target.RegisterAssignment != null)
         {
             foreach (GXDLMSObjectDefinition it in target.RegisterAssignment)
             {
                 ListViewItem li = new ListViewItem(it.ObjectType.ToString());
                 li.SubItems.Add(it.LogicalName);
                 Assigments.Items.Add(li);
             }
         }
     }
     else if (arg.Index == 3)
     {
         // mask_list
         Masks.Items.Clear();
         ActiveMasksCb.Items.Clear();
         StringBuilder sb = new StringBuilder();
         string str;
         foreach (KeyValuePair<byte[], byte[]> it in target.MaskList)
         {
             if (IsAscii(it.Key))
             {
                 str = ASCIIEncoding.ASCII.GetString(it.Key);
             }
             else
             {
                 str = GXDLMSTranslator.ToHex(it.Key);
             }
             ListViewItem li = new ListViewItem(str);
             sb.Length = 0;
             foreach (byte v in it.Value)
             {
                 sb.Append(v);
                 sb.Append(", ");
             }
             if (sb.Length != 0)
             {
                 sb.Length -= 2;
             }
             li.SubItems.Add(sb.ToString());
             li.Tag = it;
             Masks.Items.Add(li);
             ActiveMasksCb.Items.Add(str);
         }
     }
     else if (arg.Index == 4)
     {
         string str;
         if (target.ActiveMask != null && IsAscii(target.ActiveMask))
         {
             str = ASCIIEncoding.ASCII.GetString(target.ActiveMask);
         }
         else
         {
             str = GXDLMSTranslator.ToHex(target.ActiveMask);
         }
         this.ActiveMasksCb.SelectedIndexChanged -= new System.EventHandler(this.ActiveMasksCb_SelectedIndexChanged);
         ActiveMasksCb.SelectedIndex = ActiveMasksCb.FindString(str);
         this.ActiveMasksCb.SelectedIndexChanged += new System.EventHandler(this.ActiveMasksCb_SelectedIndexChanged);
     }
 }
예제 #3
0
        /// <summary>
        /// Get certificate for the private key.
        /// </summary>
        private void GetCertificateMnu_Click(object sender, EventArgs e)
        {
            try
            {
                ListViewItem it = KeyList.SelectedItems[0];
                GXCertificateSigningRequestDlg dlg = new GXCertificateSigningRequestDlg(SystemTitle);
                if (dlg.ShowDialog(Parent) == DialogResult.OK)
                {
                    SystemTitle = dlg.SystemTitle;
                    GXPkcs8 pk = GXPkcs8.Load((string)it.Tag);
                    KeyValuePair <GXPublicKey, GXPrivateKey> kp = new KeyValuePair <GXPublicKey, GXPrivateKey>(pk.PublicKey, pk.PrivateKey);
                    List <GXCertificateRequest> certifications  = new List <GXCertificateRequest>();
                    GXCertificateRequest        it2             = new GXCertificateRequest();
                    it2.CertificateType  = dlg.CertificateType;
                    it2.ExtendedKeyUsage = dlg.ExtendedKeyUsage;
                    //Generate certificate request and ask new x509Certificate.
                    it2.Certificate = GXPkcs10.CreateCertificateSigningRequest(kp, GXAsn1Converter.SystemTitleToSubject(SystemTitle));
                    certifications.Add(it2);
                    //Note! There is a limit how many request you can do in a day.
                    GXx509Certificate[] certificates = GXPkcs10.GetCertificate(_address, certifications);
                    foreach (GXx509Certificate cert in certificates)
                    {
                        if (cert.KeyUsage == KeyUsage.DigitalSignature)
                        {
                            _path = "D" + Path.GetFileName((string)it.Tag);
                        }
                        else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                        {
                            _path = "A" + Path.GetFileName((string)it.Tag);
                        }
                        else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                        {
                            //TLS.
                            _path = "T" + Path.GetFileName((string)it.Tag);
                        }
                        else
                        {
                            //Other.
                            _path = "O" + Path.GetFileName((string)it.Tag);
                        }

                        if (File.Exists(_path))
                        {
                            if (cert.KeyUsage == KeyUsage.DigitalSignature)
                            {
                                _path = "D" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else if (cert.KeyUsage == KeyUsage.KeyAgreement)
                            {
                                _path = "A" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else if (cert.KeyUsage == (KeyUsage.KeyAgreement | KeyUsage.DigitalSignature))
                            {
                                //TLS.
                                _path = "T" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            else
                            {
                                //Other.
                                _path = "O" + GXDLMSTranslator.ToHex(SystemTitle, false);
                            }
                            _path += ".pem";
                        }
                        _path = Path.Combine(_certificateFolder, _path);
                        cert.Save(_path);
                    }
                    _updater.UpdateUI();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Parent, ex.Message);
            }
        }
예제 #4
0
        /// <summary>
        /// Update private and public keys to the translator.
        /// </summary>
        private void GetKeys()
        {
            if (updateUI)
            {
                if (ClientSigningKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> cs)
                {
                    ClientSigningKey = cs.Key.ToDer();
                }
                else
                {
                    ClientSigningKey = null;
                }
                if (ClientAgreementKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> ca)
                {
                    ClientAgreementKey = ca.Key.ToDer();
                }
                else
                {
                    ClientAgreementKey = null;
                }
                if (ServerSigningKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> ss)
                {
                    ServerSigningKey = ss.Value.ToDer();
                }
                else
                {
                    ServerSigningKey = null;
                }
                if (ServerAgreementKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> sa)
                {
                    ServerAgreementKey = sa.Value.ToDer();
                }
                else
                {
                    ServerAgreementKey = null;
                }
                bool check = _checkSystemTitle;
                if (check)
                {
                    string st;
                    if (SystemTitleAsciiCb.Checked)
                    {
                        st = GXDLMSTranslator.ToHex(ASCIIEncoding.ASCII.GetBytes(SystemTitleTb.Text), false);
                    }
                    else
                    {
                        st = SystemTitleTb.Text.Replace(" ", "");
                    }
                    if (check && (ClientSigningKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> cv) && cv.Value != null)
                    {
                        string certificateSt = GXDLMSTranslator.ToHex(GXAsn1Converter.SystemTitleFromSubject(cv.Value.Subject), false);
                        if (st != certificateSt)
                        {
                            if (MessageBox.Show(Parent, string.Format("System title '{0}' of the client is different than in the certificate '{1}'. Do you want to update the system title from the certificate?", SystemTitleTb.Text, certificateSt), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                SystemTitleAsciiCb.Checked = false;
                                SystemTitleTb.Text         = certificateSt;
                                check = false;
                            }
                        }
                    }
                    if (check && (ClientAgreementKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> ck) && ck.Value != null)
                    {
                        string certificateSt = GXDLMSTranslator.ToHex(GXAsn1Converter.SystemTitleFromSubject(ck.Value.Subject), false);
                        if (st != certificateSt)
                        {
                            if (MessageBox.Show(Parent, string.Format("System title '{0}' of the client is different than in the certificate '{1}'. Do you want to update the system title from the certificate?", SystemTitleTb.Text, certificateSt), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                SystemTitleAsciiCb.Checked = false;
                                SystemTitleTb.Text         = certificateSt;
                                check = false;
                            }
                        }
                    }

                    if (check && ServerSigningKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> sv)
                    {
                        string certificateSt = GXDLMSTranslator.ToHex(GXAsn1Converter.SystemTitleFromSubject(sv.Value.Subject), false);
                        if (ServerSystemTitleTb.Text.Replace(" ", "") != certificateSt)
                        {
                            if (MessageBox.Show(Parent, string.Format("System title '{0}' of the server is different than in the certificate '{1}'. Do you want to update the system title from the certificate?", ServerSystemTitleTb.Text, certificateSt), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                ServerSystemTitleTb.Text = certificateSt;
                                check = false;
                            }
                        }
                    }
                    if (check && ServerAgreementKeysCb.SelectedItem is KeyValuePair <GXPkcs8, GXx509Certificate> sk)
                    {
                        string certificateSt = GXDLMSTranslator.ToHex(GXAsn1Converter.SystemTitleFromSubject(sk.Value.Subject), false);
                        if (ServerSystemTitleTb.Text.Replace(" ", "") != certificateSt)
                        {
                            if (MessageBox.Show(Parent, string.Format("System title '{0}' of the server is different than in the certificate '{1}'. Do you want to update the system title from the certificate?", ServerSystemTitleTb.Text, certificateSt), "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                ServerSystemTitleTb.Text = certificateSt;
                                check = false;
                            }
                        }
                    }
                }
            }
        }
예제 #5
0
 private void TemplatesAdd_Click(object sender, EventArgs e)
 {
     try
     {
         OpenFileDialog dlg = new OpenFileDialog();
         dlg.Multiselect      = false;
         dlg.InitialDirectory = Directory.GetCurrentDirectory();
         dlg.Filter           = Properties.Resources.FilterTxt;
         dlg.DefaultExt       = ".gdr";
         dlg.ValidateNames    = true;
         if (dlg.ShowDialog(panel1.Parent) == DialogResult.OK)
         {
             if (File.Exists(dlg.FileName))
             {
                 List <GXDLMSDevice> devices;
                 using (XmlReader reader = XmlReader.Create(dlg.FileName))
                 {
                     List <Type> types = new List <Type>(Gurux.DLMS.GXDLMSClient.GetObjectTypes());
                     types.Add(typeof(GXDLMSAttributeSettings));
                     types.Add(typeof(GXDLMSAttribute));
                     //Version is added to namespace.
                     XmlSerializer x = new XmlSerializer(typeof(List <GXDLMSDevice>), null, types.ToArray(), null, "Gurux1");
                     if (!x.CanDeserialize(reader))
                     {
                         x = new XmlSerializer(typeof(List <GXDLMSDevice>), types.ToArray());
                     }
                     devices = (List <GXDLMSDevice>)x.Deserialize(reader);
                     reader.Close();
                 }
                 GXDeviceTemplate        m         = new GXDeviceTemplate();
                 List <GXDeviceTemplate> templates = new List <GXDeviceTemplate>();
                 foreach (GXDLMSDevice it in devices)
                 {
                     GXDeviceTemplate t = new GXDeviceTemplate();
                     GXDevice.Copy(t, it);
                     if (!string.IsNullOrEmpty(it.Password))
                     {
                         t.Password = ASCIIEncoding.ASCII.GetString(CryptHelper.Decrypt(it.Password, Password.Key));
                     }
                     else if (it.HexPassword != null)
                     {
                         t.Password = GXDLMSTranslator.ToHex(CryptHelper.Decrypt(it.HexPassword, Password.Key));
                     }
                     List <GXObjectTemplate> list = new List <GXObjectTemplate>();
                     if (it.Objects.Count == 0)
                     {
                         throw new Exception("There are no objects. Read the association view first.");
                     }
                     foreach (GXDLMSObject value in it.Objects)
                     {
                         string[]         names = ((IGXDLMSBase)value).GetNames();
                         GXObjectTemplate obj   = new GXObjectTemplate();
                         obj.LogicalName = value.LogicalName;
                         obj.ObjectType  = (int)value.ObjectType;
                         obj.Name        = value.Description;
                         obj.Version     = value.Version;
                         obj.ShortName   = value.ShortName;
                         list.Add(obj);
                         for (int pos = 2; pos <= ((IGXDLMSBase)value).GetAttributeCount(); ++pos)
                         {
                             GXAttributeTemplate a = new GXAttributeTemplate();
                             a.Name        = names[pos - 1];
                             a.Index       = pos;
                             a.AccessLevel = (int)value.GetAccess(pos);
                             a.DataType    = (int)((IGXDLMSBase)value).GetDataType(pos);
                             a.UIDataType  = (int)((GXDLMSObject)value).GetUIDataType(pos);
                             if (value.GetStatic(pos))
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             //Profile generic capture object read is not allowed.
                             if (value is GXDLMSProfileGeneric && pos == 3)
                             {
                                 a.ExpirationTime = 0xFFFFFFFF;
                             }
                             obj.Attributes.Add(a);
                         }
                         t.Objects = list;
                     }
                     templates.Add(t);
                 }
                 DBDevicePropertiesForm dlg2 = new DBDevicePropertiesForm(templates.ToArray(), m);
                 if (dlg2.ShowDialog(panel1.Parent) == DialogResult.OK)
                 {
                     {
                         ami.AddDeviceTemplates(new GXDLMSMeterBase[] { m });
                         ListViewItem li = TemplatesView.Items.Add(m.Name);
                         li.Tag      = m;
                         li.Selected = true;
                     }
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         MessageBox.Show(panel1.Parent, Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
 public override string ToString()
 {
     return(GXDLMSTranslator.ToHex(Name));
 }
예제 #7
0
 /// <summary>
 /// Returns the private key as a hex string.
 /// </summary>
 /// <param name="addSpace">Is space added between the bytes.</param>
 /// <returns>Private key as hex string.</returns>
 public string ToHex(bool addSpace)
 {
     return(GXDLMSTranslator.ToHex(RawValue, addSpace));
 }
 /// <summary>
 /// Returns the private key as a hex string.
 /// </summary>
 /// <returns></returns>
 public string ToHex()
 {
     return(GXDLMSTranslator.ToHex(RawValue));
 }
예제 #9
0
        public void OnValueChanged(GXDLMSViewArguments arg)
        {
            GXDLMSPrimeNbOfdmPlcMacNetworkAdministrationData target = Target as GXDLMSPrimeNbOfdmPlcMacNetworkAdministrationData;

            if (arg.Index == 2)
            {
                MulticastView.Items.Clear();
                if (target.MulticastEntries != null)
                {
                    foreach (GXMacMulticastEntry it in target.MulticastEntries)
                    {
                        ListViewItem li = MulticastView.Items.Add(it.Id.ToString());
                        li.SubItems.Add(it.Members.ToString());
                    }
                }
            }
            else if (arg.Index == 3)
            {
                SwitchTableView.Items.Clear();
                if (target.SwitchTable != null)
                {
                    foreach (Int16 it in target.SwitchTable)
                    {
                        SwitchTableView.Items.Add(it.ToString());
                    }
                }
            }
            else if (arg.Index == 4)
            {
                DirectTableView.Items.Clear();
                if (target.DirectTable != null)
                {
                    foreach (GXMacDirectTable it in target.DirectTable)
                    {
                        ListViewItem li = DirectTableView.Items.Add(it.SourceSId.ToString());
                        li.SubItems.Add(it.SourceLnId.ToString());
                        li.SubItems.Add(it.SourceLcId.ToString());
                        li.SubItems.Add(it.DestinationSId.ToString());
                        li.SubItems.Add(it.DestinationLnId.ToString());
                        li.SubItems.Add(it.DestinationLcId.ToString());
                        li.SubItems.Add(GXDLMSTranslator.ToHex(it.Did));
                        li.Tag = it;
                    }
                }
            }
            else if (arg.Index == 5)
            {
                AvailableSwitchesView.Items.Clear();
                if (target.AvailableSwitches != null)
                {
                    foreach (GXMacAvailableSwitch it in target.AvailableSwitches)
                    {
                        ListViewItem li = AvailableSwitchesView.Items.Add(GXDLMSTranslator.ToHex(it.Sna));
                        li.SubItems.Add(it.LsId.ToString());
                        li.SubItems.Add(it.Level.ToString());
                        li.SubItems.Add(it.RxLevel.ToString());
                        li.SubItems.Add(it.RxSnr.ToString());
                        li.Tag = it;
                    }
                }
            }
            else if (arg.Index == 6)
            {
                PhyCommmunicationView.Items.Clear();
                if (target.Communications != null)
                {
                    foreach (GXMacPhyCommunication it in target.Communications)
                    {
                        ListViewItem li = PhyCommmunicationView.Items.Add(GXDLMSTranslator.ToHex(it.Eui));
                        li.SubItems.Add(it.TxPower.ToString());
                        li.SubItems.Add(it.TxCoding.ToString());
                        li.SubItems.Add(it.RxCoding.ToString());
                        li.SubItems.Add(it.RxLvl.ToString());
                        li.SubItems.Add(it.Snr.ToString());
                        li.SubItems.Add(it.TxPowerModified.ToString());
                        li.SubItems.Add(it.TxCodingModified.ToString());
                        li.SubItems.Add(it.RxCodingModified.ToString());
                        li.Tag = it;
                    }
                }
            }
            else
            {
                throw new IndexOutOfRangeException("index");
            }
        }
예제 #10
0
        public void OnValueChanged(GXDLMSViewArguments arg)
        {
            GXDLMSNtpSetup target = (GXDLMSNtpSetup)Target;

            if (arg.Index == 2)
            {
                ActivatedCb.Checked = target.Activated;
            }
            else if (arg.Index == 6)
            {
                KeysView.Items.Clear();
                foreach (KeyValuePair <UInt32, byte[]> it in target.Keys)
                {
                    ListViewItem li = new ListViewItem(new string[] { it.Key.ToString(), GXDLMSTranslator.ToHex(it.Value) });
                    KeysView.Items.Add(li).Tag = it;
                }
                ActivatedCb.Checked = target.Activated;
            }
            else
            {
                throw new IndexOutOfRangeException("index");
            }
        }
예제 #11
0
        /// <summary>
        /// Write object value to file.
        /// </summary>
        /// <param name="name">Object name.</param>
        /// <param name="value">Object value.</param>
        /// <param name="skipDefaultValue">Is default value serialized.</param>
        public void WriteElementObject(string name, object value, DataType dt, DataType uiType, int index)
        {
            if (value != null)
            {
                if (IgnoreDefaultValues && value is DateTime && ((DateTime)value == DateTime.MinValue || (DateTime)value == DateTime.MaxValue))
                {
                    return;
                }

                writer.WriteStartElement(name);
                writer.WriteAttributeString("Type", ((int)dt).ToString());
                if (uiType != DataType.None && dt != uiType && (uiType != DataType.String || dt == DataType.OctetString))
                {
                    writer.WriteAttributeString("UIType", ((int)uiType).ToString());
                }
                else if (value is float || value is double)
                {
                    if (value is double)
                    {
                        writer.WriteAttributeString("UIType", ((int)DataType.Float64).ToString());
                    }
                    else
                    {
                        writer.WriteAttributeString("UIType", ((int)DataType.Float32).ToString());
                    }
                }
                if (dt == DataType.Array || dt == DataType.Structure)
                {
                    WriteArray(value);
                }
                else
                {
                    if (value is GXDateTime)
                    {
                        if (UseMeterTime)
                        {
                            writer.WriteString(((GXDateTime)value).ToFormatMeterString(CultureInfo.InvariantCulture));
                        }
                        else
                        {
                            writer.WriteString(((GXDateTime)value).ToFormatString(CultureInfo.InvariantCulture));
                        }
                    }
                    else if (value is DateTime)
                    {
                        writer.WriteString(((DateTime)value).ToString(CultureInfo.InvariantCulture));
                    }
                    else if (value is byte[])
                    {
                        writer.WriteString(GXDLMSTranslator.ToHex((byte[])value));
                    }
                    else
                    {
                        writer.WriteString(Convert.ToString(value, CultureInfo.InvariantCulture));
                    }
                }
                writer.WriteEndElement();
            }
            else if (!IgnoreDefaultValues)
            {
                writer.WriteStartElement(name);
                writer.WriteAttributeString("Type", "0");
                writer.WriteEndElement();
            }
        }
예제 #12
0
        /// <summary>
        /// Convert message to XML.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TranslateBtn_Click(object sender, EventArgs e)
        {
            if (MessagePduTB.ReadOnly)
            {
                StatusLbl.Text = "Cancelling translate.";
                CancelTranslate.Set();
                return;
            }
            TranslateBtn.Checked  = true;
            MessagePduTB.ReadOnly = true;
            Follow       follow = (Follow)FollowmessagesCb.SelectedItem;
            ShowMessages show   = (ShowMessages)ShowCb.SelectedItem;

            MessageXmlTB.Text   = null;
            ProgressBar.Visible = true;
            object selectedInterface = InterfaceCb.SelectedItem;

            UpdateSecuritySettings();
            StatusLbl.Text = "Finding frames";
            GXByteBuffer bb = new GXByteBuffer();

            bb.Set(GXDLMSTranslator.HexToBytes(RemoveComments(string.Join(Environment.NewLine, MessagePduTB.Lines))));
            System.Threading.Tasks.Task.Run(async() =>
            {
                if (translator.BlockCipherKey != null)
                {
                    OnAppendMessage("BlockCipher key: " +
                                    GXDLMSTranslator.ToHex(translator.BlockCipherKey) + Environment.NewLine, Color.Green);
                }
                if (translator.AuthenticationKey != null)
                {
                    OnAppendMessage("Authentication Key:" +
                                    GXDLMSTranslator.ToHex(translator.AuthenticationKey) + Environment.NewLine, Color.Green);
                }
                StringBuilder sb = new StringBuilder();
                Security s       = translator.Security;
                int count        = 1;
                try
                {
                    translator.Clear();
                    translator.PduOnly = PduOnlyMnu.Checked;
                    GXByteBuffer pdu   = new GXByteBuffer();
                    UpdateProgress(0, 0);
                    UpdateMaxProgress(bb.Size, 0);
                    GXDLMSTranslatorMessage frame = new GXDLMSTranslatorMessage();
                    frame.Message = bb;
                    if (selectedInterface is string)
                    {
                        frame.InterfaceType = GXDLMSTranslator.GetDlmsFraming(bb);
                        BeginInvoke((Action)(() =>
                        {
                            InterfaceCb.SelectedItem = frame.InterfaceType;
                        }));
                    }
                    else
                    {
                        frame.InterfaceType = (InterfaceType)selectedInterface;
                    }
                    string last       = "";
                    int clientAddress = 0, serverAddress = 0;
                    while (translator.FindNextFrame(frame, pdu, clientAddress, serverAddress))
                    {
                        //Translate is cancelled.
                        if (CancelTranslate.WaitOne(1))
                        {
                            UpdateMaxProgress(0, 0);
                            BeginInvoke((Action)(() =>
                            {
                                MessagePduTB.ReadOnly = false;
                                TranslateBtn.Checked = false;
                            }));
                            CancelTranslate.Reset();
                            return;
                        }
                        int start = bb.Position;
                        UpdateProgress(start, count);
                        GXDLMSTranslatorMessage msg = new GXDLMSTranslatorMessage();
                        msg.Message = bb;
                        translator.MessageToXml(msg);
                        if (follow != Follow.None)
                        {
                            if ((follow & Follow.Client) != 0 && clientAddress == 0)
                            {
                                clientAddress = msg.SourceAddress;
                            }
                            if ((follow & Follow.Meter) != 0 && serverAddress == 0)
                            {
                                serverAddress = msg.TargetAddress;
                            }
                        }
                        //Remove duplicate messages.
                        if (RemoveDuplicatesMnu.Checked)
                        {
                            if (last == msg.Xml)
                            {
                                continue;
                            }
                        }
                        last = msg.Xml;
                        if (msg.Command == Command.Aarq)
                        {
                            if (msg.SystemTitle != null && msg.SystemTitle.Length == 8)
                            {
                                if (UpdateSystemTitle(this, "Current System title \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                      msg.SystemTitle, translator.SystemTitle))
                                {
                                    translator.SystemTitle = msg.SystemTitle;
                                    BeginInvoke((Action)(() =>
                                    {
                                        Ciphering.SystemTitle = msg.SystemTitle;
                                    }));
                                }
                            }
                            if (msg.DedicatedKey != null && msg.DedicatedKey.Length == 16)
                            {
                                if (UpdateSystemTitle(this, "Current dedicated key \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                      msg.DedicatedKey, translator.DedicatedKey))
                                {
                                    translator.DedicatedKey = msg.DedicatedKey;
                                    BeginInvoke((Action)(() =>
                                    {
                                        Ciphering.DedicatedKey = msg.DedicatedKey;
                                    }));
                                }
                            }
                        }
                        if (msg.Command == Command.Aare && msg.SystemTitle != null && msg.SystemTitle.Length == 8)
                        {
                            if (UpdateSystemTitle(this, "Current Server System title \"{0}\" is different in the parsed \"{1}\". Do you want to start using parsed one?",
                                                  msg.SystemTitle, translator.ServerSystemTitle))
                            {
                                translator.ServerSystemTitle = msg.SystemTitle;
                                BeginInvoke((Action)(() =>
                                {
                                    Ciphering.ServerSystemTitle = msg.SystemTitle;
                                }));
                            }
                        }
                        if (show != ShowMessages.All)
                        {
                            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 (show == ShowMessages.Received)
                                {
                                    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 (show == ShowMessages.Sent)
                                {
                                    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.GeneralSigning:
                            case Command.InformationReport:
                            case Command.EventNotification:
                            case Command.DedConfirmedServiceError:
                            case Command.DedUnconfirmedWriteRequest:
                            case Command.DedInformationReport:
                            case Command.DedEventNotification:
                                break;
                            }
                        }
                        if (Properties.Settings.Default.TranslatorFrame)
                        {
                            if (Properties.Settings.Default.FrameNumber)
                            {
                                sb.Append(count + ": ");
                            }
                            sb.AppendLine(bb.ToHex(true, start, bb.Position - start));
                        }
                        if (Properties.Settings.Default.TranslatorXml)
                        {
                            sb.Append(msg.Xml);
                        }
                        if (msg.Exception != null)
                        {
                            ++count;
                            OnAppendMessage(sb.ToString(), Color.Red);
                        }
                        else if (show != ShowMessages.Failed)
                        {
                            ++count;
                            OnAppendMessage(sb.ToString());
                        }
                        sb.Clear();
                        pdu.Clear();
                    }
                    OnAppendMessage(sb.ToString());
                    translator.Security = s;
                    //Update UI.
                    await System.Threading.Tasks.Task.Delay(1);
                }
                catch (Exception ex)
                {
                    translator.Security = s;
                    OnAppendMessage(sb.ToString());
                    OnAppendMessage(Environment.NewLine);
                    OnAppendMessage(bb.RemainingHexString(true));
                    MessageBox.Show(ex.Message);
                }
                //Count starts from 1.
                UpdateMaxProgress(0, count - 1);
                BeginInvoke((Action)(() =>
                {
                    MessagePduTB.ReadOnly = false;
                    TranslateBtn.Checked = false;
                }));
            });
        }
 public GXDLMSKeyTableDlg(GXKeyValuePair <byte, byte[]> item)
 {
     InitializeComponent();
     IdTb.Text  = item.Key.ToString();
     KeyTb.Text = GXDLMSTranslator.ToHex(item.Value);
 }
예제 #14
0
 static public object ConvertFromDLMS(object data, DataType from, DataType type, bool arrayAsString, bool useUtc)
 {
     if (type == DataType.Array)
     {
         return(data);
     }
     if (type == DataType.None)
     {
         if (arrayAsString && data != null && (data is List <object> || data.GetType().IsArray))
         {
             data = GXDLMSTranslator.ValueToXml(data);
         }
         return(data);
     }
     //Show Octet string...
     if (from == DataType.OctetString && type == DataType.OctetString)
     {
         if (data is byte[])
         {
             string str = "";
             byte[] arr = (byte[])data;
             if (arr.Length == 0)
             {
                 data = string.Empty;
             }
             else
             {
                 foreach (byte it in arr)
                 {
                     str += it.ToString() + ".";
                 }
                 data = str.Substring(0, str.Length - 1);
             }
         }
     }
     //Convert DLMS octect string to Windows string.
     else if (from == DataType.OctetString && type == DataType.String)
     {
         if (data is string)
         {
             return(data);
         }
         else if (data is byte[])
         {
             byte[] arr = (byte[])data;
             data = System.Text.Encoding.ASCII.GetString(arr);
         }
     }
     //Convert DLMS date time to Windows Time.
     else if (type == DataType.DateTime)
     {
         if (data is byte[])
         {
             if (((byte[])data).Length == 5)
             {
                 return(GXDLMSClient.ChangeType((byte[])data, DataType.Date, useUtc));
             }
             return(GXDLMSClient.ChangeType((byte[])data, DataType.DateTime, useUtc));
         }
         return(data);
     }
     //Convert DLMS date time to Windows Date.
     else if (type == DataType.Date)
     {
         if (data is DateTime)
         {
             return(data);
         }
         if (data is string)
         {
             return(data);
         }
         if (!data.GetType().IsArray || ((Array)data).Length < 5)
         {
             throw new Exception("DateTime conversion failed. Invalid DLMS format.");
         }
         return(GXDLMSClient.ChangeType((byte[])data, DataType.Date, useUtc));
     }
     //Convert DLMS date time to Windows Time.
     else if (type == DataType.Time)
     {
         if (data is byte[])
         {
             return(GXDLMSClient.ChangeType((byte[])data, type, useUtc));
         }
         return(data);
     }
     else if (data is byte[])
     {
         if (type == DataType.String)
         {
             data = System.Text.Encoding.ASCII.GetString((byte[])data);
         }
         else
         {
             data = GXDLMSTranslator.ToHex((byte[])data);
         }
     }
     else if (data is Array)
     {
         data = ArrayToString(data);
     }
     return(data);
 }
예제 #15
0
 void IGXDLMSBase.Save(GXXmlWriter writer)
 {
     writer.WriteElementString("SystemTitle", GXDLMSTranslator.ToHex(SystemTitle), 2);
     writer.WriteElementString("MacAddress", MacAddress, 3);
     writer.WriteElementString("LSapSelector", LSapSelector, 4);
 }
예제 #16
0
 public override string ToString()
 {
     return(GXDLMSTranslator.ToHex(Name) + " " + Start.ToFormatString() + " " + GXDLMSTranslator.ToHex(WeekName));
 }
예제 #17
0
 void UpdateData(DataTable dt)
 {
     if (target.CaptureObjects.Count == 0)
     {
         return;
     }
     if (structures)
     {
         List <object[]> data = new List <object[]>();
         foreach (object[] r in target.Buffer)
         {
             List <object> row   = new List <object>();
             int           index = 0;
             foreach (var it in target.CaptureObjects)
             {
                 //If COSEM object is selected.
                 //Only few meters are supporting this.
                 if (it.Value.AttributeIndex == 0 && r[index] is List <object> )
                 {
                     //Values must be update to the list because there might be Register Scaler
                     //and it expects that scaler is read before value is updated.
                     GXDLMSObject obj = GXDLMSClient.CreateObject(it.Key.ObjectType);
                     byte         i2  = 1;
                     Dictionary <byte, object> list = new Dictionary <byte, object>();
                     foreach (object v in (r[index] as List <object>))
                     {
                         list.Add(i2, v);
                         ++i2;
                     }
                     //Update values first.
                     foreach (byte i in (obj as IGXDLMSBase).GetAttributeIndexToRead(true))
                     {
                         ValueEventArgs ve = new ValueEventArgs(obj, i, 0, null);
                         ve.Value = list[i];
                         (obj as IGXDLMSBase).SetValue(null, ve);
                     }
                     //Show values.
                     for (byte i = 0; i != (obj as IGXDLMSBase).GetAttributeCount(); ++i)
                     {
                         row.Add(GetValue(obj.GetValues()[i]));
                     }
                 }
                 else
                 {
                     row.Add(GetValue(r[index]));
                 }
                 ++index;
             }
             data.Add(row.ToArray());
         }
         for (int pos = dt.Rows.Count; pos < data.Count; ++pos)
         {
             object[] row = data[pos];
             dt.LoadDataRow(row, true);
         }
     }
     else
     {
         for (int pos = dt.Rows.Count; pos < target.Buffer.Count; ++pos)
         {
             object[] row = target.Buffer[pos];
             if (row != null)
             {
                 for (int col = 0; col != row.Length; ++col)
                 {
                     if (row[col] is GXDateTime)
                     {
                         if (GXDlmsUi.UseMeterTimeZone)
                         {
                             row[col] = (row[col] as GXDateTime).ToFormatMeterString();
                         }
                         else
                         {
                             row[col] = (row[col] as GXDateTime).ToFormatString();
                         }
                     }
                     else if (row[col] is byte[])
                     {
                         row[col] = GXDLMSTranslator.ToHex((byte[])row[col], true);
                     }
                     else if (row[col] is Object[])
                     {
                         row[col] = GXDLMSTranslator.ValueToXml(row[col]);
                     }
                     else if (row[col] is GXStructure || row[col] is GXArray)
                     {
                         if (target.CaptureObjects[col].Key is GXDLMSRegister && target.CaptureObjects[col].Value.AttributeIndex == 2)
                         {
                             GXDLMSRegister obj = new GXDLMSRegister();
                             ValueEventArgs ve  = new ValueEventArgs(obj, target.CaptureObjects[col].Value.AttributeIndex, 0, null);
                             ve.Value = row[col];
                             (obj as IGXDLMSBase).SetValue(null, ve);
                             row[col] = "{" + obj.Scaler + ", " + obj.Unit + "}";
                         }
                         else
                         {
                             StringBuilder sb = new StringBuilder();
                             GetArrayAsString(sb, row[col]);
                             row[col] = sb.ToString();
                         }
                     }
                     else
                     {
                         GXDLMSAttributeSettings att = target.CaptureObjects[col].Key.Attributes.Find(target.CaptureObjects[col].Value.AttributeIndex);
                         if (att != null && att.Values != null)
                         {
                             if (att.Type == DataType.BitString && row[col] is string)
                             {
                                 string str = (string)row[col];
                                 if (str.Length != 0 && (str[0] == '0' || str[0] == '1'))
                                 {
                                     StringBuilder sb   = new StringBuilder();
                                     int           pos2 = 0;
                                     foreach (char it in str)
                                     {
                                         if (it == '1')
                                         {
                                             if (sb.Length != 0)
                                             {
                                                 sb.Append(',');
                                             }
                                             sb.Append(att.Values[pos2].UIValue);
                                         }
                                         ++pos2;
                                         if (pos2 == att.Values.Count)
                                         {
                                             break;
                                         }
                                     }
                                     row[col] = sb.ToString();
                                 }
                             }
                             else
                             {
                                 foreach (GXObisValueItem it in att.Values)
                                 {
                                     if (IsNumber(row[col]) && it.Value == Convert.ToInt32(row[col]))
                                     {
                                         row[col] = it.UIValue;
                                         break;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 dt.LoadDataRow(row, true);
             }
         }
     }
 }
예제 #18
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);
        }
예제 #19
0
        public void OnValueChanged(GXDLMSViewArguments arg)
        {
            GXDLMSAssociationLogicalName target = Target as GXDLMSAssociationLogicalName;

            //object list.
            if (arg.Index == 2)
            {
                GXDLMSObjectCollection items = target.ObjectList;
                ObjectsView.Items.Clear();
                if (items != null)
                {
                    foreach (GXDLMSObject it in items)
                    {
                        ListViewItem li = ObjectsView.Items.Add(it.ObjectType.ToString());
                        li.SubItems.Add(it.Version.ToString()); //Version
                        li.SubItems.Add(it.LogicalName);
                        li.Tag = it;
                        //access_rights: access_right
                        if (it is IGXDLMSBase)
                        {
                            string str = null;
                            //Show attribute access.
                            int cnt = (it as IGXDLMSBase).GetAttributeCount();
                            for (int pos = 1; pos != cnt + 1; ++pos)
                            {
                                if (str != null)
                                {
                                    str += ", ";
                                }
                                if (target.Version < 3)
                                {
                                    AccessMode mode = it.GetAccess(pos);
                                    str += pos.ToString() + " = " + mode;
                                }
                                else
                                {
                                    AccessMode3 mode = it.GetAccess3(pos);
                                    str += pos.ToString() + " = " + mode;
                                }
                            }
                            li.SubItems.Add(str);
                            //Show method access.
                            str = null;
                            cnt = (it as IGXDLMSBase).GetMethodCount();
                            for (int pos = 1; pos != cnt + 1; ++pos)
                            {
                                if (str != null)
                                {
                                    str += ", ";
                                }
                                if (target.Version < 3)
                                {
                                    MethodAccessMode mode = it.GetMethodAccess(pos);
                                    str += pos.ToString() + " = " + mode;
                                }
                                else
                                {
                                    MethodAccessMode3 mode = it.GetMethodAccess3(pos);
                                    str += pos.ToString() + " = " + mode;
                                }
                            }
                            li.SubItems.Add(str);
                        }
                    }
                }
            }
            //Associated partners ID.
            else if (arg.Index == 3)
            {
                ClientSAPTb.Text = Convert.ToString(target.ClientSAP);
                ServerSAPTb.Text = Convert.ToString(target.ServerSAP);
            }
            else if (arg.Index == 4)
            {
                try
                {
                    this.ApplicationContextIDCb.SelectedIndexChanged -= new System.EventHandler(this.ApplicationContextIDCb_SelectedIndexChanged);
                    ApplicationContextIDCb.Items.Clear();
                    if (target.ApplicationContextName.ContextId == ApplicationContextName.LogicalName ||
                        target.ApplicationContextName.ContextId == ApplicationContextName.LogicalNameWithCiphering)
                    {
                        ApplicationContextIDCb.Items.AddRange(new object[] {
                            ApplicationContextName.LogicalName, ApplicationContextName.LogicalNameWithCiphering
                        });
                    }
                    else
                    {
                        ApplicationContextIDCb.Items.AddRange(new object[] {
                            ApplicationContextName.ShortName, ApplicationContextName.ShortNameWithCiphering
                        });
                    }
                    // Application context name.
                    ApplicationJointISOCTTTb.Text            = Convert.ToString(target.ApplicationContextName.JointIsoCtt);
                    ApplicationCountryTb.Text                = Convert.ToString(target.ApplicationContextName.Country);
                    ApplicationCountryNameTb.Text            = Convert.ToString(target.ApplicationContextName.CountryName);
                    ApplicationIdentifiedOrganizationTb.Text = Convert.ToString(target.ApplicationContextName.IdentifiedOrganization);
                    ApplicationDLMSUATb.Text                        = Convert.ToString(target.ApplicationContextName.DlmsUA);
                    ApplicationContextTb.Text                       = Convert.ToString(target.ApplicationContextName.ApplicationContext);
                    ApplicationContextIDCb.SelectedItem             = target.ApplicationContextName.ContextId;
                    ApplicationRegistrationAuthorityCb.SelectedItem = FindCountry(target.ApplicationContextName.JointIsoCtt, target.ApplicationContextName.Country, target.ApplicationContextName.CountryName);
                }
                finally
                {
                    ApplicationContextIDCb.SelectedIndexChanged += new System.EventHandler(this.ApplicationContextIDCb_SelectedIndexChanged);
                }
            }
            else if (arg.Index == 5)
            {
                // xDLMS_context_info
                ShowConformance(target.XDLMSContextInfo.Conformance);
                MaxReceivePDUSizeTb.Text = target.XDLMSContextInfo.MaxReceivePduSize.ToString();
                MaxSendPDUSizeTb.Text    = target.XDLMSContextInfo.MaxSendPduSize.ToString();
                DLMSVersionNumberTB.Text = target.XDLMSContextInfo.DlmsVersionNumber.ToString();
                CypheringInfoTb.Text     = GXDLMSTranslator.ToHex(target.XDLMSContextInfo.CypheringInfo);
            }
            else if (arg.Index == 6)
            {
                Freeze = true;
                // authentication_mechanism_name
                AuthenticationJointISOCTTTb.Text            = Convert.ToString(target.AuthenticationMechanismName.JointIsoCtt);
                AuthenticationCountryTb.Text                = Convert.ToString(target.AuthenticationMechanismName.Country);
                AuthenticationCountryNameTb.Text            = Convert.ToString(target.AuthenticationMechanismName.CountryName);
                AuthenticationIdentifiedorganizationTb.Text = Convert.ToString(target.AuthenticationMechanismName.IdentifiedOrganization);
                AuthenticationDLMSUATb.Text        = Convert.ToString(target.AuthenticationMechanismName.DlmsUA);
                AuthenticationMechanismNameTb.Text = Convert.ToString(target.AuthenticationMechanismName.AuthenticationMechanismName);
                AuthenticationMechanismIdCb.Text   = Convert.ToString(target.AuthenticationMechanismName.MechanismId);
                AuthenticationRegistrationAuthorityCb.SelectedItem = FindCountry(target.AuthenticationMechanismName.JointIsoCtt, target.AuthenticationMechanismName.Country, target.AuthenticationMechanismName.CountryName);
                Freeze = false;
            }
            else if (arg.Index == 7)
            {
                //Secret.
                if (GXHelpers.IsAscii(target.Secret))
                {
                    SecretAsciiCb.Checked = true;
                    SecretTB.Text         = ASCIIEncoding.ASCII.GetString(target.Secret);
                }
                else
                {
                    SecretTB.Text = GXDLMSTranslator.ToHex(target.Secret);
                }
            }
            else if (arg.Index == 9)
            {
                SecuritySetupCb.Items.Clear();
                //security_setup_reference
                if (target.Parent != null)
                {
                    SecuritySetupCb.Items.Add("");
                    foreach (GXDLMSSecuritySetup it in target.Parent.GetObjects(ObjectType.SecuritySetup))
                    {
                        SecuritySetupCb.Items.Add(it);
                        if (target.SecuritySetupReference == it.LogicalName)
                        {
                            SecuritySetupCb.SelectedIndexChanged -= new System.EventHandler(this.SecuritySetupCb_SelectedIndexChanged);
                            SecuritySetupCb.SelectedItem          = it;
                            SecuritySetupCb.SelectedIndexChanged += new System.EventHandler(this.SecuritySetupCb_SelectedIndexChanged);
                        }
                    }
                }
                else
                {
                    GXDLMSSecuritySetup it = new GXDLMSSecuritySetup(target.SecuritySetupReference);
                    SecuritySetupCb.Items.Add(it);
                    SecuritySetupCb.SelectedIndexChanged -= new System.EventHandler(this.SecuritySetupCb_SelectedIndexChanged);
                    SecuritySetupCb.SelectedItem          = it;
                    SecuritySetupCb.SelectedIndexChanged += new System.EventHandler(this.SecuritySetupCb_SelectedIndexChanged);
                }
            }
            //User list.
            else if (arg.Index == 10)
            {
                List <KeyValuePair <byte, string> > items = target.UserList;
                UsersList.Items.Clear();
                if (items != null)
                {
                    foreach (KeyValuePair <byte, string> it in items)
                    {
                        ListViewItem li = UsersList.Items.Add(it.Key.ToString());
                        li.SubItems.Add(it.Value);
                        li.Tag = it.Key;
                    }
                }
            }
            else if (arg.Index == 11) //Current user
            {
                foreach (ListViewItem it in UsersList.Items)
                {
                    if ((byte)it.Tag == target.CurrentUser.Key)
                    {
                        it.Selected = true;
                    }
                    else if (it.Selected)
                    {
                        it.Selected = false;
                    }
                }
            }
        }
예제 #20
0
 void IGXDLMSBase.Save(GXXmlWriter writer)
 {
     writer.WriteElementString("Secret", GXDLMSTranslator.ToHex(Secret));
     writer.WriteElementString("SecuritySetupReference", SecuritySetupReference);
 }
        void UpdateData(DataTable dt)
        {
            Standard standard = Standard.DLMS;

            if (target.Parent != null && target.Parent.Parent is GXDLMSClient)
            {
                standard = ((GXDLMSClient)target.Parent.Parent).Standard;
            }
            List <object> rows = GXDLMSCompactData.GetData(target.TemplateDescription, target.Buffer, standard == Standard.Italy);

            if (structures)
            {
                List <object[]> data = new List <object[]>();
                foreach (List <object> r in rows)
                {
                    List <object> row   = new List <object>();
                    int           index = 0;
                    foreach (var it in target.CaptureObjects)
                    {
                        //If COSEM object is selected.
                        //Only few meters are supporting this.
                        if (it.Value.AttributeIndex == 0 && r[index] is List <object> )
                        {
                            //Values must be update to the list because there might be Register Scaler
                            //and it expects that scaler is read before value is updated.
                            GXDLMSObject obj = GXDLMSClient.CreateObject(it.Key.ObjectType);
                            byte         i2  = 1;
                            Dictionary <byte, object> list = new Dictionary <byte, object>();
                            foreach (object v in (r[index] as object[]))
                            {
                                list.Add(i2, v);
                                ++i2;
                            }
                            //Update values first.
                            for (byte i = 0; i != (obj as IGXDLMSBase).GetAttributeCount(); ++i)
                            {
                                ValueEventArgs ve = new ValueEventArgs(obj, i, 0, null);
                                ve.Value = list[i];
                                (obj as IGXDLMSBase).SetValue(null, ve);
                            }
                            //Show values.
                            for (byte i = 0; i != (obj as IGXDLMSBase).GetAttributeCount(); ++i)
                            {
                                row.Add(GetValue(obj.GetValues()[i]));
                            }
                        }
                        else
                        {
                            row.Add(GetValue(r[index]));
                        }
                        ++index;
                    }
                    data.Add(row.ToArray());
                }
                for (int pos = dt.Rows.Count; pos < data.Count; ++pos)
                {
                    object[] row = data[pos];
                    dt.LoadDataRow(row, true);
                }
            }
            else
            {
                for (int pos = dt.Rows.Count; pos < rows.Count; ++pos)
                {
                    List <object> row = (List <object>)rows[pos];
                    if (row != null)
                    {
                        for (int col = 0; col != row.Count; ++col)
                        {
                            if (row[col] is byte[])
                            {
                                if (pos < target.CaptureObjects.Count && target.CaptureObjects[col].Key.GetUIDataType(target.CaptureObjects[col].Value.AttributeIndex) == DataType.DateTime)
                                {
                                    row[col] = GXDLMSClient.ChangeType(row[col] as byte[], DataType.DateTime);
                                }
                                else
                                {
                                    row[col] = GXDLMSTranslator.ToHex((byte[])row[col], true);
                                }
                            }
                            else if (row[col] is Object[])
                            {
                                row[col] = GXDLMSTranslator.ValueToXml(row[col]);
                            }
                            else if (row[col] is List <Object> )
                            {
                                row[col] = GXDLMSTranslator.ValueToXml(row[col]);
                            }
                            else if (col < target.CaptureObjects.Count)
                            {
                                GXDLMSAttributeSettings att = target.CaptureObjects[col].Key.Attributes.Find(target.CaptureObjects[col].Value.AttributeIndex);
                                if (att != null && att.Values != null)
                                {
                                    if (att.Type == DataType.BitString && row[col] is string)
                                    {
                                        string str = (string)row[col];
                                        if (str.Length != 0 && (str[0] == '0' || str[0] == '1'))
                                        {
                                            StringBuilder sb   = new StringBuilder();
                                            int           pos2 = 0;
                                            foreach (char it in str)
                                            {
                                                if (it == '1')
                                                {
                                                    if (sb.Length != 0)
                                                    {
                                                        sb.Append(',');
                                                    }
                                                    sb.Append(att.Values[pos2].UIValue);
                                                }
                                                ++pos2;
                                                if (pos2 == att.Values.Count)
                                                {
                                                    break;
                                                }
                                            }
                                            row[col] = sb.ToString();
                                        }
                                    }
                                    else
                                    {
                                        foreach (GXObisValueItem it in att.Values)
                                        {
                                            if (IsNumber(row[col]) && it.Value == Convert.ToInt32(row[col]))
                                            {
                                                row[col] = it.UIValue;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (dt.Columns.Count != 0)
                        {
                            try
                            {
                                dt.LoadDataRow(row.ToArray(), true);
                            }
                            catch (Exception)
                            {
                                //It's OK if this fails.
                            }
                        }
                    }
                }
            }
        }
예제 #22
0
 /// <summary>
 /// Update certificates with server and client system title.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void UpdateBtn_Click(object sender, EventArgs e)
 {
     try
     {
         _checkSystemTitle = false;
         SecuritySuite ss     = (SecuritySuite)SecuritySuiteCb.SelectedItem;
         Ecc           scheme = ss == SecuritySuite.Suite1 ? Ecc.P256 : Ecc.P384;
         byte[]        tmp    = GXDLMSTranslator.HexToBytes(SystemTitle);
         if (tmp.Length != 0 && tmp.Length != 8)
         {
             throw new Exception("Client system title is invalid.");
         }
         string clientST = null;
         if (tmp.Length != 0)
         {
             clientST = "CN=" + GXDLMSTranslator.ToHex(tmp, false);
         }
         tmp = GXDLMSTranslator.HexToBytes(ServerSystemTitle);
         if (tmp.Length != 0 && tmp.Length != 8)
         {
             throw new Exception("Server system title is invalid.");
         }
         string serverST = null;
         if (tmp.Length != 0)
         {
             serverST = "CN=" + GXDLMSTranslator.ToHex(tmp, false);
         }
         ClientAgreementKeysCb.SelectedItem = null;
         ServerAgreementKeysCb.SelectedItem = null;
         ClientSigningKeysCb.SelectedItem   = null;
         ServerSigningKeysCb.SelectedItem   = null;
         if (clientST != null)
         {
             foreach (object tmp2 in ClientAgreementKeysCb.Items)
             {
                 if (tmp2 is KeyValuePair <GXPkcs8, GXx509Certificate> it)
                 {
                     if (it.Value != null && it.Value.PublicKey.Scheme == scheme && it.Value.Subject.Contains(clientST))
                     {
                         ClientAgreementKeysCb.SelectedItem = it;
                         break;
                     }
                 }
             }
             foreach (object tmp2 in ClientSigningKeysCb.Items)
             {
                 if (tmp2 is KeyValuePair <GXPkcs8, GXx509Certificate> it)
                 {
                     if (it.Value != null && it.Value.PublicKey.Scheme == scheme && it.Value.Subject.Contains(clientST))
                     {
                         ClientSigningKeysCb.SelectedItem = it;
                         break;
                     }
                 }
             }
         }
         if (serverST != null)
         {
             foreach (object tmp2 in ServerAgreementKeysCb.Items)
             {
                 if (tmp2 is KeyValuePair <GXPkcs8, GXx509Certificate> it)
                 {
                     if (it.Value != null && it.Value.PublicKey.Scheme == scheme && it.Value.Subject.Contains(serverST))
                     {
                         ServerAgreementKeysCb.SelectedItem = it;
                         break;
                     }
                 }
             }
             foreach (object tmp2 in ServerSigningKeysCb.Items)
             {
                 if (tmp2 is KeyValuePair <GXPkcs8, GXx509Certificate> it)
                 {
                     if (it.Value != null && it.Value.PublicKey.Scheme == scheme && it.Value.Subject.Contains(serverST))
                     {
                         ServerSigningKeysCb.SelectedItem = it;
                         break;
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(Parent, ex.Message);
     }
     finally
     {
         _checkSystemTitle = true;
     }
 }