public static byte[] GetAsHex(string value, bool ascii) { if (ascii) { return(ASCIIEncoding.ASCII.GetBytes(value)); } return(GXCommon.HexToBytes(value)); }
public GXNotifyClient(bool useLogicalNameReferencing, int interfaceType, string systemTitle, string blockCipherKey) { Notify = new GXReplyData(); Reply = new GXByteBuffer(); Client = new GXDLMSSecureClient(useLogicalNameReferencing, -1, -1, Authentication.None, null, (InterfaceType)interfaceType); Client.Ciphering.SystemTitle = GXCommon.HexToBytes(systemTitle); Client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(blockCipherKey); DataReceived = DateTime.MinValue; }
/// <summary> /// Convert the XML from the Gurux library to our business object <see cref="DataRow"/> /// </summary> /// <param name="XML">Gurux XML after parsing the HEX package</param> /// <returns></returns> internal override DataRow ParseXML(string XML) { DataRow data = new DataRow(); data.XML = XML; using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(XML))) { // Load the document and set the root element. XmlDocument doc = new XmlDocument(); doc.Load(ms); XmlNode root = doc.DocumentElement; //Zeitstempel XmlNode node = root.SelectSingleNode("NotificationBody/DataValue/Structure/OctetString[1]"); string accessDate = node.Attributes.GetNamedItem("Value").InnerText; GXDateTime dt = (GXDateTime)GXDLMSClient.ChangeType(GXCommon.HexToBytes(accessDate), DataType.DateTime, true); data.TimeStamp = dt.Value.DateTime; //Wirkenergie A+ data.ActiveEnergyPositive = UInt32.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt32[1]").Attributes.GetNamedItem("Value").InnerText); //Wirkenergie A- data.ActiveEnergyNegative = UInt32.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt32[2]").Attributes.GetNamedItem("Value").InnerText); //Momentanleistung P+ data.ActivePowerPositive = UInt32.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt32[3]").Attributes.GetNamedItem("Value").InnerText); //Momentanleistung P- data.ActivePowerNegative = UInt32.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt32[4]").Attributes.GetNamedItem("Value").InnerText); //Spannung L1 data.Voltage1 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[1]").Attributes.GetNamedItem("Value").InnerText); //Spannung L2 data.Voltage2 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[2]").Attributes.GetNamedItem("Value").InnerText); //Spannung L3 data.Voltage3 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[3]").Attributes.GetNamedItem("Value").InnerText); //Strom L1 data.Current1 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[4]").Attributes.GetNamedItem("Value").InnerText); //Strom L2 data.Current2 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[5]").Attributes.GetNamedItem("Value").InnerText); //Strom L3 data.Current3 = UInt16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/UInt16[6]").Attributes.GetNamedItem("Value").InnerText); //Leistungsfaktor data.PowerFactor = Int16.Parse(root.SelectSingleNode("NotificationBody/DataValue/Structure/Int16[1]").Attributes.GetNamedItem("Value").InnerText); //Zählernummer //Todo: there seems to be an issue to extract the right meter number - only looking at the HEX values, the last view characters are far outside of the normal ASCII range :/ data.MeterNumber = ConvertHexToString(root.SelectSingleNode("NotificationBody/DataValue/Structure/OctetString[13]").Attributes.GetNamedItem("Value").InnerText); //data.MeterNumber = (string)GXDLMSClient.ChangeType(GXCommon.HexToBytes(root.SelectSingleNode("NotificationBody/DataValue/Structure/OctetString[13]").Attributes.GetNamedItem("Value").InnerText), DataType.Str//ing); } return(data); }
void IGXDLMSBase.Load(GXXmlReader reader) { ReportingSystemList.Clear(); if (reader.IsStartElement("ReportingSystems", true)) { while (reader.IsStartElement("Item", false)) { ReportingSystemList.Add(GXCommon.HexToBytes(reader.ReadElementContentAsString("Item"))); } } }
/// <summary> /// Update security settings to the translator. /// </summary> private void UpdateSecurity() { translator.Security = (Security)Enum.Parse(typeof(Security), SecurityCB.SelectedItem.ToString()); translator.SystemTitle = GXCommon.HexToBytes(GetAsHex(SystemTitleTB.Text, SystemTitleAsciiCb.Checked)); translator.BlockCipherKey = GXCommon.HexToBytes(GetAsHex(BlockCipherKeyTB.Text, BlockCipherKeyAsciiCb.Checked)); translator.AuthenticationKey = GXCommon.HexToBytes(GetAsHex(AuthenticationKeyTB.Text, AuthenticationKeyAsciiCb.Checked)); translator.InvocationCounter = UInt32.Parse(InvocationCounterTB.Text); translator.ServerSystemTitle = GXCommon.HexToBytes(GetAsHex(ServerSystemTitleTB.Text, ServerSystemTitleAsciiCb.Checked)); translator.DedicatedKey = GXCommon.HexToBytes(GetAsHex(DedicatedKeyTb.Text, DedicatedKeyAsciiCb.Checked)); translator.DedicatedKey = GXCommon.HexToBytes(GetAsHex(DedicatedKeyTb.Text, DedicatedKeyAsciiCb.Checked)); }
/// <summary> /// Convert ASN1 PDU bytes to XML. /// </summary> /// <param name="value">Bytes to convert. </param> /// <returns> Converted XML. </returns> public static string PduToXml(string value) { if (value == null || value.Length == 0) { return(""); } if (!GXCommon.IsHexString(value)) { return(PduToXml(GXCommon.FromBase64(value))); } return(PduToXml(new GXByteBuffer(GXCommon.HexToBytes(value)))); }
private void OKBtn_Click(object sender, EventArgs e) { try { if (NameTB.Text.Length == 0) { throw new Exception("Invalid manufacturer name."); } if (ManufacturerIdTB.Text.Length != 3) { throw new Exception("Invalid manufacturer identification."); } if (ManufacturerIdTB.Enabled && Manufacturers.FindByIdentification(ManufacturerIdTB.Text) != null) { throw new Exception("Manufacturer identification already exists."); } if (!SerialNumberFormulaTB.ReadOnly && SerialNumberFormulaTB.Text.Length == 0) { throw new Exception("Invalid Serial Number."); } Manufacturer.Name = NameTB.Text; Manufacturer.Identification = ManufacturerIdTB.Text; Manufacturer.UseLogicalNameReferencing = UseLNCB.Checked; Manufacturer.UseIEC47 = UseIEC47CB.Checked; Manufacturer.StartProtocol = (StartProtocolType)StartProtocolCB.SelectedItem; Manufacturer.Standard = (Standard)StandardCb.SelectedItem; GXAuthentication authentication = Manufacturer.GetActiveAuthentication(); authentication.ClientAddress = Convert.ToInt32(this.ClientAddTB.Value); //Save server values. UpdateServer((GXServerAddress)ServerAddressTypeCB.SelectedItem); Manufacturer.WebAddress = WebAddressTB.Text; if (!string.IsNullOrEmpty(InfoTB.Text)) { Manufacturer.Info = Convert.ToBase64String(ASCIIEncoding.UTF8.GetBytes(InfoTB.Text)); } else { Manufacturer.Info = null; } Manufacturer.Security = (Security)SecurityCB.SelectedItem; Manufacturer.SystemTitle = GXCommon.HexToBytes(DevicePropertiesForm.GetAsHex(SystemTitleTB.Text, SystemTitleAsciiCb.Checked)); Manufacturer.BlockCipherKey = GXCommon.HexToBytes(DevicePropertiesForm.GetAsHex(BlockCipherKeyTB.Text, BlockCipherKeyAsciiCb.Checked)); Manufacturer.AuthenticationKey = GXCommon.HexToBytes(DevicePropertiesForm.GetAsHex(AuthenticationKeyTB.Text, AuthenticationKeyAsciiCb.Checked)); } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); this.DialogResult = DialogResult.None; } }
object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e) { if (e.Index == 1) { return(GXCommon.LogicalNameToBytes(LogicalName)); } if (e.Index == 2) { return(GXCommon.HexToBytes(MacAddress)); } e.Error = ErrorCode.ReadWriteDenied; return(null); }
private string ConvertHexToString(string hex) { string value = ""; foreach (string cc in BitConverter.ToString((byte[])GXCommon.HexToBytes(hex)).Split("-")) { int n = Convert.ToInt32(cc, 16); char c = (char)n; value += c.ToString(); } return(value); }
private void OKBtn_Click(object sender, EventArgs e) { try { Target.Security = (Security)SecurityCB.SelectedItem; Target.SystemTitle = GXCommon.HexToBytes(SystemTitleTB.Text, true); Target.BlockCipherKey = GXCommon.HexToBytes(BlockCipherKeyTB.Text, true); Target.AuthenticationKey = GXCommon.HexToBytes(AuthenticationKeyTB.Text, true); } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); DialogResult = DialogResult.None; } }
private void PasswordBtn_Click(object sender, EventArgs e) { try { GXCiphering c = new GXCiphering(null); c.SystemTitle = GXCommon.HexToBytes(GetAsHex(SystemTitleTB.Text, SystemTitleAsciiCb.Checked)); c.BlockCipherKey = GXCommon.HexToBytes(GetAsHex(BlockCipherKeyTB.Text, BlockCipherKeyAsciiCb.Checked)); c.AuthenticationKey = GXCommon.HexToBytes(GetAsHex(AuthenticationKeyTB.Text, AuthenticationKeyAsciiCb.Checked)); c.InvocationCounter = UInt32.Parse(InvocationCounterTB.Text); MessageBox.Show(this, GXCommon.ToHex(c.GenerateGmacPassword(GXCommon.HexToBytes(GetAsHex(ChallengeTb.Text, ChallengeAsciiCb.Checked))), true)); } catch (Exception ex) { MessageBox.Show(this, ex.Message); } }
void IGXDLMSBase.Load(GXXmlReader reader) { LnId = (short)reader.ReadElementContentAsInt("LnId"); LsId = (byte)reader.ReadElementContentAsInt("LsId"); SId = (byte)reader.ReadElementContentAsInt("SId"); Sna = GXCommon.HexToBytes(reader.ReadElementContentAsString("SNa")); State = (MacState)reader.ReadElementContentAsInt("State"); ScpLength = (byte)reader.ReadElementContentAsInt("ScpLength"); NodeHierarchyLevel = (byte)reader.ReadElementContentAsInt("NodeHierarchyLevel"); BeaconSlotCount = (byte)reader.ReadElementContentAsInt("BeaconSlotCount"); BeaconRxSlot = (byte)reader.ReadElementContentAsInt("BeaconRxSlot"); BeaconTxSlot = (byte)reader.ReadElementContentAsInt("BeaconTxSlot"); BeaconRxFrequency = (byte)reader.ReadElementContentAsInt("BeaconRxFrequency"); BeaconTxFrequency = (byte)reader.ReadElementContentAsInt("BeaconTxFrequency"); Capabilities = (MacCapabilities)reader.ReadElementContentAsInt("Capabilities"); }
void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e) { switch (e.Index) { case 1: LogicalName = GXCommon.ToLogicalName(e.Value); break; case 2: if (e.Value is byte[]) { Buffer = (byte[])e.Value; } else if (e.Value is string) { Buffer = GXCommon.HexToBytes((string)e.Value); } break; case 3: SetCaptureObjects(settings, CaptureObjects, (object[])e.Value); if (settings.IsServer) { UpdateTemplateDescription(); } break; case 4: TemplateId = (byte)e.Value; break; case 5: TemplateDescription = (byte[])e.Value; break; case 6: CaptureMethod = (CaptureMethod)Convert.ToByte(e.Value); break; default: e.Error = ErrorCode.ReadWriteDenied; break; } }
/// <summary> /// Encrypt Elster PW for A1700. /// </summary> /// <param name="password"></param> /// <param name="seed"></param> /// <returns></returns> string ElsterEncrypt(string password, string seed) { //Convert hex string to byte array. byte[] s = GXCommon.HexToBytes(seed, false); byte[] crypted = new byte[8]; for (int pos = 0; pos != 8; ++pos) { crypted[pos] = (byte)(password[pos] ^ s[pos]); } int last = crypted[7]; for (int pos = 0; pos != 8; ++pos) { long tmp = (crypted[pos] + last) & 0x800000FF; crypted[pos] = (byte)((crypted[pos] + last) & 0xFF); last = crypted[pos]; } return(GXCommon.ToHex(crypted, false)); }
private void OKBtn_Click(object sender, EventArgs e) { try { if (HexRB.Checked) { Target.SharedSecret = GXCommon.HexToBytes(this.SecretTB.Text, true); } else { Target.SharedSecret = ASCIIEncoding.ASCII.GetBytes(this.SecretTB.Text); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); DialogResult = DialogResult.None; } }
public ActionResult <ListDevicesResponse> Post(ListDevices request) { ListDevicesResponse ret = new ListDevicesResponse(); GXSelectArgs arg = GXSelectArgs.SelectAll <GXDevice>(); arg.Where.And <GXDevice>(q => q.Removed == DateTime.MinValue); if ((request.Targets & TargetType.Attribute) != 0) { arg.Columns.Add <GXObject>(); arg.Columns.Add <GXAttribute>(); arg.Joins.AddLeftJoin <GXDevice, GXObject>(d => d.Id, o => o.DeviceId); arg.Joins.AddLeftJoin <GXObject, GXAttribute>(o => o.Id, a => a.ObjectId); arg.Where.And <GXObject>(q => q.Removed == DateTime.MinValue); arg.Where.And <GXAttribute>(q => q.Removed == DateTime.MinValue); } else if ((request.Targets & TargetType.Object) != 0) { arg.Columns.Add <GXObject>(); arg.Joins.AddLeftJoin <GXDevice, GXObject>(d => d.Id, o => o.DeviceId); arg.Where.And <GXObject>(q => q.Removed == DateTime.MinValue); } byte[] st = GXCommon.HexToBytes(request.SystemTitle); if (st.Length == 8) { string str = GXCommon.ToHex(st, false); arg.Where.And <GXDevice>(q => q.DeviceSystemTitle.Equals(str)); } else if (!string.IsNullOrEmpty(request.Name)) { string name = request.Name; arg.Where.And <GXDevice>(q => q.Name.Contains(name)); } else if (request.Ids != null) { arg.Where.And <GXDevice>(q => request.Ids.Contains(q.Id)); } ret.Devices = host.Connection.Select <GXDevice>(arg).ToArray(); return(ret); }
private GXMacAvailableSwitch[] LoadAvailableSwitches(GXXmlReader reader) { List <GXMacAvailableSwitch> list = new List <GXMacAvailableSwitch>(); if (reader.IsStartElement("AvailableSwitches", true)) { while (reader.IsStartElement("Item", true)) { GXMacAvailableSwitch it = new GXMacAvailableSwitch(); list.Add(it); it.Sna = GXCommon.HexToBytes(reader.ReadElementContentAsString("Sna")); it.LsId = (Int16)reader.ReadElementContentAsInt("LsId"); it.Level = (sbyte)reader.ReadElementContentAsInt("Level"); it.RxLevel = (sbyte)reader.ReadElementContentAsInt("RxLevel"); it.RxSnr = (sbyte)reader.ReadElementContentAsInt("RxSnr"); } reader.ReadEndElement("AvailableSwitches"); } return(list.ToArray()); }
/// <summary> /// Get logical names from client request. /// </summary> /// <param name="nodes">XML nodes.</param> /// <returns>Collection of logical names.</returns> private static void GetLN(GXDLMSObjectCollection objects, List <ValueEventArgs> targets, XmlNodeList nodes) { List <ValueEventArgs> list = new List <ValueEventArgs>(); foreach (XmlNode node in nodes) { ObjectType ot; string classId, instanceId; int attributeId; if (node.Name == "cosem-attribute-descriptor") { classId = node.ChildNodes[0].ChildNodes[0].InnerText; instanceId = node.ChildNodes[1].ChildNodes[0].InnerText; instanceId = GXDLMSObject.ToLogicalName(GXCommon.HexToBytes(instanceId)); attributeId = int.Parse(node.ChildNodes[2].ChildNodes[0].InnerText); ot = (ObjectType)int.Parse(classId); GXDLMSObject t = objects.FindByLN(ot, instanceId); if (t == null) { t = GXDLMSClient.CreateDLMSObject((int)ot, 0, 0, instanceId, null); } ValueEventArgs ve = new ValueEventArgs(t, attributeId, 0, null); targets.Add(ve); System.Diagnostics.Debug.WriteLine(ot + " " + instanceId); } else if ("AttributeDescriptorList".Equals(node.Name)) { foreach (XmlNode it in node.ChildNodes[1].ChildNodes) { classId = it.ChildNodes[0].InnerText; instanceId = it.ChildNodes[1].InnerText; instanceId = GXDLMSObject.ToLogicalName(GXCommon.HexToBytes(instanceId)); attributeId = int.Parse(it.ChildNodes[2].InnerText); ot = (ObjectType)int.Parse(classId); ValueEventArgs ve = new ValueEventArgs(objects.FindByLN(ot, instanceId), attributeId, 0, null); targets.Add(ve); System.Diagnostics.Debug.WriteLine(ot + " " + instanceId); } } } }
private void OnChange(object sender, EventArgs e) { try { byte[] data; if (HexRB.Checked) { data = ASCIIEncoding.ASCII.GetBytes(this.SecretTB.Text); this.SecretTB.Text = GXCommon.ToHex(data, true); } else { data = GXCommon.HexToBytes(this.SecretTB.Text, true); this.SecretTB.Text = ASCIIEncoding.ASCII.GetString(data); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
void IGXDLMSBase.Load(GXXmlReader reader) { Token = GXCommon.HexToBytes(reader.ReadElementContentAsString("Token")); string tmp = reader.ReadElementContentAsString("Time"); if (tmp != null) { Time = new GXDateTime(tmp, System.Globalization.CultureInfo.InvariantCulture); } Descriptions.Clear(); if (reader.IsStartElement("Descriptions", true)) { while (reader.IsStartElement("Item", true)) { Descriptions.Add(reader.ReadElementContentAsString("Name")); } reader.ReadEndElement("Descriptions"); } DeliveryMethod = (TokenDelivery)reader.ReadElementContentAsInt("DeliveryMethod"); StatusCode = (TokenStatusCode)reader.ReadElementContentAsInt("Status"); DataValue = reader.ReadElementContentAsString("Data"); }
private GXMacDirectTable[] LoadDirectTable(GXXmlReader reader) { List <GXMacDirectTable> list = new List <GXMacDirectTable>(); if (reader.IsStartElement("DirectTable", true)) { while (reader.IsStartElement("Item", true)) { GXMacDirectTable it = new GXMacDirectTable(); list.Add(it); it.SourceSId = (Int16)reader.ReadElementContentAsInt("SourceSId"); it.SourceLnId = (Int16)reader.ReadElementContentAsInt("SourceLnId"); it.SourceLcId = (Int16)reader.ReadElementContentAsInt("SourceLcId"); it.DestinationSId = (Int16)reader.ReadElementContentAsInt("DestinationSId"); it.DestinationLnId = (Int16)reader.ReadElementContentAsInt("DestinationLnId"); it.DestinationLcId = (Int16)reader.ReadElementContentAsInt("DestinationLcId"); it.Did = GXCommon.HexToBytes(reader.ReadElementContentAsString("Did")); } reader.ReadEndElement("DirectTable"); } return(list.ToArray()); }
private void AsciiRB_CheckedChanged(object sender, EventArgs e) { try { if (HexRB.Checked) { SystemTitleTB.Text = GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(SystemTitleTB.Text), true); BlockCipherKeyTB.Text = GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(BlockCipherKeyTB.Text), true); AuthenticationKeyTB.Text = GXCommon.ToHex(ASCIIEncoding.ASCII.GetBytes(AuthenticationKeyTB.Text), true); } else { SystemTitleTB.Text = ASCIIEncoding.ASCII.GetString(GXCommon.HexToBytes(SystemTitleTB.Text)); BlockCipherKeyTB.Text = ASCIIEncoding.ASCII.GetString(GXCommon.HexToBytes(BlockCipherKeyTB.Text)); AuthenticationKeyTB.Text = ASCIIEncoding.ASCII.GetString(GXCommon.HexToBytes(AuthenticationKeyTB.Text)); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); } }
/// <summary> /// Accept changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OKBtn_Click(object sender, EventArgs e) { try { _eventsTranslator.SystemTitle = GXCommon.HexToBytes(GetAsHex(SystemTitleTB.Text, SystemTitleAsciiCb.Checked)); _eventsTranslator.BlockCipherKey = GXCommon.HexToBytes(GetAsHex(BlockCipherKeyTB.Text, BlockCipherKeyAsciiCb.Checked)); _eventsTranslator.AuthenticationKey = GXCommon.HexToBytes(GetAsHex(AuthenticationKeyTB.Text, AuthenticationKeyAsciiCb.Checked)); (notifications as IGXPropertyPage).Apply(); foreach (IGXSettingsPage it in MediaPropertiesForm) { it.Apply(); } //Handle external medias. Properties.Settings.Default.ExternalMedias = ""; bool first = true; foreach (ListViewItem it in MediaList.Items) { if (first) { first = false; } else { Properties.Settings.Default.ExternalMedias = ";"; } Properties.Settings.Default.ExternalMedias += it.SubItems[2].Text; } if (checkUpdates != null) { checkUpdates.Cancel(); } Properties.Settings.Default.GeneratorAddress = CertificationServerTb.Text; } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); this.DialogResult = DialogResult.None; } }
void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e) { if (e.Index == 1) { LogicalName = GXCommon.ToLogicalName(e.Value); } else if (e.Index == 2) { if (e.Value is byte[]) { MacAddress = GXCommon.ToHex((byte[])e.Value, true); MacAddress = MacAddress.Replace(' ', ':'); } else { MacAddress = GXCommon.ToHex(GXCommon.HexToBytes((string)e.Value), true); MacAddress = MacAddress.Replace(' ', ':'); } } else { e.Error = ErrorCode.ReadWriteDenied; } }
private GXMacPhyCommunication[] LoadCommunications(GXXmlReader reader) { List <GXMacPhyCommunication> list = new List <GXMacPhyCommunication>(); if (reader.IsStartElement("Communications", true)) { while (reader.IsStartElement("Item", true)) { GXMacPhyCommunication it = new GXMacPhyCommunication(); list.Add(it); it.Eui = GXCommon.HexToBytes(reader.ReadElementContentAsString("Eui")); it.TxPower = (sbyte)reader.ReadElementContentAsInt("TxPower"); it.TxCoding = (sbyte)reader.ReadElementContentAsInt("TxCoding"); it.RxCoding = (sbyte)reader.ReadElementContentAsInt("RxCoding"); it.RxLvl = (sbyte)reader.ReadElementContentAsInt("RxLvl"); it.Snr = (sbyte)reader.ReadElementContentAsInt("Snr"); it.TxPowerModified = (sbyte)reader.ReadElementContentAsInt("TxPowerModified"); it.TxCodingModified = (sbyte)reader.ReadElementContentAsInt("TxCodingModified"); it.RxCodingModified = (sbyte)reader.ReadElementContentAsInt("RxCodingModified"); } reader.ReadEndElement("Communications"); } return(list.ToArray()); }
private void OKBtn_Click(object sender, EventArgs e) { try { Target.Security = (Security)SecurityCB.SelectedItem; if (HexRB.Checked) { Target.SystemTitle = GXCommon.HexToBytes(SystemTitleTB.Text); Target.BlockCipherKey = GXCommon.HexToBytes(BlockCipherKeyTB.Text); Target.AuthenticationKey = GXCommon.HexToBytes(AuthenticationKeyTB.Text); } else { Target.SystemTitle = ASCIIEncoding.ASCII.GetBytes(SystemTitleTB.Text); Target.BlockCipherKey = ASCIIEncoding.ASCII.GetBytes(BlockCipherKeyTB.Text); Target.AuthenticationKey = ASCIIEncoding.ASCII.GetBytes(AuthenticationKeyTB.Text); } } catch (Exception Ex) { GXDLMS.Common.Error.ShowError(this, Ex); DialogResult = DialogResult.None; } }
object IGXDLMSBase.GetValue(GXDLMSSettings settings, ValueEventArgs e) { if (e.Index == 1) { return(GXCommon.LogicalNameToBytes(LogicalName)); } if (e.Index == 2) { if (CalendarNameActive == null) { return(null); } if (IsSec()) { return(GXCommon.HexToBytes(CalendarNameActive)); } return(ASCIIEncoding.ASCII.GetBytes(CalendarNameActive)); } if (e.Index == 3) { e.ByteArray = true; bool useOctectString = settings.Standard != Standard.SaudiArabia; return(GetSeasonProfile(settings, SeasonProfileActive, useOctectString)); } if (e.Index == 4) { e.ByteArray = true; return(GetWeekProfileTable(settings, WeekProfileTableActive)); } if (e.Index == 5) { e.ByteArray = true; return(GetDayProfileTable(settings, DayProfileTableActive)); } if (e.Index == 6) { if (CalendarNamePassive == null) { return(null); } if (IsSec()) { return(GXCommon.HexToBytes(CalendarNamePassive)); } return(ASCIIEncoding.ASCII.GetBytes(CalendarNamePassive)); } if (e.Index == 7) { e.ByteArray = true; bool useOctectString = settings.Standard != Standard.SaudiArabia; return(GetSeasonProfile(settings, SeasonProfilePassive, useOctectString)); } if (e.Index == 8) { e.ByteArray = true; return(GetWeekProfileTable(settings, WeekProfileTablePassive)); } if (e.Index == 9) { e.ByteArray = true; return(GetDayProfileTable(settings, DayProfileTablePassive)); } if (e.Index == 10) { return(Time); } e.Error = ErrorCode.ReadWriteDenied; return(null); }
public static int GetParameters(string[] args, Settings settings) { string[] tmp; List <GXCmdParameter> parameters = GXCommon.GetParameters(args, "h:p:c:s:r:iIt:a:wP:g:S:C:n:v:o:T:A:B:D:d:l:F:"); GXNet net = null; foreach (GXCmdParameter it in parameters) { switch (it.Tag) { case 'w': settings.client.InterfaceType = InterfaceType.WRAPPER; break; 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': //IEC. settings.iec = true; 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 { 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 { 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 '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 '?': 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."); default: ShowHelp(); return(1); } default: ShowHelp(); return(1); } } if (settings.media == null) { ShowHelp(); return(1); } return(0); }
/// <summary> /// Change DB value type. /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> static public object ChangeType(object value, Type type) { if (value == null || value is DBNull) { return(null); } if (type == typeof(byte[])) { if (value is string) { return(GXCommon.HexToBytes((string)value, false)); } return(GXCommon.HexToBytes(ASCIIEncoding.ASCII.GetString((byte[])value), false)); } //Date times are saved in UTC format. if (type == typeof(DateTime)) { DateTime dt = (DateTime)Convert.ChangeType(value, type); if (dt == DateTime.MinValue) { return(dt); } //Milliseconst are not saved. if (dt.Ticks == DateTime.MaxValue.AddTicks(-9999999).Ticks) { return(DateTime.MaxValue); } dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc); return(dt.ToLocalTime()); } if (value.GetType() == type) { return(value); } if (type == typeof(Guid)) { if (value is string) { Guid g = new Guid((string)value); return(g); } } else if (type.IsEnum) { if (value is string) { return(Enum.Parse(type, (string)value)); } return(Enum.Parse(type, value.ToString())); } else if (type == typeof(System.Decimal)) { if (Convert.ToDouble(value) == -7.9228162514264338E+28) { return(System.Decimal.MinValue); } if (Convert.ToDouble(value) == 7.9228162514264338E+28) { return(System.Decimal.MaxValue); } Convert.ToDecimal(value); } else if (type == typeof(Int64)) { if (value is double) { if ((double)value == 9.2233720368547758E+18) { return(Int64.MaxValue); } } } else if (type == typeof(UInt64)) { if (value is double) { if ((double)value == 1.8446744073709552E+19) { return(UInt64.MaxValue); } } } else if (type == typeof(TimeSpan)) { return(new TimeSpan(Convert.ToInt64(value) * 10000)); } else if (type == typeof(DateTimeOffset)) { DateTime dt = (DateTime)Convert.ChangeType(value, typeof(DateTime)); dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc); return(new DateTimeOffset(dt.ToLocalTime())); } //If nullable. if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>)) { if (value == null) { return(null); } Type tp = Nullable.GetUnderlyingType(type); //Date times are saved in UTC format. if (tp == typeof(DateTime)) { DateTime dt = (DateTime)Convert.ChangeType(value, tp); dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc); return(dt.ToLocalTime()); } if (value.GetType() != tp) { return(ChangeType(value, tp)); } return(value); } if (type.IsArray) { Type pt = GXInternal.GetPropertyType(type); string[] tmp = ((string)value).Split(new char[] { ';' }); Array items = Array.CreateInstance(pt, tmp.Length); int pos2 = -1; foreach (string it in tmp) { items.SetValue(GXInternal.ChangeType(it, pt), ++pos2); } return(items); } if (type == typeof(Type)) { return(Type.GetType(value.ToString())); } return(Convert.ChangeType(value, type)); }
/// <summary> /// Read data from the meter. /// </summary> private static void ReadMeter(object parameter) { GXDLMSReader reader = null; System.Net.Http.HttpClient httpClient = Helpers.client; using (GXNet media = (GXNet)parameter) { try { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true) .Build(); ListenerOptions listener = config.GetSection("Listener").Get <ListenerOptions>(); GXDLMSObjectCollection objects = new GXDLMSObjectCollection(); GXDLMSSecureClient client = new GXDLMSSecureClient(listener.UseLogicalNameReferencing, listener.ClientAddress, listener.ServerAddress, (Authentication)listener.Authentication, listener.Password, (InterfaceType)listener.Interface); reader = new GXDLMSReader(client, media, _logger); GXDLMSData ldn = new GXDLMSData("0.0.42.0.0.255"); ldn.SetUIDataType(2, DataType.String); reader.InitializeConnection(); reader.Read(ldn, 2); Console.WriteLine("Meter connected: " + ldn.Value); //Find device. GXDevice dev = null; ListDevicesResponse devs = null; { using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices() { Name = (string)ldn.Value }).Result) { Helpers.CheckStatus(response); devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result; } //If device is unknown. if (devs.Devices.Length == 0) { if (listener.DefaultDeviceTemplate == 0) { string str = "Unknown Meter try to connect to the Gurux.DLMS.AMI server: " + ldn.Value; Console.WriteLine(str); AddSystemError info = new AddSystemError(); info.Error = new GXSystemError() { Error = str }; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result) { Helpers.CheckStatus(response); } return; } ListDeviceTemplates lt = new ListDeviceTemplates() { Ids = new UInt64[] { listener.DefaultDeviceTemplate } }; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/template/ListDeviceTemplates", lt).Result) { Helpers.CheckStatus(response); ListDeviceTemplatesResponse ret = response.Content.ReadAsAsync <ListDeviceTemplatesResponse>().Result; if (ret.Devices.Length != 1) { throw new Exception("DefaultDeviceTemplate value is invalid: " + listener.DefaultDeviceTemplate); } dev = new GXDevice(); GXDevice.Copy(dev, ret.Devices[0]); dev.Name = Convert.ToString(ldn.Value); dev.TemplateId = listener.DefaultDeviceTemplate; dev.Manufacturer = ret.Devices[0].Name; } dev.Dynamic = true; UpdateDevice update = new UpdateDevice(); update.Device = dev; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/UpdateDevice", update).Result) { Helpers.CheckStatus(response); UpdateDeviceResponse r = response.Content.ReadAsAsync <UpdateDeviceResponse>().Result; dev.Id = r.DeviceId; } using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/device/ListDevices", new ListDevices() { Ids = new UInt64[] { dev.Id } }).Result) { Helpers.CheckStatus(response); devs = response.Content.ReadAsAsync <ListDevicesResponse>().Result; } } else if (devs.Devices.Length != 1) { throw new Exception("There are multiple devices with same name: " + ldn.Value); } else { dev = devs.Devices[0]; if (dev.Security != Security.None) { Console.WriteLine("Reading frame counter."); GXDLMSData fc = new GXDLMSData(listener.InvocationCounter); reader.Read(fc, 2); dev.InvocationCounter = 1 + Convert.ToUInt32(fc.Value); Console.WriteLine("Device ID: " + dev.Id + " LDN: " + (string)ldn.Value); Console.WriteLine("Frame counter: " + dev.FrameCounter); } GetNextTaskResponse ret; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/GetNextTask", new GetNextTask() { Listener = true, DeviceId = dev.Id }).Result) { Helpers.CheckStatus(response); ret = response.Content.ReadAsAsync <GetNextTaskResponse>().Result; } if (ret.Tasks == null || ret.Tasks.Length == 0) { Console.WriteLine("No tasks to execute"); } else { Console.WriteLine("Task count: " + ret.Tasks.Length); if (client.ClientAddress != dev.ClientAddress || dev.Security != Security.None) { reader.Release(); reader.Disconnect(); client = new GXDLMSSecureClient(dev.UseLogicalNameReferencing, dev.ClientAddress, dev.PhysicalAddress, (Authentication)dev.Authentication, dev.Password, dev.InterfaceType); client.UtcTimeZone = dev.UtcTimeZone; client.Standard = (Standard)dev.Standard; if (dev.Conformance != 0) { client.ProposedConformance = (Conformance)dev.Conformance; } client.Priority = dev.Priority; client.ServiceClass = dev.ServiceClass; client.Ciphering.SystemTitle = GXCommon.HexToBytes(dev.ClientSystemTitle); client.Ciphering.BlockCipherKey = GXCommon.HexToBytes(dev.BlockCipherKey); client.Ciphering.AuthenticationKey = GXCommon.HexToBytes(dev.AuthenticationKey); client.ServerSystemTitle = GXCommon.HexToBytes(dev.DeviceSystemTitle); client.Ciphering.InvocationCounter = dev.InvocationCounter; client.Ciphering.Security = (Security)dev.Security; reader = new GXDLMSReader(client, media, _logger); reader.InitializeConnection(); } List <GXValue> values = new List <GXValue>(); foreach (GXTask task in ret.Tasks) { GXDLMSObject obj = GXDLMSClient.CreateObject((ObjectType)task.Object.ObjectType); obj.LogicalName = task.Object.LogicalName; try { if (task.TaskType == TaskType.Write) { if (obj.LogicalName == "0.0.1.1.0.255" && task.Index == 2) { client.UpdateValue(obj, task.Index, GXDateTime.ToUnixTime(DateTime.UtcNow)); } else { client.UpdateValue(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data)); } reader.Write(obj, task.Index); } else if (task.TaskType == TaskType.Action) { reader.Method(obj, task.Index, GXDLMSTranslator.XmlToValue(task.Data), DataType.None); } else if (task.TaskType == TaskType.Read) { Reader.Reader.Read(null, httpClient, reader, task, media, obj); } } catch (Exception ex) { task.Result = ex.Message; AddError error = new AddError(); error.Error = new GXError() { DeviceId = dev.Id, Error = "Failed to " + task.TaskType + " " + task.Object.LogicalName + ":" + task.Index + ". " + ex.Message }; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/error/AddError", error).Result) { Helpers.CheckStatus(response); response.Content.ReadAsAsync <AddErrorResponse>(); } } using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/task/TaskReady", new TaskReady() { Tasks = new GXTask[] { task } }).Result) { Helpers.CheckStatus(response); } } } } } } catch (Exception ex) { try { AddSystemError info = new AddSystemError(); info.Error = new GXSystemError() { Error = ex.Message }; using (System.Net.Http.HttpResponseMessage response = httpClient.PostAsJsonAsync(Startup.ServerAddress + "/api/SystemError/AddSystemError", info).Result) { Helpers.CheckStatus(response); } } catch (Exception ex2) { } } finally { if (reader != null) { reader.Close(); } } } }